jscript: Don't leave current scope in return statement before evaluating the expression.
[wine] / dlls / winmm / mci.c
1 /*
2  * MCI internal functions
3  *
4  * Copyright 1998/1999 Eric Pouech
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 /* TODO:
22  * - implement WINMM (32bit) multitasking and use it in all MCI drivers
23  *   instead of the home grown one 
24  * - 16bit mmTaskXXX functions are currently broken because the 16
25  *   loader does not support binary command lines => provide Wine's
26  *   own mmtask.tsk not using binary command line.
27  * - correctly handle the MCI_ALL_DEVICE_ID in functions.
28  * - finish mapping 16 <=> 32 of MCI structures and commands
29  * - implement auto-open feature (ie, when a string command is issued
30  *   for a not yet opened device, MCI automatically opens it) 
31  * - use a default registry setting to replace the [mci] section in
32  *   configuration file (layout of info in registry should be compatible
33  *   with all Windows' version - which use different layouts of course)
34  * - implement automatic open
35  *      + only works on string interface, on regular devices (don't work on all
36  *        nor custom devices)
37  * - command table handling isn't thread safe
38  */
39
40 #include "config.h"
41 #include "wine/port.h"
42
43 #include <stdlib.h>
44 #include <stdarg.h>
45 #include <stdio.h>
46 #include <string.h>
47
48 #include "windef.h"
49 #include "winbase.h"
50 #include "wingdi.h"
51 #include "mmsystem.h"
52 #include "winuser.h"
53 #include "winnls.h"
54 #include "winreg.h"
55 #include "wownt32.h"
56
57 #include "digitalv.h"
58 #include "winemm.h"
59
60 #include "wine/debug.h"
61 #include "wine/unicode.h"
62
63 WINE_DEFAULT_DEBUG_CHANNEL(mci);
64
65 /* First MCI valid device ID (0 means error) */
66 #define MCI_MAGIC 0x0001
67
68 /* MCI settings */
69 static const WCHAR wszHklmMci  [] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s',' ','N','T','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','M','C','I',0};
70 static const WCHAR wszNull     [] = {0};
71 static const WCHAR wszAll      [] = {'A','L','L',0};
72 static const WCHAR wszMci      [] = {'M','C','I',0};
73 static const WCHAR wszOpen     [] = {'o','p','e','n',0};
74 static const WCHAR wszSystemIni[] = {'s','y','s','t','e','m','.','i','n','i',0};
75
76 static WINE_MCIDRIVER *MciDrivers;
77
78 static UINT WINAPI MCI_DefYieldProc(MCIDEVICEID wDevID, DWORD data);
79 static UINT MCI_SetCommandTable(HGLOBAL hMem, UINT uDevType);
80
81 /* dup a string and uppercase it */
82 static inline LPWSTR str_dup_upper( LPCWSTR str )
83 {
84     INT len = (strlenW(str) + 1) * sizeof(WCHAR);
85     LPWSTR p = HeapAlloc( GetProcessHeap(), 0, len );
86     if (p)
87     {
88         memcpy( p, str, len );
89         CharUpperW( p );
90     }
91     return p;
92 }
93
94 /**************************************************************************
95  *                              MCI_GetDriver                   [internal]
96  */
97 static LPWINE_MCIDRIVER MCI_GetDriver(UINT wDevID)
98 {
99     LPWINE_MCIDRIVER    wmd = 0;
100
101     EnterCriticalSection(&WINMM_cs);
102     for (wmd = MciDrivers; wmd; wmd = wmd->lpNext) {
103         if (wmd->wDeviceID == wDevID)
104             break;
105     }
106     LeaveCriticalSection(&WINMM_cs);
107     return wmd;
108 }
109
110 /**************************************************************************
111  *                              MCI_GetDriverFromString         [internal]
112  */
113 static UINT MCI_GetDriverFromString(LPCWSTR lpstrName)
114 {
115     LPWINE_MCIDRIVER    wmd;
116     UINT                ret = 0;
117
118     if (!lpstrName)
119         return 0;
120
121     if (!strcmpiW(lpstrName, wszAll))
122         return MCI_ALL_DEVICE_ID;
123
124     EnterCriticalSection(&WINMM_cs);
125     for (wmd = MciDrivers; wmd; wmd = wmd->lpNext) {
126         if (wmd->lpstrAlias && strcmpiW(wmd->lpstrAlias, lpstrName) == 0) {
127             ret = wmd->wDeviceID;
128             break;
129         }
130     }
131     LeaveCriticalSection(&WINMM_cs);
132
133     return ret;
134 }
135
136 /**************************************************************************
137  *                      MCI_MessageToString                     [internal]
138  */
139 static const char* MCI_MessageToString(UINT wMsg)
140 {
141 #define CASE(s) case (s): return #s
142
143     switch (wMsg) {
144         CASE(DRV_LOAD);
145         CASE(DRV_ENABLE);
146         CASE(DRV_OPEN);
147         CASE(DRV_CLOSE);
148         CASE(DRV_DISABLE);
149         CASE(DRV_FREE);
150         CASE(DRV_CONFIGURE);
151         CASE(DRV_QUERYCONFIGURE);
152         CASE(DRV_INSTALL);
153         CASE(DRV_REMOVE);
154         CASE(DRV_EXITSESSION);
155         CASE(DRV_EXITAPPLICATION);
156         CASE(DRV_POWER);
157         CASE(MCI_BREAK);
158         CASE(MCI_CLOSE);
159         CASE(MCI_CLOSE_DRIVER);
160         CASE(MCI_COPY);
161         CASE(MCI_CUE);
162         CASE(MCI_CUT);
163         CASE(MCI_DELETE);
164         CASE(MCI_ESCAPE);
165         CASE(MCI_FREEZE);
166         CASE(MCI_PAUSE);
167         CASE(MCI_PLAY);
168         CASE(MCI_GETDEVCAPS);
169         CASE(MCI_INFO);
170         CASE(MCI_LOAD);
171         CASE(MCI_OPEN);
172         CASE(MCI_OPEN_DRIVER);
173         CASE(MCI_PASTE);
174         CASE(MCI_PUT);
175         CASE(MCI_REALIZE);
176         CASE(MCI_RECORD);
177         CASE(MCI_RESUME);
178         CASE(MCI_SAVE);
179         CASE(MCI_SEEK);
180         CASE(MCI_SET);
181         CASE(MCI_SOUND);
182         CASE(MCI_SPIN);
183         CASE(MCI_STATUS);
184         CASE(MCI_STEP);
185         CASE(MCI_STOP);
186         CASE(MCI_SYSINFO);
187         CASE(MCI_UNFREEZE);
188         CASE(MCI_UPDATE);
189         CASE(MCI_WHERE);
190         CASE(MCI_WINDOW);
191         /* constants for digital video */
192         CASE(MCI_CAPTURE);
193         CASE(MCI_MONITOR);
194         CASE(MCI_RESERVE);
195         CASE(MCI_SETAUDIO);
196         CASE(MCI_SIGNAL);
197         CASE(MCI_SETVIDEO);
198         CASE(MCI_QUALITY);
199         CASE(MCI_LIST);
200         CASE(MCI_UNDO);
201         CASE(MCI_CONFIGURE);
202         CASE(MCI_RESTORE);
203 #undef CASE
204     default:
205         return wine_dbg_sprintf("MCI_<<%04X>>", wMsg);
206     }
207 }
208
209 static LPWSTR MCI_strdupAtoW( LPCSTR str )
210 {
211     LPWSTR ret;
212     INT len;
213
214     if (!str) return NULL;
215     len = MultiByteToWideChar( CP_ACP, 0, str, -1, NULL, 0 );
216     ret = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
217     if (ret) MultiByteToWideChar( CP_ACP, 0, str, -1, ret, len );
218     return ret;
219 }
220
221 static int MCI_MapMsgAtoW(UINT msg, DWORD_PTR dwParam1, DWORD_PTR *dwParam2)
222 {
223     if (msg < DRV_RESERVED) return 0;
224
225     switch (msg)
226     {
227     case MCI_CLOSE:
228     case MCI_CONFIGURE:
229     case MCI_PLAY:
230     case MCI_SEEK:
231     case MCI_STOP:
232     case MCI_PAUSE:
233     case MCI_GETDEVCAPS:
234     case MCI_SPIN:
235     case MCI_SET:
236     case MCI_STEP:
237     case MCI_RECORD:
238     case MCI_BREAK:
239     case MCI_STATUS:
240     case MCI_CUE:
241     case MCI_REALIZE:
242     case MCI_PUT:
243     case MCI_WHERE:
244     case MCI_FREEZE:
245     case MCI_UNFREEZE:
246     case MCI_CUT:
247     case MCI_COPY:
248     case MCI_PASTE:
249     case MCI_UPDATE:
250     case MCI_RESUME:
251     case MCI_DELETE:
252     case MCI_MONITOR:
253     case MCI_SIGNAL:
254     case MCI_UNDO:
255         return 0;
256
257     case MCI_OPEN:
258         {   /* MCI_ANIM_OPEN_PARMS is the largest known MCI_OPEN_PARMS
259              * structure, larger than MCI_WAVE_OPEN_PARMS */
260             MCI_ANIM_OPEN_PARMSA *mci_openA = (MCI_ANIM_OPEN_PARMSA*)*dwParam2;
261             MCI_ANIM_OPEN_PARMSW *mci_openW;
262             DWORD_PTR *ptr;
263
264             ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(DWORD_PTR) + sizeof(*mci_openW));
265             if (!ptr) return -1;
266
267             *ptr++ = *dwParam2; /* save the previous pointer */
268             *dwParam2 = (DWORD_PTR)ptr;
269             mci_openW = (MCI_ANIM_OPEN_PARMSW *)ptr;
270
271             if (dwParam1 & MCI_NOTIFY)
272                 mci_openW->dwCallback = mci_openA->dwCallback;
273
274             if (dwParam1 & MCI_OPEN_TYPE)
275             {
276                 if (dwParam1 & MCI_OPEN_TYPE_ID)
277                     mci_openW->lpstrDeviceType = (LPCWSTR)mci_openA->lpstrDeviceType;
278                 else
279                     mci_openW->lpstrDeviceType = MCI_strdupAtoW(mci_openA->lpstrDeviceType);
280             }
281             if (dwParam1 & MCI_OPEN_ELEMENT)
282             {
283                 if (dwParam1 & MCI_OPEN_ELEMENT_ID)
284                     mci_openW->lpstrElementName = (LPCWSTR)mci_openA->lpstrElementName;
285                 else
286                     mci_openW->lpstrElementName = MCI_strdupAtoW(mci_openA->lpstrElementName);
287             }
288             if (dwParam1 & MCI_OPEN_ALIAS)
289                 mci_openW->lpstrAlias = MCI_strdupAtoW(mci_openA->lpstrAlias);
290             /* We don't know how many DWORD follow, as
291              * the structure depends on the device. */
292             if (HIWORD(dwParam1))
293                 memcpy(&mci_openW->dwStyle, &mci_openA->dwStyle, sizeof(MCI_ANIM_OPEN_PARMSW) - sizeof(MCI_OPEN_PARMSW));
294         }
295         return 1;
296
297     case MCI_WINDOW:
298         if (dwParam1 & MCI_ANIM_WINDOW_TEXT)
299         {
300             MCI_ANIM_WINDOW_PARMSA *mci_windowA = (MCI_ANIM_WINDOW_PARMSA *)*dwParam2;
301             MCI_ANIM_WINDOW_PARMSW *mci_windowW;
302
303             mci_windowW = HeapAlloc(GetProcessHeap(), 0, sizeof(*mci_windowW));
304             if (!mci_windowW) return -1;
305
306             *dwParam2 = (DWORD_PTR)mci_windowW;
307
308             mci_windowW->lpstrText = MCI_strdupAtoW(mci_windowA->lpstrText);
309
310             if (dwParam1 & MCI_NOTIFY)
311                 mci_windowW->dwCallback = mci_windowA->dwCallback;
312             if (dwParam1 & MCI_ANIM_WINDOW_HWND)
313                 mci_windowW->hWnd = mci_windowA->hWnd;
314             if (dwParam1 & MCI_ANIM_WINDOW_STATE)
315                 mci_windowW->nCmdShow = mci_windowA->nCmdShow;
316
317             return 1;
318         }
319         return 0;
320
321     case MCI_SYSINFO:
322         if (dwParam1 & (MCI_SYSINFO_INSTALLNAME | MCI_SYSINFO_NAME))
323         {
324             MCI_SYSINFO_PARMSA *mci_sysinfoA = (MCI_SYSINFO_PARMSA *)*dwParam2;
325             MCI_SYSINFO_PARMSW *mci_sysinfoW;
326             DWORD_PTR *ptr;
327
328             ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(*mci_sysinfoW) + sizeof(DWORD_PTR));
329             if (!ptr) return -1;
330
331             *ptr++ = *dwParam2; /* save the previous pointer */
332             *dwParam2 = (DWORD_PTR)ptr;
333             mci_sysinfoW = (MCI_SYSINFO_PARMSW *)ptr;
334
335             if (dwParam1 & MCI_NOTIFY)
336                 mci_sysinfoW->dwCallback = mci_sysinfoA->dwCallback;
337
338             /* Size is measured in numbers of characters, despite what MSDN says. */
339             mci_sysinfoW->dwRetSize = mci_sysinfoA->dwRetSize;
340             mci_sysinfoW->lpstrReturn = HeapAlloc(GetProcessHeap(), 0, mci_sysinfoW->dwRetSize * sizeof(WCHAR));
341             mci_sysinfoW->dwNumber = mci_sysinfoA->dwNumber;
342             mci_sysinfoW->wDeviceType = mci_sysinfoA->wDeviceType;
343             return 1;
344         }
345         return 0;
346     case MCI_INFO:
347         {
348             MCI_DGV_INFO_PARMSA *mci_infoA = (MCI_DGV_INFO_PARMSA *)*dwParam2;
349             MCI_DGV_INFO_PARMSW *mci_infoW;
350             DWORD_PTR *ptr;
351
352             ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(*mci_infoW) + sizeof(DWORD_PTR));
353             if (!ptr) return -1;
354
355             *ptr++ = *dwParam2; /* save the previous pointer */
356             *dwParam2 = (DWORD_PTR)ptr;
357             mci_infoW = (MCI_DGV_INFO_PARMSW *)ptr;
358
359             if (dwParam1 & MCI_NOTIFY)
360                 mci_infoW->dwCallback = mci_infoA->dwCallback;
361
362             /* Size is measured in numbers of characters. */
363             mci_infoW->dwRetSize = mci_infoA->dwRetSize;
364             mci_infoW->lpstrReturn = HeapAlloc(GetProcessHeap(), 0, mci_infoW->dwRetSize * sizeof(WCHAR));
365             if (dwParam1 & MCI_DGV_INFO_ITEM)
366                 mci_infoW->dwItem = mci_infoA->dwItem;
367             return 1;
368         }
369     case MCI_SAVE:
370     case MCI_LOAD:
371     case MCI_CAPTURE:
372     case MCI_RESTORE:
373         {   /* All these commands have the same layout: callback + string + optional rect */
374             MCI_OVLY_LOAD_PARMSA *mci_loadA = (MCI_OVLY_LOAD_PARMSA *)*dwParam2;
375             MCI_OVLY_LOAD_PARMSW *mci_loadW;
376
377             mci_loadW = HeapAlloc(GetProcessHeap(), 0, sizeof(*mci_loadW));
378             if (!mci_loadW) return -1;
379
380             *dwParam2 = (DWORD_PTR)mci_loadW;
381             if (dwParam1 & MCI_NOTIFY)
382                 mci_loadW->dwCallback = mci_loadA->dwCallback;
383             mci_loadW->lpfilename = MCI_strdupAtoW(mci_loadA->lpfilename);
384             if ((MCI_SAVE    == msg && dwParam1 & MCI_DGV_RECT) ||
385                 (MCI_LOAD    == msg && dwParam1 & MCI_OVLY_RECT) ||
386                 (MCI_CAPTURE == msg && dwParam1 & MCI_DGV_CAPTURE_AT) ||
387                 (MCI_RESTORE == msg && dwParam1 & MCI_DGV_RESTORE_AT))
388                 mci_loadW->rc = mci_loadA->rc;
389             return 1;
390         }
391     case MCI_SOUND:
392     case MCI_ESCAPE:
393         {   /* All these commands have the same layout: callback + string */
394             MCI_VD_ESCAPE_PARMSA *mci_vd_escapeA = (MCI_VD_ESCAPE_PARMSA *)*dwParam2;
395             MCI_VD_ESCAPE_PARMSW *mci_vd_escapeW;
396
397             mci_vd_escapeW = HeapAlloc(GetProcessHeap(), 0, sizeof(*mci_vd_escapeW));
398             if (!mci_vd_escapeW) return -1;
399
400             *dwParam2 = (DWORD_PTR)mci_vd_escapeW;
401             if (dwParam1 & MCI_NOTIFY)
402                 mci_vd_escapeW->dwCallback = mci_vd_escapeA->dwCallback;
403             mci_vd_escapeW->lpstrCommand = MCI_strdupAtoW(mci_vd_escapeA->lpstrCommand);
404             return 1;
405         }
406     case MCI_SETAUDIO:
407     case MCI_SETVIDEO:
408         if (!(dwParam1 & (MCI_DGV_SETVIDEO_QUALITY | MCI_DGV_SETVIDEO_ALG
409                         | MCI_DGV_SETAUDIO_QUALITY | MCI_DGV_SETAUDIO_ALG)))
410             return 0;
411         /* fall through to default */
412     case MCI_RESERVE:
413     case MCI_QUALITY:
414     case MCI_LIST:
415     default:
416         FIXME("Message %s needs translation\n", MCI_MessageToString(msg));
417         return 0; /* pass through untouched */
418     }
419 }
420
421 static void MCI_UnmapMsgAtoW(UINT msg, DWORD_PTR dwParam1, DWORD_PTR dwParam2,
422                               DWORD result)
423 {
424     switch (msg)
425     {
426     case MCI_OPEN:
427         {
428             DWORD_PTR *ptr = (DWORD_PTR *)dwParam2 - 1;
429             MCI_OPEN_PARMSA *mci_openA = (MCI_OPEN_PARMSA *)*ptr;
430             MCI_OPEN_PARMSW *mci_openW = (MCI_OPEN_PARMSW *)dwParam2;
431
432             mci_openA->wDeviceID = mci_openW->wDeviceID;
433
434             if (dwParam1 & MCI_OPEN_TYPE)
435             {
436                 if (!(dwParam1 & MCI_OPEN_TYPE_ID))
437                     HeapFree(GetProcessHeap(), 0, (LPWSTR)mci_openW->lpstrDeviceType);
438             }
439             if (dwParam1 & MCI_OPEN_ELEMENT)
440             {
441                 if (!(dwParam1 & MCI_OPEN_ELEMENT_ID))
442                     HeapFree(GetProcessHeap(), 0, (LPWSTR)mci_openW->lpstrElementName);
443             }
444             if (dwParam1 & MCI_OPEN_ALIAS)
445                 HeapFree(GetProcessHeap(), 0, (LPWSTR)mci_openW->lpstrAlias);
446             HeapFree(GetProcessHeap(), 0, ptr);
447         }
448         break;
449     case MCI_WINDOW:
450         if (dwParam1 & MCI_ANIM_WINDOW_TEXT)
451         {
452             MCI_ANIM_WINDOW_PARMSW *mci_windowW = (MCI_ANIM_WINDOW_PARMSW *)dwParam2;
453
454             HeapFree(GetProcessHeap(), 0, (void*)mci_windowW->lpstrText);
455             HeapFree(GetProcessHeap(), 0, mci_windowW);
456         }
457         break;
458
459     case MCI_SYSINFO:
460         if (dwParam1 & (MCI_SYSINFO_INSTALLNAME | MCI_SYSINFO_NAME))
461         {
462             DWORD_PTR *ptr = (DWORD_PTR *)dwParam2 - 1;
463             MCI_SYSINFO_PARMSA *mci_sysinfoA = (MCI_SYSINFO_PARMSA *)*ptr;
464             MCI_SYSINFO_PARMSW *mci_sysinfoW = (MCI_SYSINFO_PARMSW *)dwParam2;
465
466             if (!result)
467             {
468                 WideCharToMultiByte(CP_ACP, 0,
469                                     mci_sysinfoW->lpstrReturn, -1,
470                                     mci_sysinfoA->lpstrReturn, mci_sysinfoA->dwRetSize,
471                                     NULL, NULL);
472             }
473
474             HeapFree(GetProcessHeap(), 0, mci_sysinfoW->lpstrReturn);
475             HeapFree(GetProcessHeap(), 0, ptr);
476         }
477         break;
478     case MCI_INFO:
479         {
480             DWORD_PTR *ptr = (DWORD_PTR *)dwParam2 - 1;
481             MCI_INFO_PARMSA *mci_infoA = (MCI_INFO_PARMSA *)*ptr;
482             MCI_INFO_PARMSW *mci_infoW = (MCI_INFO_PARMSW *)dwParam2;
483
484             if (!result)
485             {
486                 WideCharToMultiByte(CP_ACP, 0,
487                                     mci_infoW->lpstrReturn, -1,
488                                     mci_infoA->lpstrReturn, mci_infoA->dwRetSize,
489                                     NULL, NULL);
490             }
491
492             HeapFree(GetProcessHeap(), 0, mci_infoW->lpstrReturn);
493             HeapFree(GetProcessHeap(), 0, ptr);
494         }
495         break;
496     case MCI_SAVE:
497     case MCI_LOAD:
498     case MCI_CAPTURE:
499     case MCI_RESTORE:
500         {   /* All these commands have the same layout: callback + string + optional rect */
501             MCI_OVLY_LOAD_PARMSW *mci_loadW = (MCI_OVLY_LOAD_PARMSW *)dwParam2;
502
503             HeapFree(GetProcessHeap(), 0, (void*)mci_loadW->lpfilename);
504             HeapFree(GetProcessHeap(), 0, mci_loadW);
505         }
506         break;
507     case MCI_SOUND:
508     case MCI_ESCAPE:
509         {   /* All these commands have the same layout: callback + string */
510             MCI_VD_ESCAPE_PARMSW *mci_vd_escapeW = (MCI_VD_ESCAPE_PARMSW *)dwParam2;
511
512             HeapFree(GetProcessHeap(), 0, (void*)mci_vd_escapeW->lpstrCommand);
513             HeapFree(GetProcessHeap(), 0, mci_vd_escapeW);
514         }
515         break;
516
517     default:
518         FIXME("Message %s needs unmapping\n", MCI_MessageToString(msg));
519         break;
520     }
521 }
522
523 /**************************************************************************
524  *                              MCI_GetDevTypeFromFileName      [internal]
525  */
526 static  DWORD   MCI_GetDevTypeFromFileName(LPCWSTR fileName, LPWSTR buf, UINT len)
527 {
528     LPCWSTR     tmp;
529     HKEY        hKey;
530     static const WCHAR keyW[] = {'S','O','F','T','W','A','R','E','\\','M','i','c','r','o','s','o','f','t','\\',
531                                  'W','i','n','d','o','w','s',' ','N','T','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
532                                  'M','C','I',' ','E','x','t','e','n','s','i','o','n','s',0};
533     if ((tmp = strrchrW(fileName, '.'))) {
534         if (RegOpenKeyExW( HKEY_LOCAL_MACHINE, keyW,
535                            0, KEY_QUERY_VALUE, &hKey ) == ERROR_SUCCESS) {
536             DWORD dwLen = len;
537             LONG lRet = RegQueryValueExW( hKey, tmp + 1, 0, 0, (void*)buf, &dwLen ); 
538             RegCloseKey( hKey );
539             if (lRet == ERROR_SUCCESS) return 0;
540         }
541         TRACE("No ...\\MCI Extensions entry for %s found.\n", debugstr_w(tmp));
542     }
543     return MCIERR_EXTENSION_NOT_FOUND;
544 }
545
546 /**************************************************************************
547  *                              MCI_GetDevTypeFromResource      [internal]
548  */
549 static  UINT    MCI_GetDevTypeFromResource(LPCWSTR lpstrName)
550 {
551     WCHAR       buf[32];
552     UINT        uDevType;
553     for (uDevType = MCI_DEVTYPE_FIRST; uDevType <= MCI_DEVTYPE_LAST; uDevType++) {
554         if (LoadStringW(hWinMM32Instance, uDevType, buf, sizeof(buf) / sizeof(WCHAR))) {
555             /* FIXME: ignore digits suffix */
556             if (!strcmpiW(buf, lpstrName))
557                 return uDevType;
558         }
559     }
560     return 0;
561 }
562
563 #define MAX_MCICMDTABLE                 20
564 #define MCI_COMMAND_TABLE_NOT_LOADED    0xFFFE
565
566 typedef struct tagWINE_MCICMDTABLE {
567     UINT                uDevType;
568     HGLOBAL             hMem;
569     const BYTE*         lpTable;
570     UINT                nVerbs;         /* number of verbs in command table */
571     LPCWSTR*            aVerbs;         /* array of verbs to speed up the verb look up process */
572 } WINE_MCICMDTABLE, *LPWINE_MCICMDTABLE;
573
574 static WINE_MCICMDTABLE S_MciCmdTable[MAX_MCICMDTABLE];
575
576 /**************************************************************************
577  *                              MCI_IsCommandTableValid         [internal]
578  */
579 static  BOOL            MCI_IsCommandTableValid(UINT uTbl)
580 {
581     const BYTE* lmem;
582     LPCWSTR     str;
583     DWORD       flg;
584     WORD        eid;
585     int         idx = 0;
586     BOOL        inCst = FALSE;
587
588     TRACE("Dumping cmdTbl=%d [lpTable=%p devType=%d]\n",
589           uTbl, S_MciCmdTable[uTbl].lpTable, S_MciCmdTable[uTbl].uDevType);
590
591     if (uTbl >= MAX_MCICMDTABLE || !S_MciCmdTable[uTbl].lpTable)
592         return FALSE;
593
594     lmem = S_MciCmdTable[uTbl].lpTable;
595     do {
596         str = (LPCWSTR)lmem;
597         lmem += (strlenW(str) + 1) * sizeof(WCHAR);
598         flg = *(const DWORD*)lmem;
599         eid = *(const WORD*)(lmem + sizeof(DWORD));
600         lmem += sizeof(DWORD) + sizeof(WORD);
601         idx ++;
602         /* TRACE("cmd=%s %08lx %04x\n", debugstr_w(str), flg, eid); */
603         switch (eid) {
604         case MCI_COMMAND_HEAD:          if (!*str || !flg) return FALSE; idx = 0;               break;  /* check unicity of str in table */
605         case MCI_STRING:                if (inCst) return FALSE;                                break;
606         case MCI_HWND:                  /* Occurs inside MCI_CONSTANT as in "window handle default" */
607         case MCI_HPAL:
608         case MCI_HDC:
609         case MCI_INTEGER:               if (!*str) return FALSE;                                break;
610         case MCI_END_COMMAND:           if (*str || flg || idx == 0) return FALSE; idx = 0;     break;
611         case MCI_RETURN:                if (*str || idx != 1) return FALSE;                     break;
612         case MCI_FLAG:                  if (!*str) return FALSE;                                break;
613         case MCI_END_COMMAND_LIST:      if (*str || flg) return FALSE;  idx = 0;                break;
614         case MCI_RECT:                  if (!*str || inCst) return FALSE;                       break;
615         case MCI_CONSTANT:              if (inCst) return FALSE; inCst = TRUE;                  break;
616         case MCI_END_CONSTANT:          if (*str || flg || !inCst) return FALSE; inCst = FALSE; break;
617         default:                        return FALSE;
618         }
619     } while (eid != MCI_END_COMMAND_LIST);
620     return TRUE;
621 }
622
623 /**************************************************************************
624  *                              MCI_DumpCommandTable            [internal]
625  */
626 static  BOOL            MCI_DumpCommandTable(UINT uTbl)
627 {
628     const BYTE* lmem;
629     LPCWSTR     str;
630     WORD        eid;
631
632     if (!MCI_IsCommandTableValid(uTbl)) {
633         ERR("Ooops: %d is not valid\n", uTbl);
634         return FALSE;
635     }
636
637     lmem = S_MciCmdTable[uTbl].lpTable;
638     do {
639         do {
640             /* DWORD flg; */
641             str = (LPCWSTR)lmem;
642             lmem += (strlenW(str) + 1) * sizeof(WCHAR);
643             /* flg = *(const DWORD*)lmem; */
644             eid = *(const WORD*)(lmem + sizeof(DWORD));
645             /* TRACE("cmd=%s %08lx %04x\n", debugstr_w(str), flg, eid); */
646             lmem += sizeof(DWORD) + sizeof(WORD);
647         } while (eid != MCI_END_COMMAND && eid != MCI_END_COMMAND_LIST);
648         /* EPP TRACE(" => end of command%s\n", (eid == MCI_END_COMMAND_LIST) ? " list" : ""); */
649     } while (eid != MCI_END_COMMAND_LIST);
650     return TRUE;
651 }
652
653
654 /**************************************************************************
655  *                              MCI_GetCommandTable             [internal]
656  */
657 static  UINT            MCI_GetCommandTable(UINT uDevType)
658 {
659     UINT        uTbl;
660     WCHAR       buf[32];
661     LPCWSTR     str = NULL;
662
663     /* first look up existing for existing devType */
664     for (uTbl = 0; uTbl < MAX_MCICMDTABLE; uTbl++) {
665         if (S_MciCmdTable[uTbl].lpTable && S_MciCmdTable[uTbl].uDevType == uDevType)
666             return uTbl;
667     }
668
669     /* well try to load id */
670     if (uDevType >= MCI_DEVTYPE_FIRST && uDevType <= MCI_DEVTYPE_LAST) {
671         if (LoadStringW(hWinMM32Instance, uDevType, buf, sizeof(buf) / sizeof(WCHAR))) {
672             str = buf;
673         }
674     } else if (uDevType == 0) {
675         static const WCHAR wszCore[] = {'C','O','R','E',0};
676         str = wszCore;
677     }
678     uTbl = MCI_NO_COMMAND_TABLE;
679     if (str) {
680         HRSRC   hRsrc = FindResourceW(hWinMM32Instance, str, (LPCWSTR)RT_RCDATA);
681         HANDLE  hMem = 0;
682
683         if (hRsrc) hMem = LoadResource(hWinMM32Instance, hRsrc);
684         if (hMem) {
685             uTbl = MCI_SetCommandTable(hMem, uDevType);
686         } else {
687             WARN("No command table found in resource %p[%s]\n",
688                  hWinMM32Instance, debugstr_w(str));
689         }
690     }
691     TRACE("=> %d\n", uTbl);
692     return uTbl;
693 }
694
695 /**************************************************************************
696  *                              MCI_SetCommandTable             [internal]
697  */
698 static UINT MCI_SetCommandTable(HGLOBAL hMem, UINT uDevType)
699 {
700     int                 uTbl;
701     static      BOOL    bInitDone = FALSE;
702
703     /* <HACK>
704      * The CORE command table must be loaded first, so that MCI_GetCommandTable()
705      * can be called with 0 as a uDevType to retrieve it.
706      * </HACK>
707      */
708     if (!bInitDone) {
709         bInitDone = TRUE;
710         MCI_GetCommandTable(0);
711     }
712     TRACE("(%p, %u)\n", hMem, uDevType);
713     for (uTbl = 0; uTbl < MAX_MCICMDTABLE; uTbl++) {
714         if (!S_MciCmdTable[uTbl].lpTable) {
715             const BYTE* lmem;
716             LPCWSTR     str;
717             WORD        eid;
718             WORD        count;
719
720             S_MciCmdTable[uTbl].uDevType = uDevType;
721             S_MciCmdTable[uTbl].lpTable = LockResource(hMem);
722             S_MciCmdTable[uTbl].hMem = hMem;
723
724             if (TRACE_ON(mci)) {
725                 MCI_DumpCommandTable(uTbl);
726             }
727
728             /* create the verbs table */
729             /* get # of entries */
730             lmem = S_MciCmdTable[uTbl].lpTable;
731             count = 0;
732             do {
733                 str = (LPCWSTR)lmem;
734                 lmem += (strlenW(str) + 1) * sizeof(WCHAR);
735                 eid = *(const WORD*)(lmem + sizeof(DWORD));
736                 lmem += sizeof(DWORD) + sizeof(WORD);
737                 if (eid == MCI_COMMAND_HEAD)
738                     count++;
739             } while (eid != MCI_END_COMMAND_LIST);
740
741             S_MciCmdTable[uTbl].aVerbs = HeapAlloc(GetProcessHeap(), 0, count * sizeof(LPCWSTR));
742             S_MciCmdTable[uTbl].nVerbs = count;
743
744             lmem = S_MciCmdTable[uTbl].lpTable;
745             count = 0;
746             do {
747                 str = (LPCWSTR)lmem;
748                 lmem += (strlenW(str) + 1) * sizeof(WCHAR);
749                 eid = *(const WORD*)(lmem + sizeof(DWORD));
750                 lmem += sizeof(DWORD) + sizeof(WORD);
751                 if (eid == MCI_COMMAND_HEAD)
752                     S_MciCmdTable[uTbl].aVerbs[count++] = str;
753             } while (eid != MCI_END_COMMAND_LIST);
754             /* assert(count == S_MciCmdTable[uTbl].nVerbs); */
755             return uTbl;
756         }
757     }
758
759     return MCI_NO_COMMAND_TABLE;
760 }
761
762 /**************************************************************************
763  *                              MCI_UnLoadMciDriver             [internal]
764  */
765 static  BOOL    MCI_UnLoadMciDriver(LPWINE_MCIDRIVER wmd)
766 {
767     LPWINE_MCIDRIVER*           tmp;
768
769     if (!wmd)
770         return TRUE;
771
772     CloseDriver(wmd->hDriver, 0, 0);
773
774     if (wmd->dwPrivate != 0)
775         WARN("Unloading mci driver with non nul dwPrivate field\n");
776
777     EnterCriticalSection(&WINMM_cs);
778     for (tmp = &MciDrivers; *tmp; tmp = &(*tmp)->lpNext) {
779         if (*tmp == wmd) {
780             *tmp = wmd->lpNext;
781             break;
782         }
783     }
784     LeaveCriticalSection(&WINMM_cs);
785
786     HeapFree(GetProcessHeap(), 0, wmd->lpstrDeviceType);
787     HeapFree(GetProcessHeap(), 0, wmd->lpstrAlias);
788
789     HeapFree(GetProcessHeap(), 0, wmd);
790     return TRUE;
791 }
792
793 /**************************************************************************
794  *                              MCI_OpenMciDriver               [internal]
795  */
796 static  BOOL    MCI_OpenMciDriver(LPWINE_MCIDRIVER wmd, LPCWSTR drvTyp, DWORD_PTR lp)
797 {
798     WCHAR       libName[128];
799
800     if (!DRIVER_GetLibName(drvTyp, wszMci, libName, sizeof(libName)))
801         return FALSE;
802
803     /* First load driver */
804     wmd->hDriver = (HDRVR)DRIVER_TryOpenDriver32(libName, lp);
805     return wmd->hDriver != NULL;
806 }
807
808 /**************************************************************************
809  *                              MCI_LoadMciDriver               [internal]
810  */
811 static  DWORD   MCI_LoadMciDriver(LPCWSTR _strDevTyp, LPWINE_MCIDRIVER* lpwmd)
812 {
813     LPWSTR                      strDevTyp = str_dup_upper(_strDevTyp);
814     LPWINE_MCIDRIVER            wmd = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wmd));
815     MCI_OPEN_DRIVER_PARMSW      modp;
816     DWORD                       dwRet = 0;
817
818     if (!wmd || !strDevTyp) {
819         dwRet = MCIERR_OUT_OF_MEMORY;
820         goto errCleanUp;
821     }
822
823     wmd->lpfnYieldProc = MCI_DefYieldProc;
824     wmd->dwYieldData = VK_CANCEL;
825     wmd->CreatorThread = GetCurrentThreadId();
826
827     EnterCriticalSection(&WINMM_cs);
828     /* wmd must be inserted in list before sending opening the driver, because it
829      * may want to lookup at wDevID
830      */
831     wmd->lpNext = MciDrivers;
832     MciDrivers = wmd;
833
834     for (modp.wDeviceID = MCI_MAGIC;
835          MCI_GetDriver(modp.wDeviceID) != 0;
836          modp.wDeviceID++);
837
838     wmd->wDeviceID = modp.wDeviceID;
839
840     LeaveCriticalSection(&WINMM_cs);
841
842     TRACE("wDevID=%04X\n", modp.wDeviceID);
843
844     modp.lpstrParams = NULL;
845
846     if (!MCI_OpenMciDriver(wmd, strDevTyp, (DWORD_PTR)&modp)) {
847         /* silence warning if all is used... some bogus program use commands like
848          * 'open all'...
849          */
850         if (strcmpiW(strDevTyp, wszAll) == 0) {
851             dwRet = MCIERR_CANNOT_USE_ALL;
852         } else {
853             FIXME("Couldn't load driver for type %s.\n",
854                   debugstr_w(strDevTyp));
855             dwRet = MCIERR_DEVICE_NOT_INSTALLED;
856         }
857         goto errCleanUp;
858     }
859
860     /* FIXME: should also check that module's description is of the form
861      * MODULENAME:[MCI] comment
862      */
863
864     /* some drivers will return 0x0000FFFF, some others 0xFFFFFFFF */
865     wmd->uSpecificCmdTable = LOWORD(modp.wCustomCommandTable);
866     wmd->uTypeCmdTable = MCI_COMMAND_TABLE_NOT_LOADED;
867
868     TRACE("Loaded driver %p (%s), type is %d, cmdTable=%08x\n",
869           wmd->hDriver, debugstr_w(strDevTyp), modp.wType, modp.wCustomCommandTable);
870
871     wmd->lpstrDeviceType = strDevTyp;
872     wmd->wType = modp.wType;
873
874     TRACE("mcidev=%d, uDevTyp=%04X wDeviceID=%04X !\n",
875           modp.wDeviceID, modp.wType, modp.wDeviceID);
876     *lpwmd = wmd;
877     return 0;
878 errCleanUp:
879     MCI_UnLoadMciDriver(wmd);
880     HeapFree(GetProcessHeap(), 0, strDevTyp);
881     *lpwmd = 0;
882     return dwRet;
883 }
884
885 /**************************************************************************
886  *                      MCI_SendCommandFrom32                   [internal]
887  */
888 static DWORD MCI_SendCommandFrom32(MCIDEVICEID wDevID, UINT16 wMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
889 {
890     DWORD               dwRet = MCIERR_INVALID_DEVICE_ID;
891     LPWINE_MCIDRIVER    wmd = MCI_GetDriver(wDevID);
892
893     if (wmd) {
894         dwRet = SendDriverMessage(wmd->hDriver, wMsg, dwParam1, dwParam2);
895     }
896     return dwRet;
897 }
898
899 /**************************************************************************
900  *                      MCI_FinishOpen                          [internal]
901  */
902 static  DWORD   MCI_FinishOpen(LPWINE_MCIDRIVER wmd, LPMCI_OPEN_PARMSW lpParms,
903                                DWORD dwParam)
904 {
905     LPCWSTR alias = NULL;
906     /* Open always defines an alias for further reference */
907     if (dwParam & MCI_OPEN_ALIAS) {         /* open ... alias */
908         alias = lpParms->lpstrAlias;
909         if (MCI_GetDriverFromString(alias))
910             return MCIERR_DUPLICATE_ALIAS;
911     } else {
912         if ((dwParam & MCI_OPEN_ELEMENT)    /* open file.wav */
913             && !(dwParam & MCI_OPEN_ELEMENT_ID))
914             alias = lpParms->lpstrElementName;
915         else if (dwParam & MCI_OPEN_TYPE )  /* open cdaudio */
916             alias = wmd->lpstrDeviceType;
917         if (alias && MCI_GetDriverFromString(alias))
918             return MCIERR_DEVICE_OPEN;
919     }
920     if (alias) {
921         wmd->lpstrAlias = HeapAlloc(GetProcessHeap(), 0, (strlenW(alias)+1) * sizeof(WCHAR));
922         if (!wmd->lpstrAlias) return MCIERR_OUT_OF_MEMORY;
923         strcpyW( wmd->lpstrAlias, alias);
924         /* In most cases, natives adds MCI_OPEN_ALIAS to the flags passed to the driver.
925          * Don't.  The drivers don't care about the winmm alias. */
926     }
927     lpParms->wDeviceID = wmd->wDeviceID;
928
929     return MCI_SendCommandFrom32(wmd->wDeviceID, MCI_OPEN_DRIVER, dwParam,
930                                  (DWORD_PTR)lpParms);
931 }
932
933 /**************************************************************************
934  *                              MCI_FindCommand         [internal]
935  */
936 static  LPCWSTR         MCI_FindCommand(UINT uTbl, LPCWSTR verb)
937 {
938     UINT        idx;
939
940     if (uTbl >= MAX_MCICMDTABLE || !S_MciCmdTable[uTbl].lpTable)
941         return NULL;
942
943     /* another improvement would be to have the aVerbs array sorted,
944      * so that we could use a dichotomic search on it, rather than this dumb
945      * array look up
946      */
947     for (idx = 0; idx < S_MciCmdTable[uTbl].nVerbs; idx++) {
948         if (strcmpiW(S_MciCmdTable[uTbl].aVerbs[idx], verb) == 0)
949             return S_MciCmdTable[uTbl].aVerbs[idx];
950     }
951
952     return NULL;
953 }
954
955 /**************************************************************************
956  *                              MCI_GetReturnType               [internal]
957  */
958 static  DWORD           MCI_GetReturnType(LPCWSTR lpCmd)
959 {
960     lpCmd = (LPCWSTR)((const BYTE*)(lpCmd + strlenW(lpCmd) + 1) + sizeof(DWORD) + sizeof(WORD));
961     if (*lpCmd == '\0' && *(const WORD*)((const BYTE*)(lpCmd + 1) + sizeof(DWORD)) == MCI_RETURN) {
962         return *(const DWORD*)(lpCmd + 1);
963     }
964     return 0L;
965 }
966
967 /**************************************************************************
968  *                              MCI_GetMessage                  [internal]
969  */
970 static  WORD            MCI_GetMessage(LPCWSTR lpCmd)
971 {
972     return (WORD)*(const DWORD*)(lpCmd + strlenW(lpCmd) + 1);
973 }
974
975 /**************************************************************************
976  *                              MCI_GetDWord                    [internal]
977  *
978  * Accept 0 -1 255 255:0 255:255:255:255 :::1 1::: 2::3 ::4: 12345678
979  * Refuse -1:0 0:-1 :: 256:0 1:256 0::::1
980  */
981 static  BOOL            MCI_GetDWord(DWORD* data, LPWSTR* ptr)
982 {
983     LPWSTR      ret = *ptr;
984     DWORD       total = 0, shift = 0;
985     BOOL        sign = FALSE, digits = FALSE;
986
987     while (*ret == ' ' || *ret == '\t') ret++;
988     if (*ret == '-') {
989         ret++;
990         sign = TRUE;
991     }
992     for(;;) {
993         DWORD   val = 0;
994         while ('0' <= *ret && *ret <= '9') {
995             val = *ret++ - '0' + 10 * val;
996             digits = TRUE;
997         }
998         switch (*ret) {
999         case '\0':      break;
1000         case '\t':
1001         case ' ':       ret++; break;
1002         default:        return FALSE;
1003         case ':':
1004             if ((val >= 256) || (shift >= 24))  return FALSE;
1005             total |= val << shift;
1006             shift += 8;
1007             ret++;
1008             continue;
1009         }
1010
1011         if (!digits)                            return FALSE;
1012         if (shift && (val >= 256 || sign))      return FALSE;
1013         total |= val << shift;
1014         *data = sign ? -total : total;
1015         *ptr = ret;
1016         return TRUE;
1017     }
1018 }
1019
1020 /**************************************************************************
1021  *                              MCI_GetString           [internal]
1022  */
1023 static  DWORD   MCI_GetString(LPWSTR* str, LPWSTR* args)
1024 {
1025     LPWSTR      ptr = *args;
1026
1027     /* see if we have a quoted string */
1028     if (*ptr == '"') {
1029         ptr = strchrW(*str = ptr + 1, '"');
1030         if (!ptr) return MCIERR_NO_CLOSING_QUOTE;
1031         /* FIXME: shall we escape \" from string ?? */
1032         if (ptr[-1] == '\\') TRACE("Ooops: un-escaped \"\n");
1033         *ptr++ = '\0'; /* remove trailing " */
1034         if (*ptr != ' ' && *ptr != '\0') return MCIERR_EXTRA_CHARACTERS;
1035     } else {
1036         ptr = strchrW(ptr, ' ');
1037
1038         if (ptr) {
1039             *ptr++ = '\0';
1040         } else {
1041             ptr = *args + strlenW(*args);
1042         }
1043         *str = *args;
1044     }
1045
1046     *args = ptr;
1047     return 0;
1048 }
1049
1050 #define MCI_DATA_SIZE   16
1051
1052 /**************************************************************************
1053  *                              MCI_ParseOptArgs                [internal]
1054  */
1055 static  DWORD   MCI_ParseOptArgs(DWORD* data, int _offset, LPCWSTR lpCmd,
1056                                  LPWSTR args, LPDWORD dwFlags)
1057 {
1058     int         len, offset;
1059     const char* lmem;
1060     LPCWSTR     str;
1061     DWORD       dwRet, flg, cflg = 0;
1062     WORD        eid;
1063     BOOL        inCst, found;
1064
1065     /* loop on arguments */
1066     while (*args) {
1067         lmem = (const char*)lpCmd;
1068         found = inCst = FALSE;
1069         offset = _offset;
1070
1071         /* skip any leading white space(s) */
1072         while (*args == ' ') args++;
1073         TRACE("args=%s\n", debugstr_w(args));
1074
1075         do { /* loop on options for command table for the requested verb */
1076             str = (LPCWSTR)lmem;
1077             lmem += ((len = strlenW(str)) + 1) * sizeof(WCHAR);
1078             flg = *(const DWORD*)lmem;
1079             eid = *(const WORD*)(lmem + sizeof(DWORD));
1080             lmem += sizeof(DWORD) + sizeof(WORD);
1081             /* TRACE("\tcmd=%s inCst=%c eid=%04x\n", debugstr_w(str), inCst ? 'Y' : 'N', eid); */
1082
1083             switch (eid) {
1084             case MCI_CONSTANT:
1085                 inCst = TRUE;   cflg = flg;     break;
1086             case MCI_END_CONSTANT:
1087                 /* there may be additional integral values after flag in constant */
1088                 if (inCst && MCI_GetDWord(&(data[offset]), &args)) {
1089                     *dwFlags |= cflg;
1090                 }
1091                 inCst = FALSE;  cflg = 0;
1092                 break;
1093             case MCI_RETURN:
1094                 if (offset != _offset) {
1095                     ERR("MCI_RETURN not in first position\n");
1096                     return MCIERR_PARSER_INTERNAL;
1097                 }
1098             }
1099
1100             if (strncmpiW(args, str, len) == 0 &&
1101                 ((eid == MCI_STRING && len == 0) || args[len] == 0 || args[len] == ' ')) {
1102                 /* store good values into data[] */
1103                 args += len;
1104                 while (*args == ' ') args++;
1105                 found = TRUE;
1106
1107                 switch (eid) {
1108                 case MCI_COMMAND_HEAD:
1109                 case MCI_RETURN:
1110                 case MCI_END_COMMAND:
1111                 case MCI_END_COMMAND_LIST:
1112                 case MCI_CONSTANT:      /* done above */
1113                 case MCI_END_CONSTANT:  /* done above */
1114                     break;
1115                 case MCI_FLAG:
1116                     *dwFlags |= flg;
1117                     TRACE("flag=%08x\n", flg);
1118                     break;
1119                 case MCI_HWND:
1120                 case MCI_HPAL:
1121                 case MCI_HDC:
1122                 case MCI_INTEGER:
1123                     if (inCst) {
1124                         data[offset] |= flg;
1125                         *dwFlags |= cflg;
1126                         inCst = FALSE;
1127                         TRACE("flag=%08x constant=%08x\n", cflg, flg);
1128                     } else {
1129                         *dwFlags |= flg;
1130                         if (!MCI_GetDWord(&(data[offset]), &args)) {
1131                             return MCIERR_BAD_INTEGER;
1132                         }
1133                         TRACE("flag=%08x int=%d\n", flg, data[offset]);
1134                     }
1135                     break;
1136                 case MCI_RECT:
1137                     /* store rect in data (offset..offset+3) */
1138                     *dwFlags |= flg;
1139                     if (!MCI_GetDWord(&(data[offset+0]), &args) ||
1140                         !MCI_GetDWord(&(data[offset+1]), &args) ||
1141                         !MCI_GetDWord(&(data[offset+2]), &args) ||
1142                         !MCI_GetDWord(&(data[offset+3]), &args)) {
1143                         return MCIERR_BAD_INTEGER;
1144                     }
1145                     TRACE("flag=%08x for rectangle\n", flg);
1146                     break;
1147                 case MCI_STRING:
1148                     *dwFlags |= flg;
1149                     if ((dwRet = MCI_GetString((LPWSTR*)&data[offset], &args)))
1150                         return dwRet;
1151                     TRACE("flag=%08x string=%s\n", flg, debugstr_w(*(LPWSTR*)&data[offset]));
1152                     break;
1153                 default:        ERR("oops\n");
1154                 }
1155                 /* exit inside while loop, except if just entered in constant area definition */
1156                 if (!inCst || eid != MCI_CONSTANT) eid = MCI_END_COMMAND;
1157             } else {
1158                 /* have offset incremented if needed */
1159                 switch (eid) {
1160                 case MCI_COMMAND_HEAD:
1161                 case MCI_RETURN:
1162                 case MCI_END_COMMAND:
1163                 case MCI_END_COMMAND_LIST:
1164                 case MCI_CONSTANT:
1165                 case MCI_FLAG:                  break;
1166                 case MCI_HWND:
1167                 case MCI_HPAL:
1168                 case MCI_HDC:                   if (!inCst) offset += sizeof(HANDLE)/sizeof(DWORD); break;
1169                 case MCI_INTEGER:               if (!inCst) offset++;   break;
1170                 case MCI_END_CONSTANT:          offset++; break;
1171                 case MCI_STRING:                offset += sizeof(LPWSTR)/sizeof(DWORD); break;
1172                 case MCI_RECT:                  offset += 4; break;
1173                 default:                        ERR("oops\n");
1174                 }
1175             }
1176         } while (eid != MCI_END_COMMAND);
1177         if (!found) {
1178             WARN("Optarg %s not found\n", debugstr_w(args));
1179             return MCIERR_UNRECOGNIZED_COMMAND;
1180         }
1181         if (offset == MCI_DATA_SIZE) {
1182             ERR("Internal data[] buffer overflow\n");
1183             return MCIERR_PARSER_INTERNAL;
1184         }
1185     }
1186     return 0;
1187 }
1188
1189 /**************************************************************************
1190  *                              MCI_HandleReturnValues  [internal]
1191  */
1192 static  DWORD   MCI_HandleReturnValues(DWORD dwRet, LPWINE_MCIDRIVER wmd, DWORD retType,
1193                                        MCI_GENERIC_PARMS *params, LPWSTR lpstrRet, UINT uRetLen)
1194 {
1195     static const WCHAR fmt_d  [] = {'%','d',0};
1196     static const WCHAR fmt_d4 [] = {'%','d',' ','%','d',' ','%','d',' ','%','d',0};
1197     static const WCHAR wszCol3[] = {'%','0','2','d',':','%','0','2','d',':','%','0','2','d',0};
1198     static const WCHAR wszCol4[] = {'%','0','2','d',':','%','0','2','d',':','%','0','2','d',':','%','0','2','d',0};
1199
1200     if (lpstrRet) {
1201         switch (retType) {
1202         case 0: /* nothing to return */
1203             break;
1204         case MCI_INTEGER:
1205         {
1206             DWORD data = *(DWORD *)(params + 1);
1207             switch (dwRet & 0xFFFF0000ul) {
1208             case 0:
1209             case MCI_INTEGER_RETURNED:
1210                 snprintfW(lpstrRet, uRetLen, fmt_d, data);
1211                 break;
1212             case MCI_RESOURCE_RETURNED:
1213                 /* return string which ID is HIWORD(data),
1214                  * string is loaded from mmsystem.dll */
1215                 LoadStringW(hWinMM32Instance, HIWORD(data), lpstrRet, uRetLen);
1216                 break;
1217             case MCI_RESOURCE_RETURNED|MCI_RESOURCE_DRIVER:
1218                 /* return string which ID is HIWORD(data),
1219                  * string is loaded from driver */
1220                 /* FIXME: this is wrong for a 16 bit handle */
1221                 LoadStringW(GetDriverModuleHandle(wmd->hDriver),
1222                             HIWORD(data), lpstrRet, uRetLen);
1223                 break;
1224             case MCI_COLONIZED3_RETURN:
1225                 snprintfW(lpstrRet, uRetLen, wszCol3,
1226                           LOBYTE(LOWORD(data)), HIBYTE(LOWORD(data)),
1227                           LOBYTE(HIWORD(data)));
1228                 break;
1229             case MCI_COLONIZED4_RETURN:
1230                 snprintfW(lpstrRet, uRetLen, wszCol4,
1231                           LOBYTE(LOWORD(data)), HIBYTE(LOWORD(data)),
1232                           LOBYTE(HIWORD(data)), HIBYTE(HIWORD(data)));
1233                 break;
1234             default:    ERR("Ooops (%04X)\n", HIWORD(dwRet));
1235             }
1236             break;
1237         }
1238 #ifdef MCI_INTEGER64
1239         case MCI_INTEGER64:
1240         {
1241             static const WCHAR fmt_ld [] = {'%','l','d',0};
1242             DWORD_PTR data = *(DWORD_PTR *)(params + 1);
1243             switch (dwRet & 0xFFFF0000ul) {
1244             case 0:
1245             case MCI_INTEGER_RETURNED:
1246                 snprintfW(lpstrRet, uRetLen, fmt_ld, data);
1247                 break;
1248             case MCI_RESOURCE_RETURNED:
1249                 /* return string which ID is HIWORD(data),
1250                  * string is loaded from mmsystem.dll */
1251                 LoadStringW(hWinMM32Instance, HIWORD(data), lpstrRet, uRetLen);
1252                 break;
1253             case MCI_RESOURCE_RETURNED|MCI_RESOURCE_DRIVER:
1254                 /* return string which ID is HIWORD(data),
1255                  * string is loaded from driver */
1256                 /* FIXME: this is wrong for a 16 bit handle */
1257                 LoadStringW(GetDriverModuleHandle(wmd->hDriver),
1258                             HIWORD(data), lpstrRet, uRetLen);
1259                 break;
1260             case MCI_COLONIZED3_RETURN:
1261                 snprintfW(lpstrRet, uRetLen, wszCol3,
1262                           LOBYTE(LOWORD(data)), HIBYTE(LOWORD(data)),
1263                           LOBYTE(HIWORD(data)));
1264                 break;
1265             case MCI_COLONIZED4_RETURN:
1266                 snprintfW(lpstrRet, uRetLen, wszCol4,
1267                           LOBYTE(LOWORD(data)), HIBYTE(LOWORD(data)),
1268                           LOBYTE(HIWORD(data)), HIBYTE(HIWORD(data)));
1269                 break;
1270             default:    ERR("Ooops (%04X)\n", HIWORD(dwRet));
1271             }
1272             break;
1273         }
1274 #endif
1275         case MCI_STRING:
1276             switch (dwRet & 0xFFFF0000ul) {
1277             case 0:
1278                 /* nothing to do data[0] == lpstrRet */
1279                 break;
1280             case MCI_INTEGER_RETURNED:
1281             {
1282                 DWORD *data = (DWORD *)(params + 1);
1283                 *data = *(LPDWORD)lpstrRet;
1284                 snprintfW(lpstrRet, uRetLen, fmt_d, *data);
1285                 break;
1286             }
1287             default:
1288                 WARN("Oooch. MCI_STRING and HIWORD(dwRet)=%04x\n", HIWORD(dwRet));
1289                 break;
1290             }
1291             break;
1292         case MCI_RECT:
1293         {
1294             DWORD *data = (DWORD *)(params + 1);
1295             if (dwRet & 0xFFFF0000ul)
1296                 WARN("Oooch. MCI_STRING and HIWORD(dwRet)=%04x\n", HIWORD(dwRet));
1297             snprintfW(lpstrRet, uRetLen, fmt_d4, data[0], data[1], data[2], data[3]);
1298             break;
1299         }
1300         default:                ERR("oops\n");
1301         }
1302     }
1303     return LOWORD(dwRet);
1304 }
1305
1306 /**************************************************************************
1307  *                              mciSendStringW          [WINMM.@]
1308  */
1309 DWORD WINAPI mciSendStringW(LPCWSTR lpstrCommand, LPWSTR lpstrRet,
1310                             UINT uRetLen, HWND hwndCallback)
1311 {
1312     LPWSTR              verb, dev, args;
1313     LPWINE_MCIDRIVER    wmd = 0;
1314     MCIDEVICEID         uDevID, auto_open = 0;
1315     DWORD               dwFlags = 0, dwRet = 0;
1316     int                 offset = 0;
1317     DWORD               retType;
1318     LPCWSTR             lpCmd = 0;
1319     WORD                wMsg = 0;
1320     static const WCHAR  wszNew[] = {'n','e','w',0};
1321     static const WCHAR  wszSAliasS[] = {' ','a','l','i','a','s',' ',0};
1322     static const WCHAR  wszTypeS[]   = {'t','y','p','e',' ',0};
1323     union
1324     {
1325         MCI_GENERIC_PARMS  generic;
1326         MCI_OPEN_PARMSW    open;
1327         MCI_SOUND_PARMSW   sound;
1328         MCI_SYSINFO_PARMSW sysinfo;
1329         DWORD              dw[MCI_DATA_SIZE];
1330     } data;
1331
1332     TRACE("(%s, %p, %d, %p)\n", 
1333           debugstr_w(lpstrCommand), lpstrRet, uRetLen, hwndCallback);
1334     if (lpstrRet && uRetLen) *lpstrRet = '\0';
1335
1336     /* format is <command> <device> <optargs> */
1337     if (!(verb = HeapAlloc(GetProcessHeap(), 0, (strlenW(lpstrCommand)+1) * sizeof(WCHAR))))
1338         return MCIERR_OUT_OF_MEMORY;
1339     strcpyW( verb, lpstrCommand );
1340     CharLowerW(verb);
1341
1342     memset(&data, 0, sizeof(data));
1343
1344     if (!(args = strchrW(verb, ' '))) {
1345         dwRet = MCIERR_MISSING_DEVICE_NAME;
1346         goto errCleanUp;
1347     }
1348     *args++ = '\0';
1349     if ((dwRet = MCI_GetString(&dev, &args))) {
1350         goto errCleanUp;
1351     }
1352     uDevID = strcmpiW(dev, wszAll) ? 0 : MCI_ALL_DEVICE_ID;
1353
1354     /* Determine devType from open */
1355     if (!strcmpW(verb, wszOpen)) {
1356         LPWSTR  devType, tmp;
1357         WCHAR   buf[128];
1358
1359         /* case dev == 'new' has to be handled */
1360         if (!strcmpW(dev, wszNew)) {
1361             dev = 0;
1362             if ((devType = strstrW(args, wszTypeS)) != NULL) {
1363                 devType += 5;
1364                 tmp = strchrW(devType, ' ');
1365                 if (tmp) *tmp = '\0';
1366                 devType = str_dup_upper(devType);
1367                 if (tmp) *tmp = ' ';
1368                 /* dwFlags and data[2] will be correctly set in ParseOpt loop */
1369             } else {
1370                 WARN("open new requires device type\n");
1371                 dwRet = MCIERR_MISSING_DEVICE_NAME;
1372                 goto errCleanUp;
1373             }
1374         } else if ((devType = strchrW(dev, '!')) != NULL) {
1375             *devType++ = '\0';
1376             tmp = devType; devType = dev; dev = tmp;
1377
1378             dwFlags |= MCI_OPEN_TYPE;
1379             data.open.lpstrDeviceType = devType;
1380             devType = str_dup_upper(devType);
1381             dwFlags |= MCI_OPEN_ELEMENT;
1382             data.open.lpstrElementName = dev;
1383         } else if (DRIVER_GetLibName(dev, wszMci, buf, sizeof(buf))) {
1384             /* this is the name of a mci driver's type */
1385             tmp = strchrW(dev, ' ');
1386             if (tmp) *tmp = '\0';
1387             data.open.lpstrDeviceType = dev;
1388             devType = str_dup_upper(dev);
1389             if (tmp) *tmp = ' ';
1390             dwFlags |= MCI_OPEN_TYPE;
1391         } else {
1392             if ((devType = strstrW(args, wszTypeS)) != NULL) {
1393                 devType += 5;
1394                 tmp = strchrW(devType, ' ');
1395                 if (tmp) *tmp = '\0';
1396                 devType = str_dup_upper(devType);
1397                 if (tmp) *tmp = ' ';
1398                 /* dwFlags and lpstrDeviceType will be correctly set in ParseOpt loop */
1399             } else {
1400                 if ((dwRet = MCI_GetDevTypeFromFileName(dev, buf, sizeof(buf))))
1401                     goto errCleanUp;
1402
1403                 devType = str_dup_upper(buf);
1404             }
1405             dwFlags |= MCI_OPEN_ELEMENT;
1406             data.open.lpstrElementName = dev;
1407         }
1408         if (MCI_ALL_DEVICE_ID == uDevID) {
1409             dwRet = MCIERR_CANNOT_USE_ALL;
1410             goto errCleanUp;
1411         }
1412         if (!strstrW(args, wszSAliasS) && !dev) {
1413             dwRet = MCIERR_NEW_REQUIRES_ALIAS;
1414             goto errCleanUp;
1415         }
1416
1417         dwRet = MCI_LoadMciDriver(devType, &wmd);
1418         if (dwRet == MCIERR_DEVICE_NOT_INSTALLED)
1419             dwRet = MCIERR_INVALID_DEVICE_NAME;
1420         HeapFree(GetProcessHeap(), 0, devType);
1421         if (dwRet)
1422             goto errCleanUp;
1423     } else if ((MCI_ALL_DEVICE_ID != uDevID) && !(wmd = MCI_GetDriver(mciGetDeviceIDW(dev)))
1424                && (lpCmd = MCI_FindCommand(MCI_GetCommandTable(0), verb))) {
1425         /* auto-open uses the core command table */
1426         switch (MCI_GetMessage(lpCmd)) {
1427         case MCI_SOUND:   /* command does not use a device name */
1428         case MCI_SYSINFO:
1429             break;
1430         case MCI_CLOSE:   /* don't auto-open for close */
1431         case MCI_BREAK:   /* no auto-open for system commands */
1432             dwRet = MCIERR_INVALID_DEVICE_NAME;
1433             goto errCleanUp;
1434             break;
1435         default:
1436             {
1437                 static const WCHAR wszOpenWait[] = {'o','p','e','n',' ','%','s',' ','w','a','i','t',0};
1438                 WCHAR   buf[138], retbuf[6];
1439                 snprintfW(buf, sizeof(buf)/sizeof(WCHAR), wszOpenWait, dev);
1440                 /* open via mciSendString handles quoting, dev!file syntax and alias creation */
1441                 if ((dwRet = mciSendStringW(buf, retbuf, sizeof(retbuf)/sizeof(WCHAR), 0)) != 0)
1442                     goto errCleanUp;
1443                 auto_open = strtoulW(retbuf, NULL, 10);
1444                 TRACE("auto-opened %u for %s\n", auto_open, debugstr_w(dev));
1445
1446                 /* FIXME: test for notify flag (how to preparse?) before opening */
1447                 wmd = MCI_GetDriver(auto_open);
1448                 if (!wmd) {
1449                     ERR("No auto-open device %u\n", auto_open);
1450                     dwRet = MCIERR_INVALID_DEVICE_ID;
1451                     goto errCleanUp;
1452                 }
1453             }
1454         }
1455     }
1456
1457     /* get the verb in the different command tables */
1458     if (wmd) {
1459         /* try the device specific command table */
1460         lpCmd = MCI_FindCommand(wmd->uSpecificCmdTable, verb);
1461         if (!lpCmd) {
1462             /* try the type specific command table */
1463             if (wmd->uTypeCmdTable == MCI_COMMAND_TABLE_NOT_LOADED)
1464                 wmd->uTypeCmdTable = MCI_GetCommandTable(wmd->wType);
1465             if (wmd->uTypeCmdTable != MCI_NO_COMMAND_TABLE)
1466                 lpCmd = MCI_FindCommand(wmd->uTypeCmdTable, verb);
1467         }
1468     }
1469     /* try core command table */
1470     if (!lpCmd) lpCmd = MCI_FindCommand(MCI_GetCommandTable(0), verb);
1471
1472     if (!lpCmd) {
1473         TRACE("Command %s not found!\n", debugstr_w(verb));
1474         dwRet = MCIERR_UNRECOGNIZED_COMMAND;
1475         goto errCleanUp;
1476     }
1477     wMsg = MCI_GetMessage(lpCmd);
1478
1479     /* set return information */
1480     offset = sizeof(data.generic);
1481     switch (retType = MCI_GetReturnType(lpCmd)) {
1482     case 0:
1483         break;
1484     case MCI_INTEGER:
1485         offset += sizeof(DWORD);
1486         break;
1487     case MCI_STRING:
1488         data.sysinfo.lpstrReturn = lpstrRet;
1489         data.sysinfo.dwRetSize = uRetLen;
1490         offset = FIELD_OFFSET( MCI_SYSINFO_PARMSW, dwNumber );
1491         break;
1492     case MCI_RECT:
1493         offset += 4 * sizeof(DWORD);
1494         break;
1495 #ifdef MCI_INTEGER64
1496     case MCI_INTEGER64:
1497         offset += sizeof(DWORD_PTR);
1498         break;
1499 #endif
1500     default:
1501         ERR("oops\n");
1502     }
1503
1504     TRACE("verb=%s on dev=%s; offset=%d\n", 
1505           debugstr_w(verb), debugstr_w(dev), offset);
1506
1507     if ((dwRet = MCI_ParseOptArgs(data.dw, offset / sizeof(DWORD), lpCmd, args, &dwFlags)))
1508         goto errCleanUp;
1509
1510     /* set up call back */
1511     if (auto_open) {
1512         if (dwFlags & MCI_NOTIFY) {
1513             dwRet = MCIERR_NOTIFY_ON_AUTO_OPEN;
1514             goto errCleanUp;
1515         }
1516         /* FIXME: the command should get its own notification window set up and
1517          * ask for device closing while processing the notification mechanism.
1518          * hwndCallback = ...
1519          * dwFlags |= MCI_NOTIFY;
1520          * In the meantime special-case all commands but PLAY and RECORD below. */
1521     }
1522     if (dwFlags & MCI_NOTIFY) {
1523         data.generic.dwCallback = (DWORD_PTR)hwndCallback;
1524     }
1525
1526     switch (wMsg) {
1527     case MCI_OPEN:
1528         if (strcmpW(verb, wszOpen)) {
1529             FIXME("Cannot open with command %s\n", debugstr_w(verb));
1530             dwRet = MCIERR_INTERNAL;
1531             wMsg = 0;
1532             goto errCleanUp;
1533         }
1534         break;
1535     case MCI_SYSINFO:
1536         /* Requirements on dev depend on the flags:
1537          * alias with INSTALLNAME, name like "digitalvideo"
1538          * with QUANTITY and NAME. */
1539         {
1540             data.sysinfo.wDeviceType = MCI_ALL_DEVICE_ID;
1541             if (uDevID != MCI_ALL_DEVICE_ID) {
1542                 if (dwFlags & MCI_SYSINFO_INSTALLNAME)
1543                     wmd = MCI_GetDriver(mciGetDeviceIDW(dev));
1544                 else if (!(data.sysinfo.wDeviceType = MCI_GetDevTypeFromResource(dev))) {
1545                     dwRet = MCIERR_DEVICE_TYPE_REQUIRED;
1546                     goto errCleanUp;
1547                 }
1548             }
1549         }
1550         break;
1551     case MCI_SOUND:
1552         /* FIXME: name is optional, "sound" is a valid command.
1553          * FIXME: Parse "sound notify" as flag, not as name. */
1554         data.sound.lpstrSoundName = dev;
1555         dwFlags |= MCI_SOUND_NAME;
1556         break;
1557     }
1558
1559     TRACE("[%d, %s, %08x, %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x]\n",
1560           wmd ? wmd->wDeviceID : uDevID, MCI_MessageToString(wMsg), dwFlags,
1561           data.dw[0], data.dw[1], data.dw[2], data.dw[3], data.dw[4],
1562           data.dw[5], data.dw[6], data.dw[7], data.dw[8], data.dw[9]);
1563
1564     if (wMsg == MCI_OPEN) {
1565         if ((dwRet = MCI_FinishOpen(wmd, &data.open, dwFlags)))
1566             goto errCleanUp;
1567         /* FIXME: notification is not properly shared across two opens */
1568     } else {
1569         dwRet = MCI_SendCommand(wmd ? wmd->wDeviceID : uDevID, wMsg, dwFlags, (DWORD_PTR)&data);
1570     }
1571     TRACE("=> 1/ %x (%s)\n", dwRet, debugstr_w(lpstrRet));
1572     if (!LOWORD(dwRet)) {
1573         dwRet = MCI_HandleReturnValues(dwRet, wmd, retType, &data.generic, lpstrRet, uRetLen);
1574         TRACE("=> 2/ %x (%s)\n", dwRet, debugstr_w(lpstrRet));
1575     }
1576
1577 errCleanUp:
1578     if (auto_open) {
1579         /* PLAY and RECORD are the only known non-immediate commands */
1580         if (LOWORD(dwRet) || !(wMsg == MCI_PLAY || wMsg == MCI_RECORD))
1581             MCI_SendCommand(auto_open, MCI_CLOSE, 0, 0);
1582         else
1583             FIXME("leaking auto-open device %u\n", auto_open);
1584     }
1585     if (wMsg == MCI_OPEN && LOWORD(dwRet) && wmd)
1586         MCI_UnLoadMciDriver(wmd);
1587     HeapFree(GetProcessHeap(), 0, verb);
1588     return dwRet;
1589 }
1590
1591 /**************************************************************************
1592  *                              mciSendStringA                  [WINMM.@]
1593  */
1594 DWORD WINAPI mciSendStringA(LPCSTR lpstrCommand, LPSTR lpstrRet,
1595                             UINT uRetLen, HWND hwndCallback)
1596 {
1597     LPWSTR      lpwstrCommand;
1598     LPWSTR      lpwstrRet = NULL;
1599     UINT        ret;
1600     INT len;
1601
1602     /* FIXME: is there something to do with lpstrReturnString ? */
1603     len = MultiByteToWideChar( CP_ACP, 0, lpstrCommand, -1, NULL, 0 );
1604     lpwstrCommand = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
1605     MultiByteToWideChar( CP_ACP, 0, lpstrCommand, -1, lpwstrCommand, len );
1606     if (lpstrRet)
1607     {
1608         if (uRetLen) *lpstrRet = '\0'; /* NT-w2k3 use memset(lpstrRet, 0, uRetLen); */
1609         lpwstrRet = HeapAlloc(GetProcessHeap(), 0, uRetLen * sizeof(WCHAR));
1610         if (!lpwstrRet) {
1611             HeapFree( GetProcessHeap(), 0, lpwstrCommand );
1612             return MCIERR_OUT_OF_MEMORY;
1613         }
1614     }
1615     ret = mciSendStringW(lpwstrCommand, lpwstrRet, uRetLen, hwndCallback);
1616     if (!ret && lpwstrRet)
1617         WideCharToMultiByte( CP_ACP, 0, lpwstrRet, -1, lpstrRet, uRetLen, NULL, NULL );
1618     HeapFree(GetProcessHeap(), 0, lpwstrCommand);
1619     HeapFree(GetProcessHeap(), 0, lpwstrRet);
1620     return ret;
1621 }
1622
1623 /**************************************************************************
1624  *                              mciExecute                      [WINMM.@]
1625  */
1626 BOOL WINAPI mciExecute(LPCSTR lpstrCommand)
1627 {
1628     char        strRet[256];
1629     DWORD       ret;
1630
1631     TRACE("(%s)!\n", lpstrCommand);
1632
1633     ret = mciSendStringA(lpstrCommand, strRet, sizeof(strRet), 0);
1634     if (ret != 0) {
1635         if (!mciGetErrorStringA(ret, strRet, sizeof(strRet))) {
1636             sprintf(strRet, "Unknown MCI error (%d)", ret);
1637         }
1638         MessageBoxA(0, strRet, "Error in mciExecute()", MB_OK);
1639     }
1640     /* FIXME: what shall I return ? */
1641     return TRUE;
1642 }
1643
1644 /**************************************************************************
1645  *                      mciLoadCommandResource                  [WINMM.@]
1646  *
1647  * Strangely, this function only exists as a UNICODE one.
1648  */
1649 UINT WINAPI mciLoadCommandResource(HINSTANCE hInst, LPCWSTR resNameW, UINT type)
1650 {
1651     UINT        ret = MCI_NO_COMMAND_TABLE;
1652     HRSRC       hRsrc = 0;
1653     HGLOBAL     hMem;
1654
1655     TRACE("(%p, %s, %d)!\n", hInst, debugstr_w(resNameW), type);
1656
1657     /* if a file named "resname.mci" exits, then load resource "resname" from it
1658      * otherwise directly from driver
1659      * We don't support it (who uses this feature ?), but we check anyway
1660      */
1661     if (!type) {
1662 #if 0
1663         /* FIXME: we should put this back into order, but I never found a program
1664          * actually using this feature, so we may not need it
1665          */
1666         char            buf[128];
1667         OFSTRUCT        ofs;
1668
1669         strcat(strcpy(buf, resname), ".mci");
1670         if (OpenFile(buf, &ofs, OF_EXIST) != HFILE_ERROR) {
1671             FIXME("NIY: command table to be loaded from '%s'\n", ofs.szPathName);
1672         }
1673 #endif
1674     }
1675     if ((hRsrc = FindResourceW(hInst, resNameW, (LPWSTR)RT_RCDATA)) &&
1676         (hMem = LoadResource(hInst, hRsrc))) {
1677         ret = MCI_SetCommandTable(hMem, type);
1678         FreeResource(hMem);
1679     }
1680     else WARN("No command table found in module for %s\n", debugstr_w(resNameW));
1681
1682     TRACE("=> %04x\n", ret);
1683     return ret;
1684 }
1685
1686 /**************************************************************************
1687  *                      mciFreeCommandResource                  [WINMM.@]
1688  */
1689 BOOL WINAPI mciFreeCommandResource(UINT uTable)
1690 {
1691     TRACE("(%08x)!\n", uTable);
1692
1693     if (uTable >= MAX_MCICMDTABLE || !S_MciCmdTable[uTable].lpTable)
1694         return FALSE;
1695
1696     FreeResource(S_MciCmdTable[uTable].hMem);
1697     S_MciCmdTable[uTable].hMem = NULL;
1698     S_MciCmdTable[uTable].lpTable = NULL;
1699     HeapFree(GetProcessHeap(), 0, S_MciCmdTable[uTable].aVerbs);
1700     S_MciCmdTable[uTable].aVerbs = 0;
1701     S_MciCmdTable[uTable].nVerbs = 0;
1702     return TRUE;
1703 }
1704
1705 /**************************************************************************
1706  *                      MCI_Open                                [internal]
1707  */
1708 static  DWORD MCI_Open(DWORD dwParam, LPMCI_OPEN_PARMSW lpParms)
1709 {
1710     WCHAR                       strDevTyp[128];
1711     DWORD                       dwRet;
1712     LPWINE_MCIDRIVER            wmd = NULL;
1713
1714     TRACE("(%08X, %p)\n", dwParam, lpParms);
1715     if (lpParms == NULL) return MCIERR_NULL_PARAMETER_BLOCK;
1716
1717     /* only two low bytes are generic, the other ones are dev type specific */
1718 #define WINE_MCIDRIVER_SUPP     (0xFFFF0000|MCI_OPEN_SHAREABLE|MCI_OPEN_ELEMENT| \
1719                          MCI_OPEN_ALIAS|MCI_OPEN_TYPE|MCI_OPEN_TYPE_ID| \
1720                          MCI_NOTIFY|MCI_WAIT)
1721     if ((dwParam & ~WINE_MCIDRIVER_SUPP) != 0)
1722         FIXME("Unsupported yet dwFlags=%08X\n", dwParam & ~WINE_MCIDRIVER_SUPP);
1723 #undef WINE_MCIDRIVER_SUPP
1724
1725     strDevTyp[0] = 0;
1726
1727     if (dwParam & MCI_OPEN_TYPE) {
1728         if (dwParam & MCI_OPEN_TYPE_ID) {
1729             WORD uDevType = LOWORD(lpParms->lpstrDeviceType);
1730
1731             if (uDevType < MCI_DEVTYPE_FIRST ||
1732                 uDevType > MCI_DEVTYPE_LAST ||
1733                 !LoadStringW(hWinMM32Instance, uDevType,
1734                              strDevTyp, sizeof(strDevTyp) / sizeof(WCHAR))) {
1735                 dwRet = MCIERR_BAD_INTEGER;
1736                 goto errCleanUp;
1737             }
1738         } else {
1739             LPWSTR      ptr;
1740             if (lpParms->lpstrDeviceType == NULL) {
1741                 dwRet = MCIERR_NULL_PARAMETER_BLOCK;
1742                 goto errCleanUp;
1743             }
1744             strcpyW(strDevTyp, lpParms->lpstrDeviceType);
1745             ptr = strchrW(strDevTyp, '!');
1746             if (ptr) {
1747                 /* this behavior is not documented in windows. However, since, in
1748                  * some occasions, MCI_OPEN handling is translated by WinMM into
1749                  * a call to mciSendString("open <type>"); this code shall be correct
1750                  */
1751                 if (dwParam & MCI_OPEN_ELEMENT) {
1752                     ERR("Both MCI_OPEN_ELEMENT(%s) and %s are used\n",
1753                         debugstr_w(lpParms->lpstrElementName), 
1754                         debugstr_w(strDevTyp));
1755                     dwRet = MCIERR_UNRECOGNIZED_KEYWORD;
1756                     goto errCleanUp;
1757                 }
1758                 dwParam |= MCI_OPEN_ELEMENT;
1759                 *ptr++ = 0;
1760                 /* FIXME: not a good idea to write in user supplied buffer */
1761                 lpParms->lpstrElementName = ptr;
1762             }
1763
1764         }
1765         TRACE("devType=%s !\n", debugstr_w(strDevTyp));
1766     }
1767
1768     if (dwParam & MCI_OPEN_ELEMENT) {
1769         TRACE("lpstrElementName=%s\n", debugstr_w(lpParms->lpstrElementName));
1770
1771         if (dwParam & MCI_OPEN_ELEMENT_ID) {
1772             FIXME("Unsupported yet flag MCI_OPEN_ELEMENT_ID\n");
1773             dwRet = MCIERR_UNRECOGNIZED_KEYWORD;
1774             goto errCleanUp;
1775         }
1776
1777         if (!lpParms->lpstrElementName) {
1778             dwRet = MCIERR_NULL_PARAMETER_BLOCK;
1779             goto errCleanUp;
1780         }
1781
1782         /* type, if given as a parameter, supersedes file extension */
1783         if (!strDevTyp[0] &&
1784             MCI_GetDevTypeFromFileName(lpParms->lpstrElementName,
1785                                        strDevTyp, sizeof(strDevTyp))) {
1786             static const WCHAR wszCdAudio[] = {'C','D','A','U','D','I','O',0};
1787             if (GetDriveTypeW(lpParms->lpstrElementName) != DRIVE_CDROM) {
1788                 dwRet = MCIERR_EXTENSION_NOT_FOUND;
1789                 goto errCleanUp;
1790             }
1791             /* FIXME: this will not work if several CDROM drives are installed on the machine */
1792             strcpyW(strDevTyp, wszCdAudio);
1793         }
1794     }
1795
1796     if (strDevTyp[0] == 0) {
1797         FIXME("Couldn't load driver\n");
1798         dwRet = MCIERR_INVALID_DEVICE_NAME;
1799         goto errCleanUp;
1800     }
1801
1802     if (dwParam & MCI_OPEN_ALIAS) {
1803         TRACE("Alias=%s !\n", debugstr_w(lpParms->lpstrAlias));
1804         if (!lpParms->lpstrAlias) {
1805             dwRet = MCIERR_NULL_PARAMETER_BLOCK;
1806             goto errCleanUp;
1807         }
1808     }
1809
1810     if ((dwRet = MCI_LoadMciDriver(strDevTyp, &wmd))) {
1811         goto errCleanUp;
1812     }
1813
1814     if ((dwRet = MCI_FinishOpen(wmd, lpParms, dwParam))) {
1815         TRACE("Failed to open driver (MCI_OPEN_DRIVER) [%08x], closing\n", dwRet);
1816         /* FIXME: is dwRet the correct ret code ? */
1817         goto errCleanUp;
1818     }
1819
1820     /* only handled devices fall through */
1821     TRACE("wDevID=%04X wDeviceID=%d dwRet=%d\n", wmd->wDeviceID, lpParms->wDeviceID, dwRet);
1822     return 0;
1823
1824 errCleanUp:
1825     if (wmd) MCI_UnLoadMciDriver(wmd);
1826     return dwRet;
1827 }
1828
1829 /**************************************************************************
1830  *                      MCI_Close                               [internal]
1831  */
1832 static  DWORD MCI_Close(UINT wDevID, DWORD dwParam, LPMCI_GENERIC_PARMS lpParms)
1833 {
1834     DWORD               dwRet;
1835     LPWINE_MCIDRIVER    wmd;
1836
1837     TRACE("(%04x, %08X, %p)\n", wDevID, dwParam, lpParms);
1838
1839     /* Every device must handle MCI_NOTIFY on its own. */
1840     if ((UINT16)wDevID == (UINT16)MCI_ALL_DEVICE_ID) {
1841         while (MciDrivers) {
1842             /* Retrieve the device ID under lock, but send the message without,
1843              * the driver might be calling some winmm functions from another
1844              * thread before being fully stopped.
1845              */
1846             EnterCriticalSection(&WINMM_cs);
1847             if (!MciDrivers)
1848             {
1849                 LeaveCriticalSection(&WINMM_cs);
1850                 break;
1851             }
1852             wDevID = MciDrivers->wDeviceID;
1853             LeaveCriticalSection(&WINMM_cs);
1854             MCI_Close(wDevID, dwParam, lpParms);
1855         }
1856         return 0;
1857     }
1858
1859     if (!(wmd = MCI_GetDriver(wDevID))) {
1860         return MCIERR_INVALID_DEVICE_ID;
1861     }
1862
1863     dwRet = MCI_SendCommandFrom32(wDevID, MCI_CLOSE_DRIVER, dwParam, (DWORD_PTR)lpParms);
1864
1865     MCI_UnLoadMciDriver(wmd);
1866
1867     return dwRet;
1868 }
1869
1870 /**************************************************************************
1871  *                      MCI_WriteString                         [internal]
1872  */
1873 static DWORD MCI_WriteString(LPWSTR lpDstStr, DWORD dstSize, LPCWSTR lpSrcStr)
1874 {
1875     DWORD       ret = 0;
1876
1877     if (lpSrcStr) {
1878         if (dstSize <= strlenW(lpSrcStr)) {
1879             ret = MCIERR_PARAM_OVERFLOW;
1880         } else {
1881             strcpyW(lpDstStr, lpSrcStr);
1882         }
1883     } else {
1884         *lpDstStr = 0;
1885     }
1886     return ret;
1887 }
1888
1889 /**************************************************************************
1890  *                      MCI_Sysinfo                             [internal]
1891  */
1892 static  DWORD MCI_SysInfo(UINT uDevID, DWORD dwFlags, LPMCI_SYSINFO_PARMSW lpParms)
1893 {
1894     DWORD               ret = MCIERR_INVALID_DEVICE_ID, cnt = 0;
1895     WCHAR               buf[2048], *s, *p;
1896     LPWINE_MCIDRIVER    wmd;
1897     HKEY                hKey;
1898
1899     if (lpParms == NULL)                        return MCIERR_NULL_PARAMETER_BLOCK;
1900     if (lpParms->lpstrReturn == NULL)           return MCIERR_PARAM_OVERFLOW;
1901
1902     TRACE("(%08x, %08X, %p[num=%d, wDevTyp=%u])\n",
1903           uDevID, dwFlags, lpParms, lpParms->dwNumber, lpParms->wDeviceType);
1904     if ((WORD)MCI_ALL_DEVICE_ID == LOWORD(uDevID))
1905         uDevID = MCI_ALL_DEVICE_ID; /* Be compatible with Win9x */
1906
1907     switch (dwFlags & ~(MCI_SYSINFO_OPEN|MCI_NOTIFY|MCI_WAIT)) {
1908     case MCI_SYSINFO_QUANTITY:
1909         if (lpParms->dwRetSize < sizeof(DWORD))
1910             return MCIERR_PARAM_OVERFLOW;
1911         /* Win9x returns 0 for 0 < uDevID < (UINT16)MCI_ALL_DEVICE_ID */
1912         if (uDevID == MCI_ALL_DEVICE_ID) {
1913             /* wDeviceType == MCI_ALL_DEVICE_ID is not recognized. */
1914             if (dwFlags & MCI_SYSINFO_OPEN) {
1915                 TRACE("MCI_SYSINFO_QUANTITY: # of open MCI drivers\n");
1916                 EnterCriticalSection(&WINMM_cs);
1917                 for (wmd = MciDrivers; wmd; wmd = wmd->lpNext) {
1918                     cnt++;
1919                 }
1920                 LeaveCriticalSection(&WINMM_cs);
1921             } else {
1922                 TRACE("MCI_SYSINFO_QUANTITY: # of installed MCI drivers\n");
1923                 if (RegOpenKeyExW( HKEY_LOCAL_MACHINE, wszHklmMci,
1924                                    0, KEY_QUERY_VALUE, &hKey ) == ERROR_SUCCESS) {
1925                     RegQueryInfoKeyW( hKey, 0, 0, 0, &cnt, 0, 0, 0, 0, 0, 0, 0);
1926                     RegCloseKey( hKey );
1927                 }
1928                 if (GetPrivateProfileStringW(wszMci, 0, wszNull, buf, sizeof(buf) / sizeof(buf[0]), wszSystemIni))
1929                     for (s = buf; *s; s += strlenW(s) + 1) cnt++;
1930             }
1931         } else {
1932             if (dwFlags & MCI_SYSINFO_OPEN) {
1933                 TRACE("MCI_SYSINFO_QUANTITY: # of open MCI drivers of type %d\n", lpParms->wDeviceType);
1934                 EnterCriticalSection(&WINMM_cs);
1935                 for (wmd = MciDrivers; wmd; wmd = wmd->lpNext) {
1936                     if (wmd->wType == lpParms->wDeviceType) cnt++;
1937                 }
1938                 LeaveCriticalSection(&WINMM_cs);
1939             } else {
1940                 TRACE("MCI_SYSINFO_QUANTITY: # of installed MCI drivers of type %d\n", lpParms->wDeviceType);
1941                 FIXME("Don't know how to get # of MCI devices of a given type\n");
1942                 /* name = LoadStringW(hWinMM32Instance, LOWORD(lpParms->wDeviceType))
1943                  * then lookup registry and/or system.ini for name, ignoring digits suffix */
1944                 switch (LOWORD(lpParms->wDeviceType)) {
1945                 case MCI_DEVTYPE_CD_AUDIO:
1946                 case MCI_DEVTYPE_WAVEFORM_AUDIO:
1947                 case MCI_DEVTYPE_SEQUENCER:
1948                     cnt = 1;
1949                     break;
1950                 default: /* "digitalvideo" gets 0 because it's not in the registry */
1951                     cnt = 0;
1952                 }
1953             }
1954         }
1955         *(DWORD*)lpParms->lpstrReturn = cnt;
1956         TRACE("(%d) => '%d'\n", lpParms->dwNumber, *(DWORD*)lpParms->lpstrReturn);
1957         ret = MCI_INTEGER_RETURNED;
1958         /* return ret; Only Win9x sends a notification in this case. */
1959         break;
1960     case MCI_SYSINFO_INSTALLNAME:
1961         TRACE("MCI_SYSINFO_INSTALLNAME\n");
1962         if ((wmd = MCI_GetDriver(uDevID))) {
1963             ret = MCI_WriteString(lpParms->lpstrReturn, lpParms->dwRetSize,
1964                                   wmd->lpstrDeviceType);
1965         } else {
1966             ret = (uDevID == MCI_ALL_DEVICE_ID)
1967                 ? MCIERR_CANNOT_USE_ALL : MCIERR_INVALID_DEVICE_NAME;
1968         }
1969         TRACE("(%d) => %s\n", lpParms->dwNumber, debugstr_w(lpParms->lpstrReturn));
1970         break;
1971     case MCI_SYSINFO_NAME:
1972         s = NULL;
1973         if (dwFlags & MCI_SYSINFO_OPEN) {
1974             /* Win9x returns 0 for 0 < uDevID < (UINT16)MCI_ALL_DEVICE_ID */
1975             TRACE("MCI_SYSINFO_NAME: nth alias of type %d\n",
1976                   uDevID == MCI_ALL_DEVICE_ID ? MCI_ALL_DEVICE_ID : lpParms->wDeviceType);
1977             EnterCriticalSection(&WINMM_cs);
1978             for (wmd = MciDrivers; wmd; wmd = wmd->lpNext) {
1979                 /* wDeviceType == MCI_ALL_DEVICE_ID is not recognized. */
1980                 if (uDevID == MCI_ALL_DEVICE_ID ||
1981                     lpParms->wDeviceType == wmd->wType) {
1982                     cnt++;
1983                     if (cnt == lpParms->dwNumber) {
1984                         s = wmd->lpstrAlias;
1985                         break;
1986                     }
1987                 }
1988             }
1989             LeaveCriticalSection(&WINMM_cs);
1990             ret = s ? MCI_WriteString(lpParms->lpstrReturn, lpParms->dwRetSize, s) : MCIERR_OUTOFRANGE;
1991         } else if (MCI_ALL_DEVICE_ID == uDevID) {
1992             TRACE("MCI_SYSINFO_NAME: device #%d\n", lpParms->dwNumber);
1993             if (RegOpenKeyExW( HKEY_LOCAL_MACHINE, wszHklmMci, 0, 
1994                                KEY_QUERY_VALUE, &hKey ) == ERROR_SUCCESS) {
1995                 if (RegQueryInfoKeyW( hKey, 0, 0, 0, &cnt, 
1996                                       0, 0, 0, 0, 0, 0, 0) == ERROR_SUCCESS && 
1997                     lpParms->dwNumber <= cnt) {
1998                     DWORD bufLen = sizeof(buf)/sizeof(buf[0]);
1999                     if (RegEnumKeyExW(hKey, lpParms->dwNumber - 1, 
2000                                       buf, &bufLen, 0, 0, 0, 0) == ERROR_SUCCESS)
2001                         s = buf;
2002                 }
2003                 RegCloseKey( hKey );
2004             }
2005             if (!s) {
2006                 if (GetPrivateProfileStringW(wszMci, 0, wszNull, buf, sizeof(buf) / sizeof(buf[0]), wszSystemIni)) {
2007                     for (p = buf; *p; p += strlenW(p) + 1, cnt++) {
2008                         TRACE("%d: %s\n", cnt, debugstr_w(p));
2009                         if (cnt == lpParms->dwNumber - 1) {
2010                             s = p;
2011                             break;
2012                         }
2013                     }
2014                 }
2015             }
2016             ret = s ? MCI_WriteString(lpParms->lpstrReturn, lpParms->dwRetSize, s) : MCIERR_OUTOFRANGE;
2017         } else {
2018             FIXME("MCI_SYSINFO_NAME: nth device of type %d\n", lpParms->wDeviceType);
2019             /* Cheating: what is asked for is the nth device from the registry. */
2020             if (1 != lpParms->dwNumber || /* Handle only one of each kind. */
2021                 lpParms->wDeviceType < MCI_DEVTYPE_FIRST || lpParms->wDeviceType > MCI_DEVTYPE_LAST)
2022                 ret = MCIERR_OUTOFRANGE;
2023             else {
2024                 LoadStringW(hWinMM32Instance, LOWORD(lpParms->wDeviceType),
2025                             lpParms->lpstrReturn, lpParms->dwRetSize);
2026                 ret = 0;
2027             }
2028         }
2029         TRACE("(%d) => %s\n", lpParms->dwNumber, debugstr_w(lpParms->lpstrReturn));
2030         break;
2031     default:
2032         TRACE("Unsupported flag value=%08x\n", dwFlags);
2033         ret = MCIERR_UNRECOGNIZED_KEYWORD;
2034     }
2035     if ((dwFlags & MCI_NOTIFY) && HRESULT_CODE(ret)==0)
2036         mciDriverNotify((HWND)lpParms->dwCallback, uDevID, MCI_NOTIFY_SUCCESSFUL);
2037     return ret;
2038 }
2039
2040 /**************************************************************************
2041  *                      MCI_Break                               [internal]
2042  */
2043 static  DWORD MCI_Break(UINT wDevID, DWORD dwFlags, LPMCI_BREAK_PARMS lpParms)
2044 {
2045     DWORD       dwRet = 0;
2046
2047     if (lpParms == NULL)        return MCIERR_NULL_PARAMETER_BLOCK;
2048     FIXME("(%04x) vkey %04X stub\n", dwFlags, lpParms->nVirtKey);
2049
2050     if (MMSYSERR_NOERROR==dwRet && (dwFlags & MCI_NOTIFY))
2051         mciDriverNotify((HWND)lpParms->dwCallback, wDevID, MCI_NOTIFY_SUCCESSFUL);
2052     return dwRet;
2053 }
2054
2055 /**************************************************************************
2056  *                      MCI_Sound                               [internal]
2057  */
2058 static  DWORD MCI_Sound(UINT wDevID, DWORD dwFlags, LPMCI_SOUND_PARMSW lpParms)
2059 {
2060     DWORD       dwRet;
2061
2062     if (dwFlags & MCI_SOUND_NAME) {
2063         if (lpParms == NULL)    return MCIERR_NULL_PARAMETER_BLOCK;
2064         else dwRet = PlaySoundW(lpParms->lpstrSoundName, NULL,
2065                                 SND_ALIAS    | (dwFlags & MCI_WAIT ? SND_SYNC : SND_ASYNC))
2066                 ? 0 : MCIERR_HARDWARE;
2067     } else   dwRet = PlaySoundW((LPCWSTR)SND_ALIAS_SYSTEMDEFAULT, NULL,
2068                                 SND_ALIAS_ID | (dwFlags & MCI_WAIT ? SND_SYNC : SND_ASYNC))
2069                 ? 0 : MCIERR_HARDWARE;
2070
2071     if (!dwRet && lpParms && (dwFlags & MCI_NOTIFY))
2072         mciDriverNotify((HWND)lpParms->dwCallback, wDevID, MCI_NOTIFY_SUCCESSFUL);
2073     return dwRet;
2074 }
2075
2076 /**************************************************************************
2077  *                      MCI_SendCommand                         [internal]
2078  */
2079 DWORD   MCI_SendCommand(UINT wDevID, UINT16 wMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
2080 {
2081     DWORD               dwRet = MCIERR_UNRECOGNIZED_COMMAND;
2082
2083     switch (wMsg) {
2084     case MCI_OPEN:
2085         dwRet = MCI_Open(dwParam1, (LPMCI_OPEN_PARMSW)dwParam2);
2086         break;
2087     case MCI_CLOSE:
2088         dwRet = MCI_Close(wDevID, dwParam1, (LPMCI_GENERIC_PARMS)dwParam2);
2089         break;
2090     case MCI_SYSINFO:
2091         dwRet = MCI_SysInfo(wDevID, dwParam1, (LPMCI_SYSINFO_PARMSW)dwParam2);
2092         break;
2093     case MCI_BREAK:
2094         dwRet = MCI_Break(wDevID, dwParam1, (LPMCI_BREAK_PARMS)dwParam2);
2095         break;
2096     case MCI_SOUND:
2097         dwRet = MCI_Sound(wDevID, dwParam1, (LPMCI_SOUND_PARMSW)dwParam2);
2098         break;
2099     default:
2100       if ((UINT16)wDevID == (UINT16)MCI_ALL_DEVICE_ID) {
2101             FIXME("unhandled MCI_ALL_DEVICE_ID\n");
2102             dwRet = MCIERR_CANNOT_USE_ALL;
2103         } else {
2104             dwRet = MCI_SendCommandFrom32(wDevID, wMsg, dwParam1, dwParam2);
2105         }
2106         break;
2107     }
2108     return dwRet;
2109 }
2110
2111 /**************************************************************************
2112  *                              MCI_CleanUp                     [internal]
2113  *
2114  * Some MCI commands need to be cleaned-up (when not called from
2115  * mciSendString), because MCI drivers return extra information for string
2116  * transformation. This function gets rid of them.
2117  */
2118 static LRESULT  MCI_CleanUp(LRESULT dwRet, UINT wMsg, DWORD_PTR dwParam2)
2119 {
2120     if (LOWORD(dwRet))
2121         return LOWORD(dwRet);
2122
2123     switch (wMsg) {
2124     case MCI_GETDEVCAPS:
2125         switch (dwRet & 0xFFFF0000ul) {
2126         case 0:
2127         case MCI_COLONIZED3_RETURN:
2128         case MCI_COLONIZED4_RETURN:
2129         case MCI_INTEGER_RETURNED:
2130             /* nothing to do */
2131             break;
2132         case MCI_RESOURCE_RETURNED:
2133         case MCI_RESOURCE_RETURNED|MCI_RESOURCE_DRIVER:
2134             {
2135                 LPMCI_GETDEVCAPS_PARMS  lmgp;
2136
2137                 lmgp = (LPMCI_GETDEVCAPS_PARMS)dwParam2;
2138                 TRACE("Changing %08x to %08x\n", lmgp->dwReturn, LOWORD(lmgp->dwReturn));
2139                 lmgp->dwReturn = LOWORD(lmgp->dwReturn);
2140             }
2141             break;
2142         default:
2143             FIXME("Unsupported value for hiword (%04x) returned by DriverProc(%s)\n",
2144                   HIWORD(dwRet), MCI_MessageToString(wMsg));
2145         }
2146         break;
2147     case MCI_STATUS:
2148         switch (dwRet & 0xFFFF0000ul) {
2149         case 0:
2150         case MCI_COLONIZED3_RETURN:
2151         case MCI_COLONIZED4_RETURN:
2152         case MCI_INTEGER_RETURNED:
2153             /* nothing to do */
2154             break;
2155         case MCI_RESOURCE_RETURNED:
2156         case MCI_RESOURCE_RETURNED|MCI_RESOURCE_DRIVER:
2157             {
2158                 LPMCI_STATUS_PARMS      lsp;
2159
2160                 lsp = (LPMCI_STATUS_PARMS)dwParam2;
2161                 TRACE("Changing %08lx to %08x\n", lsp->dwReturn, LOWORD(lsp->dwReturn));
2162                 lsp->dwReturn = LOWORD(lsp->dwReturn);
2163             }
2164             break;
2165         default:
2166             FIXME("Unsupported value for hiword (%04x) returned by DriverProc(%s)\n",
2167                   HIWORD(dwRet), MCI_MessageToString(wMsg));
2168         }
2169         break;
2170     case MCI_SYSINFO:
2171         switch (dwRet & 0xFFFF0000ul) {
2172         case 0:
2173         case MCI_INTEGER_RETURNED:
2174             /* nothing to do */
2175             break;
2176         default:
2177             FIXME("Unsupported value for hiword (%04x)\n", HIWORD(dwRet));
2178         }
2179         break;
2180     default:
2181         if (HIWORD(dwRet)) {
2182             FIXME("Got non null hiword for dwRet=0x%08lx for command %s\n",
2183                   dwRet, MCI_MessageToString(wMsg));
2184         }
2185         break;
2186     }
2187     return LOWORD(dwRet);
2188 }
2189
2190 /**************************************************************************
2191  *                              mciGetErrorStringW              [WINMM.@]
2192  */
2193 BOOL WINAPI mciGetErrorStringW(MCIERROR wError, LPWSTR lpstrBuffer, UINT uLength)
2194 {
2195     BOOL                ret = FALSE;
2196
2197     if (lpstrBuffer != NULL && uLength > 0 &&
2198         wError >= MCIERR_BASE && wError <= MCIERR_CUSTOM_DRIVER_BASE) {
2199
2200         if (LoadStringW(hWinMM32Instance, wError, lpstrBuffer, uLength) > 0) {
2201             ret = TRUE;
2202         }
2203     }
2204     return ret;
2205 }
2206
2207 /**************************************************************************
2208  *                              mciGetErrorStringA              [WINMM.@]
2209  */
2210 BOOL WINAPI mciGetErrorStringA(MCIERROR dwError, LPSTR lpstrBuffer, UINT uLength)
2211 {
2212     BOOL                ret = FALSE;
2213
2214     if (lpstrBuffer != NULL && uLength > 0 &&
2215         dwError >= MCIERR_BASE && dwError <= MCIERR_CUSTOM_DRIVER_BASE) {
2216
2217         if (LoadStringA(hWinMM32Instance, dwError, lpstrBuffer, uLength) > 0) {
2218             ret = TRUE;
2219         }
2220     }
2221     return ret;
2222 }
2223
2224 /**************************************************************************
2225  *                      mciDriverNotify                         [WINMM.@]
2226  */
2227 BOOL WINAPI mciDriverNotify(HWND hWndCallBack, MCIDEVICEID wDevID, UINT wStatus)
2228 {
2229     TRACE("(%p, %04x, %04X)\n", hWndCallBack, wDevID, wStatus);
2230
2231     return PostMessageW(hWndCallBack, MM_MCINOTIFY, wStatus, wDevID);
2232 }
2233
2234 /**************************************************************************
2235  *                      mciGetDriverData                        [WINMM.@]
2236  */
2237 DWORD_PTR WINAPI mciGetDriverData(MCIDEVICEID uDeviceID)
2238 {
2239     LPWINE_MCIDRIVER    wmd;
2240
2241     TRACE("(%04x)\n", uDeviceID);
2242
2243     wmd = MCI_GetDriver(uDeviceID);
2244
2245     if (!wmd) {
2246         WARN("Bad uDeviceID\n");
2247         return 0L;
2248     }
2249
2250     return wmd->dwPrivate;
2251 }
2252
2253 /**************************************************************************
2254  *                      mciSetDriverData                        [WINMM.@]
2255  */
2256 BOOL WINAPI mciSetDriverData(MCIDEVICEID uDeviceID, DWORD_PTR data)
2257 {
2258     LPWINE_MCIDRIVER    wmd;
2259
2260     TRACE("(%04x, %08lx)\n", uDeviceID, data);
2261
2262     wmd = MCI_GetDriver(uDeviceID);
2263
2264     if (!wmd) {
2265         WARN("Bad uDeviceID\n");
2266         return FALSE;
2267     }
2268
2269     wmd->dwPrivate = data;
2270     return TRUE;
2271 }
2272
2273 /**************************************************************************
2274  *                              mciSendCommandW                 [WINMM.@]
2275  *
2276  */
2277 DWORD WINAPI mciSendCommandW(MCIDEVICEID wDevID, UINT wMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
2278 {
2279     DWORD       dwRet;
2280
2281     TRACE("(%08x, %s, %08lx, %08lx)\n",
2282           wDevID, MCI_MessageToString(wMsg), dwParam1, dwParam2);
2283
2284     dwRet = MCI_SendCommand(wDevID, wMsg, dwParam1, dwParam2);
2285     dwRet = MCI_CleanUp(dwRet, wMsg, dwParam2);
2286     TRACE("=> %08x\n", dwRet);
2287     return dwRet;
2288 }
2289
2290 /**************************************************************************
2291  *                              mciSendCommandA                 [WINMM.@]
2292  */
2293 DWORD WINAPI mciSendCommandA(MCIDEVICEID wDevID, UINT wMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
2294 {
2295     DWORD ret;
2296     int mapped;
2297
2298     TRACE("(%08x, %s, %08lx, %08lx)\n",
2299           wDevID, MCI_MessageToString(wMsg), dwParam1, dwParam2);
2300
2301     mapped = MCI_MapMsgAtoW(wMsg, dwParam1, &dwParam2);
2302     if (mapped == -1)
2303     {
2304         FIXME("message %04x mapping failed\n", wMsg);
2305         return MCIERR_OUT_OF_MEMORY;
2306     }
2307     ret = mciSendCommandW(wDevID, wMsg, dwParam1, dwParam2);
2308     if (mapped)
2309         MCI_UnmapMsgAtoW(wMsg, dwParam1, dwParam2, ret);
2310     return ret;
2311 }
2312
2313 /**************************************************************************
2314  *                              mciGetDeviceIDA                 [WINMM.@]
2315  */
2316 UINT WINAPI mciGetDeviceIDA(LPCSTR lpstrName)
2317 {
2318     LPWSTR w = MCI_strdupAtoW(lpstrName);
2319     UINT ret = MCIERR_OUT_OF_MEMORY;
2320
2321     if (w)
2322     {
2323         ret = mciGetDeviceIDW(w);
2324         HeapFree(GetProcessHeap(), 0, w);
2325     }
2326     return ret;
2327 }
2328
2329 /**************************************************************************
2330  *                              mciGetDeviceIDW                 [WINMM.@]
2331  */
2332 UINT WINAPI mciGetDeviceIDW(LPCWSTR lpwstrName)
2333 {
2334     return MCI_GetDriverFromString(lpwstrName); 
2335 }
2336
2337 /**************************************************************************
2338  *                              MCI_DefYieldProc                [internal]
2339  */
2340 static UINT WINAPI MCI_DefYieldProc(MCIDEVICEID wDevID, DWORD data)
2341 {
2342     INT16       ret;
2343     MSG         msg;
2344
2345     TRACE("(0x%04x, 0x%08x)\n", wDevID, data);
2346
2347     if ((HIWORD(data) != 0 && HWND_16(GetActiveWindow()) != HIWORD(data)) ||
2348         (GetAsyncKeyState(LOWORD(data)) & 1) == 0) {
2349         PeekMessageW(&msg, 0, 0, 0, PM_REMOVE | PM_QS_SENDMESSAGE);
2350         ret = 0;
2351     } else {
2352         msg.hwnd = HWND_32(HIWORD(data));
2353         while (!PeekMessageW(&msg, msg.hwnd, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE));
2354         ret = -1;
2355     }
2356     return ret;
2357 }
2358
2359 /**************************************************************************
2360  *                              mciSetYieldProc                 [WINMM.@]
2361  */
2362 BOOL WINAPI mciSetYieldProc(MCIDEVICEID uDeviceID, YIELDPROC fpYieldProc, DWORD dwYieldData)
2363 {
2364     LPWINE_MCIDRIVER    wmd;
2365
2366     TRACE("(%u, %p, %08x)\n", uDeviceID, fpYieldProc, dwYieldData);
2367
2368     if (!(wmd = MCI_GetDriver(uDeviceID))) {
2369         WARN("Bad uDeviceID\n");
2370         return FALSE;
2371     }
2372
2373     wmd->lpfnYieldProc = fpYieldProc;
2374     wmd->dwYieldData   = dwYieldData;
2375
2376     return TRUE;
2377 }
2378
2379 /**************************************************************************
2380  *                              mciGetDeviceIDFromElementIDA    [WINMM.@]
2381  */
2382 UINT WINAPI mciGetDeviceIDFromElementIDA(DWORD dwElementID, LPCSTR lpstrType)
2383 {
2384     LPWSTR w = MCI_strdupAtoW(lpstrType);
2385     UINT ret = 0;
2386
2387     if (w)
2388     {
2389         ret = mciGetDeviceIDFromElementIDW(dwElementID, w);
2390         HeapFree(GetProcessHeap(), 0, w);
2391     }
2392     return ret;
2393 }
2394
2395 /**************************************************************************
2396  *                              mciGetDeviceIDFromElementIDW    [WINMM.@]
2397  */
2398 UINT WINAPI mciGetDeviceIDFromElementIDW(DWORD dwElementID, LPCWSTR lpstrType)
2399 {
2400     /* FIXME: that's rather strange, there is no
2401      * mciGetDeviceIDFromElementID32A in winmm.spec
2402      */
2403     FIXME("(%u, %s) stub\n", dwElementID, debugstr_w(lpstrType));
2404     return 0;
2405 }
2406
2407 /**************************************************************************
2408  *                              mciGetYieldProc                 [WINMM.@]
2409  */
2410 YIELDPROC WINAPI mciGetYieldProc(MCIDEVICEID uDeviceID, DWORD* lpdwYieldData)
2411 {
2412     LPWINE_MCIDRIVER    wmd;
2413
2414     TRACE("(%u, %p)\n", uDeviceID, lpdwYieldData);
2415
2416     if (!(wmd = MCI_GetDriver(uDeviceID))) {
2417         WARN("Bad uDeviceID\n");
2418         return NULL;
2419     }
2420     if (!wmd->lpfnYieldProc) {
2421         WARN("No proc set\n");
2422         return NULL;
2423     }
2424     if (lpdwYieldData) *lpdwYieldData = wmd->dwYieldData;
2425     return wmd->lpfnYieldProc;
2426 }
2427
2428 /**************************************************************************
2429  *                              mciGetCreatorTask               [WINMM.@]
2430  */
2431 HTASK WINAPI mciGetCreatorTask(MCIDEVICEID uDeviceID)
2432 {
2433     LPWINE_MCIDRIVER    wmd;
2434     HTASK ret = 0;
2435
2436     if ((wmd = MCI_GetDriver(uDeviceID))) ret = (HTASK)(DWORD_PTR)wmd->CreatorThread;
2437
2438     TRACE("(%u) => %p\n", uDeviceID, ret);
2439     return ret;
2440 }
2441
2442 /**************************************************************************
2443  *                      mciDriverYield                          [WINMM.@]
2444  */
2445 UINT WINAPI mciDriverYield(MCIDEVICEID uDeviceID)
2446 {
2447     LPWINE_MCIDRIVER    wmd;
2448     UINT                ret = 0;
2449
2450     TRACE("(%04x)\n", uDeviceID);
2451
2452     if (!(wmd = MCI_GetDriver(uDeviceID)) || !wmd->lpfnYieldProc) {
2453         MSG msg;
2454         PeekMessageW(&msg, 0, 0, 0, PM_REMOVE | PM_QS_SENDMESSAGE);
2455     } else {
2456         ret = wmd->lpfnYieldProc(uDeviceID, wmd->dwYieldData);
2457     }
2458
2459     return ret;
2460 }