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