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