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