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