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