msvcrt: Fix MSVC build in locale.c.
[wine] / dlls / mcicda / mcicda.c
1 /*
2  * MCI driver for audio CD (MCICDA)
3  *
4  * Copyright 1994    Martin Ayotte
5  * Copyright 1998-99 Eric Pouech
6  * Copyright 2000    Andreas Mohr
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <string.h>
27
28 #define WIN32_NO_STATUS
29 #include "windef.h"
30 #include "winbase.h"
31 #include "wingdi.h"
32 #include "winuser.h"
33 #include "wownt32.h"
34 #include "mmddk.h"
35 #include "winioctl.h"
36 #include "ntddcdrm.h"
37 #include "winternl.h"
38 #include "wine/debug.h"
39 #include "wine/unicode.h"
40 #include "dsound.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(mcicda);
43
44 #define CDFRAMES_PERSEC                 75
45 #define CDFRAMES_PERMIN                 (CDFRAMES_PERSEC * 60)
46 #define FRAME_OF_ADDR(a) ((a)[1] * CDFRAMES_PERMIN + (a)[2] * CDFRAMES_PERSEC + (a)[3])
47 #define FRAME_OF_TOC(toc, idx)  FRAME_OF_ADDR((toc).TrackData[idx - (toc).FirstTrack].Address)
48
49 /* Defined by red-book standard; do not change! */
50 #define RAW_SECTOR_SIZE  (2352)
51
52 /* Must be >= RAW_SECTOR_SIZE */
53 #define CDDA_FRAG_SIZE   (32768)
54 /* Must be >= 2 */
55 #define CDDA_FRAG_COUNT  (3)
56
57 typedef struct {
58     UINT                wDevID;
59     int                 nUseCount;          /* Incremented for each shared open */
60     BOOL                fShareable;         /* TRUE if first open was shareable */
61     MCIDEVICEID         wNotifyDeviceID;    /* MCI device ID with a pending notification */
62     HANDLE              hCallback;          /* Callback handle for pending notification */
63     DWORD               dwTimeFormat;
64     HANDLE              handle;
65
66     /* The following are used for digital playback only */
67     HANDLE hThread;
68     HANDLE stopEvent;
69     DWORD start, end;
70
71     IDirectSound *dsObj;
72     IDirectSoundBuffer *dsBuf;
73
74     CRITICAL_SECTION cs;
75 } WINE_MCICDAUDIO;
76
77 /*-----------------------------------------------------------------------*/
78
79 typedef HRESULT(WINAPI*LPDIRECTSOUNDCREATE)(LPCGUID,LPDIRECTSOUND*,LPUNKNOWN);
80 static LPDIRECTSOUNDCREATE pDirectSoundCreate;
81
82 static DWORD CALLBACK MCICDA_playLoop(void *ptr)
83 {
84     WINE_MCICDAUDIO *wmcda = (WINE_MCICDAUDIO*)ptr;
85     DWORD lastPos, curPos, endPos, br;
86     void *cdData;
87     DWORD lockLen, fragLen;
88     DSBCAPS caps;
89     RAW_READ_INFO rdInfo;
90     HRESULT hr = DS_OK;
91
92     memset(&caps, 0, sizeof(caps));
93     caps.dwSize = sizeof(caps);
94     hr = IDirectSoundBuffer_GetCaps(wmcda->dsBuf, &caps);
95
96     fragLen = caps.dwBufferBytes/CDDA_FRAG_COUNT;
97     curPos = lastPos = 0;
98     endPos = ~0u;
99     while (SUCCEEDED(hr) && endPos != lastPos &&
100            WaitForSingleObject(wmcda->stopEvent, 0) != WAIT_OBJECT_0) {
101         hr = IDirectSoundBuffer_GetCurrentPosition(wmcda->dsBuf, &curPos, NULL);
102         if ((curPos-lastPos+caps.dwBufferBytes)%caps.dwBufferBytes < fragLen) {
103             Sleep(1);
104             continue;
105         }
106
107         EnterCriticalSection(&wmcda->cs);
108         rdInfo.DiskOffset.QuadPart = wmcda->start<<11;
109         rdInfo.SectorCount = min(fragLen/RAW_SECTOR_SIZE, wmcda->end-wmcda->start);
110         rdInfo.TrackMode = CDDA;
111
112         hr = IDirectSoundBuffer_Lock(wmcda->dsBuf, lastPos, fragLen, &cdData, &lockLen, NULL, NULL, 0);
113         if (hr == DSERR_BUFFERLOST) {
114             if(FAILED(IDirectSoundBuffer_Restore(wmcda->dsBuf)) ||
115                FAILED(IDirectSoundBuffer_Play(wmcda->dsBuf, 0, 0, DSBPLAY_LOOPING))) {
116                 LeaveCriticalSection(&wmcda->cs);
117                 break;
118             }
119             hr = IDirectSoundBuffer_Lock(wmcda->dsBuf, lastPos, fragLen, &cdData, &lockLen, NULL, NULL, 0);
120         }
121
122         if (SUCCEEDED(hr)) {
123             if (rdInfo.SectorCount > 0) {
124                 if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_RAW_READ, &rdInfo, sizeof(rdInfo), cdData, lockLen, &br, NULL))
125                     WARN("CD read failed at sector %d: 0x%x\n", wmcda->start, GetLastError());
126             }
127             if (rdInfo.SectorCount*RAW_SECTOR_SIZE < lockLen) {
128                 if(endPos == ~0u) endPos = lastPos;
129                 memset((BYTE*)cdData + rdInfo.SectorCount*RAW_SECTOR_SIZE, 0,
130                        lockLen - rdInfo.SectorCount*RAW_SECTOR_SIZE);
131             }
132             hr = IDirectSoundBuffer_Unlock(wmcda->dsBuf, cdData, lockLen, NULL, 0);
133         }
134
135         lastPos += fragLen;
136         lastPos %= caps.dwBufferBytes;
137         wmcda->start += rdInfo.SectorCount;
138
139         LeaveCriticalSection(&wmcda->cs);
140     }
141     IDirectSoundBuffer_Stop(wmcda->dsBuf);
142     SetEvent(wmcda->stopEvent);
143
144     /* A design bug in native: the independent CD player called by the
145      * MCI has no means to signal end of playing, therefore the MCI
146      * notification is left hanging.  MCI_NOTIFY_SUPERSEDED will be
147      * signaled by the next command that has MCI_NOTIFY set (or
148      * MCI_NOTIFY_ABORTED for MCI_PLAY). */
149
150     return 0;
151 }
152
153
154
155 /**************************************************************************
156  *                              MCICDA_drvOpen                  [internal]
157  */
158 static  DWORD   MCICDA_drvOpen(LPCWSTR str, LPMCI_OPEN_DRIVER_PARMSW modp)
159 {
160     static HMODULE dsHandle;
161     WINE_MCICDAUDIO*    wmcda;
162
163     if (!modp) return 0xFFFFFFFF;
164     /* FIXME: MCIERR_CANNOT_LOAD_DRIVER if there's no drive of type CD-ROM */
165
166     wmcda = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WINE_MCICDAUDIO));
167
168     if (!wmcda)
169         return 0;
170
171     if (!dsHandle) {
172         dsHandle = LoadLibraryA("dsound.dll");
173         if(dsHandle)
174             pDirectSoundCreate = (LPDIRECTSOUNDCREATE)GetProcAddress(dsHandle, "DirectSoundCreate");
175     }
176
177     wmcda->wDevID = modp->wDeviceID;
178     mciSetDriverData(wmcda->wDevID, (DWORD_PTR)wmcda);
179     modp->wCustomCommandTable = MCI_NO_COMMAND_TABLE;
180     modp->wType = MCI_DEVTYPE_CD_AUDIO;
181     InitializeCriticalSection(&wmcda->cs);
182     return modp->wDeviceID;
183 }
184
185 /**************************************************************************
186  *                              MCICDA_drvClose                 [internal]
187  */
188 static  DWORD   MCICDA_drvClose(DWORD dwDevID)
189 {
190     WINE_MCICDAUDIO*  wmcda = (WINE_MCICDAUDIO*)mciGetDriverData(dwDevID);
191
192     if (wmcda) {
193         DeleteCriticalSection(&wmcda->cs);
194         HeapFree(GetProcessHeap(), 0, wmcda);
195         mciSetDriverData(dwDevID, 0);
196     }
197     return (dwDevID == 0xFFFFFFFF) ? 1 : 0;
198 }
199
200 /**************************************************************************
201  *                              MCICDA_GetOpenDrv               [internal]
202  */
203 static WINE_MCICDAUDIO*  MCICDA_GetOpenDrv(UINT wDevID)
204 {
205     WINE_MCICDAUDIO*    wmcda = (WINE_MCICDAUDIO*)mciGetDriverData(wDevID);
206
207     if (wmcda == NULL || wmcda->nUseCount == 0) {
208         WARN("Invalid wDevID=%u\n", wDevID);
209         return 0;
210     }
211     return wmcda;
212 }
213
214 /**************************************************************************
215  *                              MCICDA_mciNotify                [internal]
216  *
217  * Notifications in MCI work like a 1-element queue.
218  * Each new notification request supersedes the previous one.
219  */
220 static void MCICDA_Notify(DWORD_PTR hWndCallBack, WINE_MCICDAUDIO* wmcda, UINT wStatus)
221 {
222     MCIDEVICEID wDevID = wmcda->wNotifyDeviceID;
223     HANDLE old = InterlockedExchangePointer(&wmcda->hCallback, NULL);
224     if (old) mciDriverNotify(old, wDevID, MCI_NOTIFY_SUPERSEDED);
225     mciDriverNotify(HWND_32(LOWORD(hWndCallBack)), wDevID, wStatus);
226 }
227
228 /**************************************************************************
229  *                              MCICDA_GetStatus                [internal]
230  */
231 static  DWORD    MCICDA_GetStatus(WINE_MCICDAUDIO* wmcda)
232 {
233     CDROM_SUB_Q_DATA_FORMAT     fmt;
234     SUB_Q_CHANNEL_DATA          data;
235     DWORD                       br;
236     DWORD                       mode = MCI_MODE_NOT_READY;
237
238     fmt.Format = IOCTL_CDROM_CURRENT_POSITION;
239     if(wmcda->hThread != 0) {
240         DWORD status;
241         HRESULT hr;
242
243         hr = IDirectSoundBuffer_GetStatus(wmcda->dsBuf, &status);
244         if(SUCCEEDED(hr)) {
245             if(!(status&DSBSTATUS_PLAYING)) {
246                 if(WaitForSingleObject(wmcda->stopEvent, 0) == WAIT_OBJECT_0)
247                     mode = MCI_MODE_STOP;
248                 else
249                     mode = MCI_MODE_PAUSE;
250             }
251             else
252                 mode = MCI_MODE_PLAY;
253         }
254     }
255     else if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_READ_Q_CHANNEL, &fmt, sizeof(fmt),
256                               &data, sizeof(data), &br, NULL)) {
257         if (GetLastError() == ERROR_NOT_READY) mode = MCI_MODE_OPEN;
258     } else {
259         switch (data.CurrentPosition.Header.AudioStatus)
260         {
261         case AUDIO_STATUS_IN_PROGRESS:          mode = MCI_MODE_PLAY;   break;
262         case AUDIO_STATUS_PAUSED:               mode = MCI_MODE_PAUSE;  break;
263         case AUDIO_STATUS_NO_STATUS:
264         case AUDIO_STATUS_PLAY_COMPLETE:        mode = MCI_MODE_STOP;   break;
265         case AUDIO_STATUS_PLAY_ERROR:
266         case AUDIO_STATUS_NOT_SUPPORTED:
267         default:
268             break;
269         }
270     }
271     return mode;
272 }
273
274 /**************************************************************************
275  *                              MCICDA_GetError                 [internal]
276  */
277 static  int     MCICDA_GetError(WINE_MCICDAUDIO* wmcda)
278 {
279     switch (GetLastError())
280     {
281     case ERROR_NOT_READY:     return MCIERR_DEVICE_NOT_READY;
282     case ERROR_NOT_SUPPORTED:
283     case ERROR_IO_DEVICE:     return MCIERR_HARDWARE;
284     default:
285         FIXME("Unknown mode %u\n", GetLastError());
286     }
287     return MCIERR_DRIVER_INTERNAL;
288 }
289
290 /**************************************************************************
291  *                      MCICDA_CalcFrame                        [internal]
292  */
293 static DWORD MCICDA_CalcFrame(WINE_MCICDAUDIO* wmcda, DWORD dwTime)
294 {
295     DWORD       dwFrame = 0;
296     UINT        wTrack;
297     CDROM_TOC   toc;
298     DWORD       br;
299     BYTE*       addr;
300
301     TRACE("(%p, %08X, %u);\n", wmcda, wmcda->dwTimeFormat, dwTime);
302
303     switch (wmcda->dwTimeFormat) {
304     case MCI_FORMAT_MILLISECONDS:
305         dwFrame = ((dwTime - 1) * CDFRAMES_PERSEC + 500) / 1000;
306         TRACE("MILLISECONDS %u\n", dwFrame);
307         break;
308     case MCI_FORMAT_MSF:
309         TRACE("MSF %02u:%02u:%02u\n",
310               MCI_MSF_MINUTE(dwTime), MCI_MSF_SECOND(dwTime), MCI_MSF_FRAME(dwTime));
311         dwFrame += CDFRAMES_PERMIN * MCI_MSF_MINUTE(dwTime);
312         dwFrame += CDFRAMES_PERSEC * MCI_MSF_SECOND(dwTime);
313         dwFrame += MCI_MSF_FRAME(dwTime);
314         break;
315     case MCI_FORMAT_TMSF:
316     default: /* unknown format ! force TMSF ! ... */
317         wTrack = MCI_TMSF_TRACK(dwTime);
318         if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_READ_TOC, NULL, 0,
319                              &toc, sizeof(toc), &br, NULL))
320             return 0;
321         if (wTrack < toc.FirstTrack || wTrack > toc.LastTrack)
322             return 0;
323         TRACE("MSF %02u-%02u:%02u:%02u\n",
324               MCI_TMSF_TRACK(dwTime), MCI_TMSF_MINUTE(dwTime),
325               MCI_TMSF_SECOND(dwTime), MCI_TMSF_FRAME(dwTime));
326         addr = toc.TrackData[wTrack - toc.FirstTrack].Address;
327         TRACE("TMSF trackpos[%u]=%d:%d:%d\n",
328               wTrack, addr[1], addr[2], addr[3]);
329         dwFrame = CDFRAMES_PERMIN * (addr[1] + MCI_TMSF_MINUTE(dwTime)) +
330             CDFRAMES_PERSEC * (addr[2] + MCI_TMSF_SECOND(dwTime)) +
331             addr[3] + MCI_TMSF_FRAME(dwTime);
332         break;
333     }
334     return dwFrame;
335 }
336
337 /**************************************************************************
338  *                      MCICDA_CalcTime                         [internal]
339  */
340 static DWORD MCICDA_CalcTime(WINE_MCICDAUDIO* wmcda, DWORD tf, DWORD dwFrame, LPDWORD lpRet)
341 {
342     DWORD       dwTime = 0;
343     UINT        wTrack;
344     UINT        wMinutes;
345     UINT        wSeconds;
346     UINT        wFrames;
347     CDROM_TOC   toc;
348     DWORD       br;
349
350     TRACE("(%p, %08X, %u);\n", wmcda, tf, dwFrame);
351
352     switch (tf) {
353     case MCI_FORMAT_MILLISECONDS:
354         dwTime = (dwFrame * 1000) / CDFRAMES_PERSEC + 1;
355         TRACE("MILLISECONDS %u\n", dwTime);
356         *lpRet = 0;
357         break;
358     case MCI_FORMAT_MSF:
359         wMinutes = dwFrame / CDFRAMES_PERMIN;
360         wSeconds = (dwFrame - CDFRAMES_PERMIN * wMinutes) / CDFRAMES_PERSEC;
361         wFrames = dwFrame - CDFRAMES_PERMIN * wMinutes - CDFRAMES_PERSEC * wSeconds;
362         dwTime = MCI_MAKE_MSF(wMinutes, wSeconds, wFrames);
363         TRACE("MSF %02u:%02u:%02u -> dwTime=%u\n",
364               wMinutes, wSeconds, wFrames, dwTime);
365         *lpRet = MCI_COLONIZED3_RETURN;
366         break;
367     case MCI_FORMAT_TMSF:
368     default:    /* unknown format ! force TMSF ! ... */
369         if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_READ_TOC, NULL, 0,
370                              &toc, sizeof(toc), &br, NULL))
371             return 0;
372         if (dwFrame < FRAME_OF_TOC(toc, toc.FirstTrack) ||
373             dwFrame > FRAME_OF_TOC(toc, toc.LastTrack + 1)) {
374             ERR("Out of range value %u [%u,%u]\n",
375                 dwFrame, FRAME_OF_TOC(toc, toc.FirstTrack),
376                 FRAME_OF_TOC(toc, toc.LastTrack + 1));
377             *lpRet = 0;
378             return 0;
379         }
380         for (wTrack = toc.FirstTrack; wTrack <= toc.LastTrack; wTrack++) {
381             if (FRAME_OF_TOC(toc, wTrack) > dwFrame)
382                 break;
383         }
384         wTrack--;
385         dwFrame -= FRAME_OF_TOC(toc, wTrack);
386         wMinutes = dwFrame / CDFRAMES_PERMIN;
387         wSeconds = (dwFrame - CDFRAMES_PERMIN * wMinutes) / CDFRAMES_PERSEC;
388         wFrames = dwFrame - CDFRAMES_PERMIN * wMinutes - CDFRAMES_PERSEC * wSeconds;
389         dwTime = MCI_MAKE_TMSF(wTrack, wMinutes, wSeconds, wFrames);
390         TRACE("%02u-%02u:%02u:%02u\n", wTrack, wMinutes, wSeconds, wFrames);
391         *lpRet = MCI_COLONIZED4_RETURN;
392         break;
393     }
394     return dwTime;
395 }
396
397 static DWORD MCICDA_Stop(UINT wDevID, DWORD dwFlags, LPMCI_GENERIC_PARMS lpParms);
398
399 /**************************************************************************
400  *                              MCICDA_Open                     [internal]
401  */
402 static DWORD MCICDA_Open(UINT wDevID, DWORD dwFlags, LPMCI_OPEN_PARMSW lpOpenParms)
403 {
404     MCIDEVICEID         dwDeviceID;
405     DWORD               ret;
406     WINE_MCICDAUDIO*    wmcda = (WINE_MCICDAUDIO*)mciGetDriverData(wDevID);
407     WCHAR               root[7], drive = 0;
408
409     TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpOpenParms);
410
411     if (lpOpenParms == NULL)            return MCIERR_NULL_PARAMETER_BLOCK;
412     if (wmcda == NULL)                  return MCIERR_INVALID_DEVICE_ID;
413
414     dwDeviceID = lpOpenParms->wDeviceID;
415
416     if (wmcda->nUseCount > 0) {
417         /* The driver is already open on this channel */
418         /* If the driver was opened shareable before and this open specifies */
419         /* shareable then increment the use count */
420         if (wmcda->fShareable && (dwFlags & MCI_OPEN_SHAREABLE))
421             ++wmcda->nUseCount;
422         else
423             return MCIERR_MUST_USE_SHAREABLE;
424     } else {
425         wmcda->nUseCount = 1;
426         wmcda->fShareable = dwFlags & MCI_OPEN_SHAREABLE;
427     }
428     if (dwFlags & MCI_OPEN_ELEMENT) {
429         if (dwFlags & MCI_OPEN_ELEMENT_ID) {
430             WARN("MCI_OPEN_ELEMENT_ID %p! Abort\n", lpOpenParms->lpstrElementName);
431             ret = MCIERR_FLAGS_NOT_COMPATIBLE;
432             goto the_error;
433         }
434         TRACE("MCI_OPEN_ELEMENT element name: %s\n", debugstr_w(lpOpenParms->lpstrElementName));
435         /* Only the first letter counts since w2k
436          * Win9x-NT accept only d: and w98SE accepts d:\foobar as well.
437          * Play d:\Track03.cda plays from the first track, not #3. */
438         if (!isalpha(lpOpenParms->lpstrElementName[0]))
439         {
440             ret = MCIERR_INVALID_FILE;
441             goto the_error;
442         }
443         drive = toupper(lpOpenParms->lpstrElementName[0]);
444         root[0] = drive; root[1] = ':'; root[2] = '\\'; root[3] = '\0';
445         if (GetDriveTypeW(root) != DRIVE_CDROM)
446         {
447             ret = MCIERR_INVALID_FILE;
448             goto the_error;
449         }
450     }
451     else
452     {
453         root[0] = 'A'; root[1] = ':'; root[2] = '\\'; root[3] = '\0';
454         for ( ; root[0] <= 'Z'; root[0]++)
455         {
456             if (GetDriveTypeW(root) == DRIVE_CDROM)
457             {
458                 drive = root[0];
459                 break;
460             }
461         }
462         if (!drive)
463         {
464             ret = MCIERR_CANNOT_LOAD_DRIVER; /* drvOpen should return this */
465             goto the_error;
466         }
467     }
468
469     wmcda->wNotifyDeviceID = dwDeviceID;
470     wmcda->dwTimeFormat = MCI_FORMAT_MSF;
471
472     /* now, open the handle */
473     root[0] = root[1] = '\\'; root[2] = '.'; root[3] = '\\'; root[4] = drive; root[5] = ':'; root[6] = '\0';
474     wmcda->handle = CreateFileW(root, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
475     if (wmcda->handle == INVALID_HANDLE_VALUE)
476     {
477         ret = MCIERR_MUST_USE_SHAREABLE;
478         goto the_error;
479     }
480
481     if (dwFlags & MCI_NOTIFY) {
482         mciDriverNotify(HWND_32(LOWORD(lpOpenParms->dwCallback)),
483                         dwDeviceID, MCI_NOTIFY_SUCCESSFUL);
484     }
485     return 0;
486
487  the_error:
488     --wmcda->nUseCount;
489     return ret;
490 }
491
492 /**************************************************************************
493  *                              MCICDA_Close                    [internal]
494  */
495 static DWORD MCICDA_Close(UINT wDevID, DWORD dwParam, LPMCI_GENERIC_PARMS lpParms)
496 {
497     WINE_MCICDAUDIO*    wmcda = MCICDA_GetOpenDrv(wDevID);
498
499     TRACE("(%04X, %08X, %p);\n", wDevID, dwParam, lpParms);
500
501     if (wmcda == NULL)  return MCIERR_INVALID_DEVICE_ID;
502
503     MCICDA_Stop(wDevID, MCI_WAIT, NULL);
504
505     if (--wmcda->nUseCount == 0) {
506         CloseHandle(wmcda->handle);
507     }
508     if ((dwParam & MCI_NOTIFY) && lpParms)
509         MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL);
510     return 0;
511 }
512
513 /**************************************************************************
514  *                              MCICDA_GetDevCaps               [internal]
515  */
516 static DWORD MCICDA_GetDevCaps(UINT wDevID, DWORD dwFlags,
517                                    LPMCI_GETDEVCAPS_PARMS lpParms)
518 {
519     WINE_MCICDAUDIO*    wmcda = (WINE_MCICDAUDIO*)mciGetDriverData(wDevID);
520     DWORD       ret = 0;
521
522     TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms);
523
524     if (lpParms == NULL) return MCIERR_NULL_PARAMETER_BLOCK;
525     if (wmcda == NULL)                  return MCIERR_INVALID_DEVICE_ID;
526
527     if (dwFlags & MCI_GETDEVCAPS_ITEM) {
528         TRACE("MCI_GETDEVCAPS_ITEM dwItem=%08X;\n", lpParms->dwItem);
529
530         switch (lpParms->dwItem) {
531         case MCI_GETDEVCAPS_CAN_RECORD:
532             lpParms->dwReturn = MAKEMCIRESOURCE(FALSE, MCI_FALSE);
533             ret = MCI_RESOURCE_RETURNED;
534             break;
535         case MCI_GETDEVCAPS_HAS_AUDIO:
536             lpParms->dwReturn = MAKEMCIRESOURCE(TRUE, MCI_TRUE);
537             ret = MCI_RESOURCE_RETURNED;
538             break;
539         case MCI_GETDEVCAPS_HAS_VIDEO:
540             lpParms->dwReturn = MAKEMCIRESOURCE(FALSE, MCI_FALSE);
541             ret = MCI_RESOURCE_RETURNED;
542             break;
543         case MCI_GETDEVCAPS_DEVICE_TYPE:
544             lpParms->dwReturn = MAKEMCIRESOURCE(MCI_DEVTYPE_CD_AUDIO, MCI_DEVTYPE_CD_AUDIO);
545             ret = MCI_RESOURCE_RETURNED;
546             break;
547         case MCI_GETDEVCAPS_USES_FILES:
548             lpParms->dwReturn = MAKEMCIRESOURCE(FALSE, MCI_FALSE);
549             ret = MCI_RESOURCE_RETURNED;
550             break;
551         case MCI_GETDEVCAPS_COMPOUND_DEVICE:
552             lpParms->dwReturn = MAKEMCIRESOURCE(FALSE, MCI_FALSE);
553             ret = MCI_RESOURCE_RETURNED;
554             break;
555         case MCI_GETDEVCAPS_CAN_EJECT:
556             lpParms->dwReturn = MAKEMCIRESOURCE(TRUE, MCI_TRUE);
557             ret = MCI_RESOURCE_RETURNED;
558             break;
559         case MCI_GETDEVCAPS_CAN_PLAY:
560             lpParms->dwReturn = MAKEMCIRESOURCE(TRUE, MCI_TRUE);
561             ret = MCI_RESOURCE_RETURNED;
562             break;
563         case MCI_GETDEVCAPS_CAN_SAVE:
564             lpParms->dwReturn = MAKEMCIRESOURCE(FALSE, MCI_FALSE);
565             ret = MCI_RESOURCE_RETURNED;
566             break;
567         default:
568             WARN("Unsupported %x devCaps item\n", lpParms->dwItem);
569             return MCIERR_UNSUPPORTED_FUNCTION;
570         }
571     } else {
572         TRACE("No GetDevCaps-Item !\n");
573         return MCIERR_MISSING_PARAMETER;
574     }
575     TRACE("lpParms->dwReturn=%08X;\n", lpParms->dwReturn);
576     if (dwFlags & MCI_NOTIFY) {
577         MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL);
578     }
579     return ret;
580 }
581
582 static DWORD CDROM_Audio_GetSerial(CDROM_TOC* toc)
583 {
584     DWORD serial = 0;
585     int i;
586     WORD wMagic;
587     DWORD dwStart, dwEnd;
588
589     /*
590      * wMagic collects the wFrames from track 1
591      * dwStart, dwEnd collect the beginning and end of the disc respectively, in
592      * frames.
593      * There it is collected for correcting the serial when there are less than
594      * 3 tracks.
595      */
596     wMagic = toc->TrackData[0].Address[3];
597     dwStart = FRAME_OF_TOC(*toc, toc->FirstTrack);
598
599     for (i = 0; i <= toc->LastTrack - toc->FirstTrack; i++) {
600         serial += (toc->TrackData[i].Address[1] << 16) |
601             (toc->TrackData[i].Address[2] << 8) | toc->TrackData[i].Address[3];
602     }
603     dwEnd = FRAME_OF_TOC(*toc, toc->LastTrack + 1);
604
605     if (toc->LastTrack - toc->FirstTrack + 1 < 3)
606         serial += wMagic + (dwEnd - dwStart);
607
608     return serial;
609 }
610
611
612 /**************************************************************************
613  *                              MCICDA_Info                     [internal]
614  */
615 static DWORD MCICDA_Info(UINT wDevID, DWORD dwFlags, LPMCI_INFO_PARMSW lpParms)
616 {
617     LPCWSTR             str = NULL;
618     WINE_MCICDAUDIO*    wmcda = MCICDA_GetOpenDrv(wDevID);
619     DWORD               ret = 0;
620     WCHAR               buffer[16];
621
622     TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms);
623
624     if (lpParms == NULL || lpParms->lpstrReturn == NULL)
625         return MCIERR_NULL_PARAMETER_BLOCK;
626     if (wmcda == NULL) return MCIERR_INVALID_DEVICE_ID;
627
628     TRACE("buf=%p, len=%u\n", lpParms->lpstrReturn, lpParms->dwRetSize);
629
630     if (dwFlags & MCI_INFO_PRODUCT) {
631         static const WCHAR wszAudioCd[] = {'W','i','n','e','\'','s',' ','a','u','d','i','o',' ','C','D',0};
632         str = wszAudioCd;
633     } else if (dwFlags & MCI_INFO_MEDIA_UPC) {
634         ret = MCIERR_NO_IDENTITY;
635     } else if (dwFlags & MCI_INFO_MEDIA_IDENTITY) {
636         DWORD       res = 0;
637         CDROM_TOC   toc;
638         DWORD       br;
639         static const WCHAR wszLu[] = {'%','l','u',0};
640
641         if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_READ_TOC, NULL, 0,
642                              &toc, sizeof(toc), &br, NULL)) {
643             return MCICDA_GetError(wmcda);
644         }
645
646         res = CDROM_Audio_GetSerial(&toc);
647         sprintfW(buffer, wszLu, res);
648         str = buffer;
649     } else {
650         WARN("Don't know this info command (%u)\n", dwFlags);
651         ret = MCIERR_MISSING_PARAMETER;
652     }
653     if (!ret) {
654         TRACE("=> %s\n", debugstr_w(str));
655         if (lpParms->dwRetSize) {
656             WCHAR zero = 0;
657             /* FIXME? Since NT, mciwave, mciseq and mcicda set dwRetSize
658              *        to the number of characters written, excluding \0. */
659             lstrcpynW(lpParms->lpstrReturn, str ? str : &zero, lpParms->dwRetSize);
660         } else ret = MCIERR_PARAM_OVERFLOW;
661     }
662     if (MMSYSERR_NOERROR==ret && (dwFlags & MCI_NOTIFY))
663         MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL);
664     return ret;
665 }
666
667 /**************************************************************************
668  *                              MCICDA_Status                   [internal]
669  */
670 static DWORD MCICDA_Status(UINT wDevID, DWORD dwFlags, LPMCI_STATUS_PARMS lpParms)
671 {
672     WINE_MCICDAUDIO*            wmcda = MCICDA_GetOpenDrv(wDevID);
673     DWORD                       ret = 0;
674     CDROM_SUB_Q_DATA_FORMAT     fmt;
675     SUB_Q_CHANNEL_DATA          data;
676     CDROM_TOC                   toc;
677     DWORD                       br;
678
679     TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms);
680
681     if (lpParms == NULL) return MCIERR_NULL_PARAMETER_BLOCK;
682     if (wmcda == NULL) return MCIERR_INVALID_DEVICE_ID;
683
684     if (dwFlags & MCI_STATUS_ITEM) {
685         TRACE("dwItem = %x\n", lpParms->dwItem);
686         switch (lpParms->dwItem) {
687         case MCI_STATUS_CURRENT_TRACK:
688             fmt.Format = IOCTL_CDROM_CURRENT_POSITION;
689             if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_READ_Q_CHANNEL, &fmt, sizeof(fmt),
690                                  &data, sizeof(data), &br, NULL))
691             {
692                 return MCICDA_GetError(wmcda);
693                 /* alt. data.CurrentPosition.TrackNumber = 1; -- what native yields */
694             }
695             lpParms->dwReturn = data.CurrentPosition.TrackNumber;
696             TRACE("CURRENT_TRACK=%lu\n", lpParms->dwReturn);
697             break;
698         case MCI_STATUS_LENGTH:
699             if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_READ_TOC, NULL, 0,
700                                  &toc, sizeof(toc), &br, NULL)) {
701                 WARN("error reading TOC !\n");
702                 return MCICDA_GetError(wmcda);
703             }
704             if (dwFlags & MCI_TRACK) {
705                 TRACE("MCI_TRACK #%u LENGTH=??? !\n", lpParms->dwTrack);
706                 if (lpParms->dwTrack < toc.FirstTrack || lpParms->dwTrack > toc.LastTrack)
707                     return MCIERR_OUTOFRANGE;
708                 lpParms->dwReturn = FRAME_OF_TOC(toc, lpParms->dwTrack + 1) -
709                     FRAME_OF_TOC(toc, lpParms->dwTrack);
710                 /* Windows returns one frame less than the total track length for the
711                    last track on the CD.  See CDDB HOWTO.  Verified on Win95OSR2. */
712                 if (lpParms->dwTrack == toc.LastTrack)
713                     lpParms->dwReturn--;
714             } else {
715                 /* Sum of the lengths of all of the tracks.  Inherits the
716                    'off by one frame' behavior from the length of the last track.
717                    See above comment. */
718                 lpParms->dwReturn = FRAME_OF_TOC(toc, toc.LastTrack + 1) -
719                     FRAME_OF_TOC(toc, toc.FirstTrack) - 1;
720             }
721             lpParms->dwReturn = MCICDA_CalcTime(wmcda,
722                                                  (wmcda->dwTimeFormat == MCI_FORMAT_TMSF)
723                                                     ? MCI_FORMAT_MSF : wmcda->dwTimeFormat,
724                                                  lpParms->dwReturn,
725                                                  &ret);
726             TRACE("LENGTH=%lu\n", lpParms->dwReturn);
727             break;
728         case MCI_STATUS_MODE:
729             lpParms->dwReturn = MCICDA_GetStatus(wmcda);
730             TRACE("MCI_STATUS_MODE=%08lX\n", lpParms->dwReturn);
731             lpParms->dwReturn = MAKEMCIRESOURCE(lpParms->dwReturn, lpParms->dwReturn);
732             ret = MCI_RESOURCE_RETURNED;
733             break;
734         case MCI_STATUS_MEDIA_PRESENT:
735             lpParms->dwReturn = (MCICDA_GetStatus(wmcda) == MCI_MODE_OPEN) ?
736                 MAKEMCIRESOURCE(FALSE, MCI_FALSE) : MAKEMCIRESOURCE(TRUE, MCI_TRUE);
737             TRACE("MCI_STATUS_MEDIA_PRESENT =%c!\n", LOWORD(lpParms->dwReturn) ? 'Y' : 'N');
738             ret = MCI_RESOURCE_RETURNED;
739             break;
740         case MCI_STATUS_NUMBER_OF_TRACKS:
741             if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_READ_TOC, NULL, 0,
742                                  &toc, sizeof(toc), &br, NULL)) {
743                 WARN("error reading TOC !\n");
744                 return MCICDA_GetError(wmcda);
745             }
746             lpParms->dwReturn = toc.LastTrack - toc.FirstTrack + 1;
747             TRACE("MCI_STATUS_NUMBER_OF_TRACKS = %lu\n", lpParms->dwReturn);
748             if (lpParms->dwReturn == (WORD)-1)
749                 return MCICDA_GetError(wmcda);
750             break;
751         case MCI_STATUS_POSITION:
752             switch (dwFlags & (MCI_STATUS_START | MCI_TRACK)) {
753             case MCI_STATUS_START:
754                 if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_READ_TOC, NULL, 0,
755                                      &toc, sizeof(toc), &br, NULL)) {
756                     WARN("error reading TOC !\n");
757                     return MCICDA_GetError(wmcda);
758                 }
759                 lpParms->dwReturn = FRAME_OF_TOC(toc, toc.FirstTrack);
760                 TRACE("get MCI_STATUS_START !\n");
761                 break;
762             case MCI_TRACK:
763                 if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_READ_TOC, NULL, 0,
764                                      &toc, sizeof(toc), &br, NULL)) {
765                     WARN("error reading TOC !\n");
766                     return MCICDA_GetError(wmcda);
767                 }
768                 if (lpParms->dwTrack < toc.FirstTrack || lpParms->dwTrack > toc.LastTrack)
769                     return MCIERR_OUTOFRANGE;
770                 lpParms->dwReturn = FRAME_OF_TOC(toc, lpParms->dwTrack);
771                 TRACE("get MCI_TRACK #%u !\n", lpParms->dwTrack);
772                 break;
773             case 0:
774                 fmt.Format = IOCTL_CDROM_CURRENT_POSITION;
775                 if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_READ_Q_CHANNEL, &fmt, sizeof(fmt),
776                                      &data, sizeof(data), &br, NULL)) {
777                     return MCICDA_GetError(wmcda);
778                 }
779                 lpParms->dwReturn = FRAME_OF_ADDR(data.CurrentPosition.AbsoluteAddress);
780                 break;
781             default:
782                 return MCIERR_FLAGS_NOT_COMPATIBLE;
783             }
784             lpParms->dwReturn = MCICDA_CalcTime(wmcda, wmcda->dwTimeFormat, lpParms->dwReturn, &ret);
785             TRACE("MCI_STATUS_POSITION=%08lX\n", lpParms->dwReturn);
786             break;
787         case MCI_STATUS_READY:
788             TRACE("MCI_STATUS_READY !\n");
789             switch (MCICDA_GetStatus(wmcda))
790             {
791             case MCI_MODE_NOT_READY:
792             case MCI_MODE_OPEN:
793                 lpParms->dwReturn = MAKEMCIRESOURCE(FALSE, MCI_FALSE);
794                 break;
795             default:
796                 lpParms->dwReturn = MAKEMCIRESOURCE(TRUE, MCI_TRUE);
797                 break;
798             }
799             TRACE("MCI_STATUS_READY=%u!\n", LOWORD(lpParms->dwReturn));
800             ret = MCI_RESOURCE_RETURNED;
801             break;
802         case MCI_STATUS_TIME_FORMAT:
803             lpParms->dwReturn = MAKEMCIRESOURCE(wmcda->dwTimeFormat, MCI_FORMAT_RETURN_BASE + wmcda->dwTimeFormat);
804             TRACE("MCI_STATUS_TIME_FORMAT=%08x!\n", LOWORD(lpParms->dwReturn));
805             ret = MCI_RESOURCE_RETURNED;
806             break;
807         case 4001: /* FIXME: for bogus FullCD */
808         case MCI_CDA_STATUS_TYPE_TRACK:
809             if (!(dwFlags & MCI_TRACK))
810                 ret = MCIERR_MISSING_PARAMETER;
811             else {
812                 if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_READ_TOC, NULL, 0,
813                                      &toc, sizeof(toc), &br, NULL)) {
814                     WARN("error reading TOC !\n");
815                     return MCICDA_GetError(wmcda);
816                 }
817                 if (lpParms->dwTrack < toc.FirstTrack || lpParms->dwTrack > toc.LastTrack)
818                     ret = MCIERR_OUTOFRANGE;
819                 else
820                     lpParms->dwReturn = (toc.TrackData[lpParms->dwTrack - toc.FirstTrack].Control & 0x04) ?
821                                          MCI_CDA_TRACK_OTHER : MCI_CDA_TRACK_AUDIO;
822                     /* FIXME: MAKEMCIRESOURCE "audio" | "other", localised */
823             }
824             TRACE("MCI_CDA_STATUS_TYPE_TRACK[%d]=%ld\n", lpParms->dwTrack, lpParms->dwReturn);
825             break;
826         default:
827             FIXME("unknown command %08X !\n", lpParms->dwItem);
828             return MCIERR_UNSUPPORTED_FUNCTION;
829         }
830     } else return MCIERR_MISSING_PARAMETER;
831     if ((dwFlags & MCI_NOTIFY) && HRESULT_CODE(ret)==0)
832         MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL);
833     return ret;
834 }
835
836 /**************************************************************************
837  *                              MCICDA_SkipDataTracks           [internal]
838  */
839 static DWORD MCICDA_SkipDataTracks(WINE_MCICDAUDIO* wmcda,DWORD *frame)
840 {
841   int i;
842   DWORD br;
843   CDROM_TOC toc;
844   if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_READ_TOC, NULL, 0,
845                       &toc, sizeof(toc), &br, NULL)) {
846     WARN("error reading TOC !\n");
847     return MCICDA_GetError(wmcda);
848   }
849   if (*frame < FRAME_OF_TOC(toc,toc.FirstTrack) ||
850       *frame >= FRAME_OF_TOC(toc,toc.LastTrack+1)) /* lead-out */
851     return MCIERR_OUTOFRANGE;
852   for(i=toc.LastTrack+1;i>toc.FirstTrack;i--)
853     if ( FRAME_OF_TOC(toc, i) <= *frame ) break;
854   /* i points to last track whose start address is not greater than frame.
855    * Now skip non-audio tracks */
856   for(;i<=toc.LastTrack;i++)
857     if ( ! (toc.TrackData[i-toc.FirstTrack].Control & 4) )
858       break;
859   /* The frame will be an address in the next audio track or
860    * address of lead-out. */
861   if ( FRAME_OF_TOC(toc, i) > *frame )
862     *frame = FRAME_OF_TOC(toc, i);
863   /* Lead-out is an invalid seek position (on Linux as well). */
864   if (*frame == FRAME_OF_TOC(toc,toc.LastTrack+1))
865      (*frame)--;
866   return 0;
867 }
868
869 /**************************************************************************
870  *                              MCICDA_Play                     [internal]
871  */
872 static DWORD MCICDA_Play(UINT wDevID, DWORD dwFlags, LPMCI_PLAY_PARMS lpParms)
873 {
874     WINE_MCICDAUDIO*            wmcda = MCICDA_GetOpenDrv(wDevID);
875     DWORD                       ret = 0, start, end;
876     HANDLE                      oldcb;
877     DWORD                       br;
878     CDROM_PLAY_AUDIO_MSF        play;
879     CDROM_SUB_Q_DATA_FORMAT     fmt;
880     SUB_Q_CHANNEL_DATA          data;
881     CDROM_TOC                   toc;
882
883     TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms);
884
885     if (lpParms == NULL)
886         return MCIERR_NULL_PARAMETER_BLOCK;
887
888     if (wmcda == NULL)
889         return MCIERR_INVALID_DEVICE_ID;
890
891     if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_READ_TOC, NULL, 0,
892                          &toc, sizeof(toc), &br, NULL)) {
893         WARN("error reading TOC !\n");
894         return MCICDA_GetError(wmcda);
895     }
896
897     if (dwFlags & MCI_FROM) {
898         start = MCICDA_CalcFrame(wmcda, lpParms->dwFrom);
899         if ( (ret=MCICDA_SkipDataTracks(wmcda, &start)) )
900           return ret;
901         TRACE("MCI_FROM=%08X -> %u\n", lpParms->dwFrom, start);
902     } else {
903         fmt.Format = IOCTL_CDROM_CURRENT_POSITION;
904         if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_READ_Q_CHANNEL, &fmt, sizeof(fmt),
905                              &data, sizeof(data), &br, NULL)) {
906             return MCICDA_GetError(wmcda);
907         }
908         start = FRAME_OF_ADDR(data.CurrentPosition.AbsoluteAddress);
909         if ( (ret=MCICDA_SkipDataTracks(wmcda, &start)) )
910           return ret;
911     }
912     if (dwFlags & MCI_TO) {
913         end = MCICDA_CalcFrame(wmcda, lpParms->dwTo);
914         if ( (ret=MCICDA_SkipDataTracks(wmcda, &end)) )
915           return ret;
916         TRACE("MCI_TO=%08X -> %u\n", lpParms->dwTo, end);
917     } else {
918         end = FRAME_OF_TOC(toc, toc.LastTrack + 1) - 1;
919     }
920     if (end < start) return MCIERR_OUTOFRANGE;
921     TRACE("Playing from %u to %u\n", start, end);
922
923     oldcb = InterlockedExchangePointer(&wmcda->hCallback,
924         (dwFlags & MCI_NOTIFY) ? HWND_32(LOWORD(lpParms->dwCallback)) : NULL);
925     if (oldcb) mciDriverNotify(oldcb, wmcda->wNotifyDeviceID, MCI_NOTIFY_ABORTED);
926
927     if (start == end || start == FRAME_OF_TOC(toc,toc.LastTrack+1)-1) {
928         if (dwFlags & MCI_NOTIFY) {
929             oldcb = InterlockedExchangePointer(&wmcda->hCallback, NULL);
930             if (oldcb) mciDriverNotify(oldcb, wDevID, MCI_NOTIFY_SUCCESSFUL);
931         }
932         return MMSYSERR_NOERROR;
933     }
934
935     if (wmcda->hThread != 0) {
936         SetEvent(wmcda->stopEvent);
937         WaitForSingleObject(wmcda->hThread, INFINITE);
938
939         CloseHandle(wmcda->hThread);
940         wmcda->hThread = 0;
941         CloseHandle(wmcda->stopEvent);
942         wmcda->stopEvent = 0;
943
944         IDirectSoundBuffer_Stop(wmcda->dsBuf);
945         IDirectSoundBuffer_Release(wmcda->dsBuf);
946         wmcda->dsBuf = NULL;
947         IDirectSound_Release(wmcda->dsObj);
948         wmcda->dsObj = NULL;
949     }
950
951     if (pDirectSoundCreate) {
952         WAVEFORMATEX format;
953         DSBUFFERDESC desc;
954         DWORD lockLen;
955         void *cdData;
956         HRESULT hr;
957
958         hr = pDirectSoundCreate(NULL, &wmcda->dsObj, NULL);
959         if (SUCCEEDED(hr)) {
960             IDirectSound_SetCooperativeLevel(wmcda->dsObj, GetDesktopWindow(), DSSCL_PRIORITY);
961
962             /* The "raw" frame is relative to the start of the first track */
963             wmcda->start = start - FRAME_OF_TOC(toc, toc.FirstTrack);
964             wmcda->end = end - FRAME_OF_TOC(toc, toc.FirstTrack);
965
966             memset(&format, 0, sizeof(format));
967             format.wFormatTag = WAVE_FORMAT_PCM;
968             format.nChannels = 2;
969             format.nSamplesPerSec = 44100;
970             format.wBitsPerSample = 16;
971             format.nBlockAlign = format.nChannels * format.wBitsPerSample / 8;
972             format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign;
973             format.cbSize = 0;
974
975             memset(&desc, 0, sizeof(desc));
976             desc.dwSize = sizeof(desc);
977             desc.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_GLOBALFOCUS;
978             desc.dwBufferBytes = (CDDA_FRAG_SIZE - (CDDA_FRAG_SIZE%RAW_SECTOR_SIZE)) * CDDA_FRAG_COUNT;
979             desc.lpwfxFormat = &format;
980
981             hr = IDirectSound_CreateSoundBuffer(wmcda->dsObj, &desc, &wmcda->dsBuf, NULL);
982         }
983         if (SUCCEEDED(hr)) {
984             hr = IDirectSoundBuffer_Lock(wmcda->dsBuf, 0, 0, &cdData, &lockLen,
985                                          NULL, NULL, DSBLOCK_ENTIREBUFFER);
986         }
987         if (SUCCEEDED(hr)) {
988             RAW_READ_INFO rdInfo;
989             int readok;
990
991             rdInfo.DiskOffset.QuadPart = wmcda->start<<11;
992             rdInfo.SectorCount = min(desc.dwBufferBytes/RAW_SECTOR_SIZE,
993                                      wmcda->end-wmcda->start);
994             rdInfo.TrackMode = CDDA;
995
996             readok = DeviceIoControl(wmcda->handle, IOCTL_CDROM_RAW_READ,
997                                      &rdInfo, sizeof(rdInfo), cdData, lockLen,
998                                      &br, NULL);
999             IDirectSoundBuffer_Unlock(wmcda->dsBuf, cdData, lockLen, NULL, 0);
1000
1001             if (readok) {
1002                 wmcda->start += rdInfo.SectorCount;
1003                 wmcda->stopEvent = CreateEventA(NULL, TRUE, FALSE, NULL);
1004             }
1005             if (wmcda->stopEvent != 0)
1006                 wmcda->hThread = CreateThread(NULL, 0, MCICDA_playLoop, wmcda, 0, &br);
1007             if (wmcda->hThread != 0) {
1008                 hr = IDirectSoundBuffer_Play(wmcda->dsBuf, 0, 0, DSBPLAY_LOOPING);
1009                 if (SUCCEEDED(hr)) {
1010                     /* FIXME: implement MCI_WAIT and send notification only in that case */
1011                     if (0) {
1012                         oldcb = InterlockedExchangePointer(&wmcda->hCallback, NULL);
1013                         if (oldcb) mciDriverNotify(oldcb, wmcda->wNotifyDeviceID,
1014                             FAILED(hr) ? MCI_NOTIFY_FAILURE : MCI_NOTIFY_SUCCESSFUL);
1015                     }
1016                     return ret;
1017                 }
1018
1019                 SetEvent(wmcda->stopEvent);
1020                 WaitForSingleObject(wmcda->hThread, INFINITE);
1021                 CloseHandle(wmcda->hThread);
1022                 wmcda->hThread = 0;
1023             }
1024         }
1025
1026         if (wmcda->stopEvent != 0) {
1027             CloseHandle(wmcda->stopEvent);
1028             wmcda->stopEvent = 0;
1029         }
1030         if (wmcda->dsBuf) {
1031             IDirectSoundBuffer_Release(wmcda->dsBuf);
1032             wmcda->dsBuf = NULL;
1033         }
1034         if (wmcda->dsObj) {
1035             IDirectSound_Release(wmcda->dsObj);
1036             wmcda->dsObj = NULL;
1037         }
1038     }
1039
1040     play.StartingM = start / CDFRAMES_PERMIN;
1041     play.StartingS = (start / CDFRAMES_PERSEC) % 60;
1042     play.StartingF = start % CDFRAMES_PERSEC;
1043     play.EndingM   = end / CDFRAMES_PERMIN;
1044     play.EndingS   = (end / CDFRAMES_PERSEC) % 60;
1045     play.EndingF   = end % CDFRAMES_PERSEC;
1046     if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_PLAY_AUDIO_MSF, &play, sizeof(play),
1047                          NULL, 0, &br, NULL)) {
1048         wmcda->hCallback = NULL;
1049         ret = MCIERR_HARDWARE;
1050     }
1051     /* The independent CD player has no means to signal MCI_NOTIFY when it's done.
1052      * Native sends a notification with MCI_WAIT only. */
1053     return ret;
1054 }
1055
1056 /**************************************************************************
1057  *                              MCICDA_Stop                     [internal]
1058  */
1059 static DWORD MCICDA_Stop(UINT wDevID, DWORD dwFlags, LPMCI_GENERIC_PARMS lpParms)
1060 {
1061     WINE_MCICDAUDIO*    wmcda = MCICDA_GetOpenDrv(wDevID);
1062     HANDLE              oldcb;
1063     DWORD               br;
1064
1065     TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms);
1066
1067     if (wmcda == NULL)  return MCIERR_INVALID_DEVICE_ID;
1068
1069     oldcb = InterlockedExchangePointer(&wmcda->hCallback, NULL);
1070     if (oldcb) mciDriverNotify(oldcb, wmcda->wNotifyDeviceID, MCI_NOTIFY_ABORTED);
1071
1072     if (wmcda->hThread != 0) {
1073         SetEvent(wmcda->stopEvent);
1074         WaitForSingleObject(wmcda->hThread, INFINITE);
1075
1076         CloseHandle(wmcda->hThread);
1077         wmcda->hThread = 0;
1078         CloseHandle(wmcda->stopEvent);
1079         wmcda->stopEvent = 0;
1080
1081         IDirectSoundBuffer_Release(wmcda->dsBuf);
1082         wmcda->dsBuf = NULL;
1083         IDirectSound_Release(wmcda->dsObj);
1084         wmcda->dsObj = NULL;
1085     }
1086     else if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_STOP_AUDIO, NULL, 0, NULL, 0, &br, NULL))
1087         return MCIERR_HARDWARE;
1088
1089     if ((dwFlags & MCI_NOTIFY) && lpParms)
1090         MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL);
1091     return 0;
1092 }
1093
1094 /**************************************************************************
1095  *                              MCICDA_Pause                    [internal]
1096  */
1097 static DWORD MCICDA_Pause(UINT wDevID, DWORD dwFlags, LPMCI_GENERIC_PARMS lpParms)
1098 {
1099     WINE_MCICDAUDIO*    wmcda = MCICDA_GetOpenDrv(wDevID);
1100     HANDLE              oldcb;
1101     DWORD               br;
1102
1103     TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms);
1104
1105     if (wmcda == NULL)  return MCIERR_INVALID_DEVICE_ID;
1106
1107     oldcb = InterlockedExchangePointer(&wmcda->hCallback, NULL);
1108     if (oldcb) mciDriverNotify(oldcb, wmcda->wNotifyDeviceID, MCI_NOTIFY_ABORTED);
1109
1110     if (wmcda->hThread != 0) {
1111         /* Don't bother calling stop if the playLoop thread has already stopped */
1112         if(WaitForSingleObject(wmcda->stopEvent, 0) != WAIT_OBJECT_0 &&
1113            FAILED(IDirectSoundBuffer_Stop(wmcda->dsBuf)))
1114             return MCIERR_HARDWARE;
1115     }
1116     else if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_PAUSE_AUDIO, NULL, 0, NULL, 0, &br, NULL))
1117         return MCIERR_HARDWARE;
1118
1119     if ((dwFlags & MCI_NOTIFY) && lpParms)
1120         MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL);
1121     return 0;
1122 }
1123
1124 /**************************************************************************
1125  *                              MCICDA_Resume                   [internal]
1126  */
1127 static DWORD MCICDA_Resume(UINT wDevID, DWORD dwFlags, LPMCI_GENERIC_PARMS lpParms)
1128 {
1129     WINE_MCICDAUDIO*    wmcda = MCICDA_GetOpenDrv(wDevID);
1130     DWORD               br;
1131
1132     TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms);
1133
1134     if (wmcda == NULL)  return MCIERR_INVALID_DEVICE_ID;
1135
1136     if (wmcda->hThread != 0) {
1137         /* Don't restart if the playLoop thread has already stopped */
1138         if(WaitForSingleObject(wmcda->stopEvent, 0) != WAIT_OBJECT_0 &&
1139            FAILED(IDirectSoundBuffer_Play(wmcda->dsBuf, 0, 0, DSBPLAY_LOOPING)))
1140             return MCIERR_HARDWARE;
1141     }
1142     else if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_RESUME_AUDIO, NULL, 0, NULL, 0, &br, NULL))
1143         return MCIERR_HARDWARE;
1144
1145     if ((dwFlags & MCI_NOTIFY) && lpParms)
1146         MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL);
1147     return 0;
1148 }
1149
1150 /**************************************************************************
1151  *                              MCICDA_Seek                     [internal]
1152  */
1153 static DWORD MCICDA_Seek(UINT wDevID, DWORD dwFlags, LPMCI_SEEK_PARMS lpParms)
1154 {
1155     DWORD                       at;
1156     WINE_MCICDAUDIO*            wmcda = MCICDA_GetOpenDrv(wDevID);
1157     CDROM_SEEK_AUDIO_MSF        seek;
1158     DWORD                       br, position, ret;
1159     CDROM_TOC                   toc;
1160
1161     TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms);
1162
1163     if (wmcda == NULL)  return MCIERR_INVALID_DEVICE_ID;
1164     if (lpParms == NULL) return MCIERR_NULL_PARAMETER_BLOCK;
1165
1166     position = dwFlags & (MCI_SEEK_TO_START|MCI_SEEK_TO_END|MCI_TO);
1167     if (!position)              return MCIERR_MISSING_PARAMETER;
1168     if (position&(position-1))  return MCIERR_FLAGS_NOT_COMPATIBLE;
1169
1170     /* Stop sends MCI_NOTIFY_ABORTED when needed.
1171      * Tests show that native first sends ABORTED and reads the TOC,
1172      * then only checks the position flags, then stops and seeks. */
1173     MCICDA_Stop(wDevID, MCI_WAIT, 0);
1174
1175     if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_READ_TOC, NULL, 0,
1176                          &toc, sizeof(toc), &br, NULL)) {
1177         WARN("error reading TOC !\n");
1178         return MCICDA_GetError(wmcda);
1179     }
1180     switch (position) {
1181     case MCI_SEEK_TO_START:
1182         TRACE("Seeking to start\n");
1183         at = FRAME_OF_TOC(toc,toc.FirstTrack);
1184         if ( (ret=MCICDA_SkipDataTracks(wmcda, &at)) )
1185           return ret;
1186         break;
1187     case MCI_SEEK_TO_END:
1188         TRACE("Seeking to end\n");
1189         /* End is prior to lead-out
1190          * yet Win9X seeks to even one frame less than that. */
1191         at = FRAME_OF_TOC(toc, toc.LastTrack + 1) - 1;
1192         if ( (ret=MCICDA_SkipDataTracks(wmcda, &at)) )
1193           return ret;
1194         break;
1195     case MCI_TO:
1196         TRACE("Seeking to %u\n", lpParms->dwTo);
1197         at = MCICDA_CalcFrame(wmcda, lpParms->dwTo);
1198         if ( (ret=MCICDA_SkipDataTracks(wmcda, &at)) )
1199           return ret;
1200         break;
1201     default:
1202         return MCIERR_FLAGS_NOT_COMPATIBLE;
1203     }
1204
1205     {
1206         seek.M = at / CDFRAMES_PERMIN;
1207         seek.S = (at / CDFRAMES_PERSEC) % 60;
1208         seek.F = at % CDFRAMES_PERSEC;
1209         if (!DeviceIoControl(wmcda->handle, IOCTL_CDROM_SEEK_AUDIO_MSF, &seek, sizeof(seek),
1210                              NULL, 0, &br, NULL))
1211             return MCIERR_HARDWARE;
1212     }
1213
1214     if (dwFlags & MCI_NOTIFY)
1215         MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL);
1216     return 0;
1217 }
1218
1219 /**************************************************************************
1220  *                              MCICDA_SetDoor                  [internal]
1221  */
1222 static DWORD    MCICDA_SetDoor(UINT wDevID, BOOL open)
1223 {
1224     WINE_MCICDAUDIO*    wmcda = MCICDA_GetOpenDrv(wDevID);
1225     DWORD               br;
1226
1227     TRACE("(%04x, %s) !\n", wDevID, (open) ? "OPEN" : "CLOSE");
1228
1229     if (wmcda == NULL) return MCIERR_INVALID_DEVICE_ID;
1230
1231     if (!DeviceIoControl(wmcda->handle,
1232                          (open) ? IOCTL_STORAGE_EJECT_MEDIA : IOCTL_STORAGE_LOAD_MEDIA,
1233                          NULL, 0, NULL, 0, &br, NULL))
1234         return MCIERR_HARDWARE;
1235
1236     return 0;
1237 }
1238
1239 /**************************************************************************
1240  *                              MCICDA_Set                      [internal]
1241  */
1242 static DWORD MCICDA_Set(UINT wDevID, DWORD dwFlags, LPMCI_SET_PARMS lpParms)
1243 {
1244     WINE_MCICDAUDIO*    wmcda = MCICDA_GetOpenDrv(wDevID);
1245
1246     TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms);
1247
1248     if (wmcda == NULL)  return MCIERR_INVALID_DEVICE_ID;
1249
1250     if (dwFlags & MCI_SET_DOOR_OPEN) {
1251         MCICDA_SetDoor(wDevID, TRUE);
1252     }
1253     if (dwFlags & MCI_SET_DOOR_CLOSED) {
1254         MCICDA_SetDoor(wDevID, FALSE);
1255     }
1256
1257     /* only functions which require valid lpParms below this line ! */
1258     if (lpParms == NULL) return MCIERR_NULL_PARAMETER_BLOCK;
1259     /*
1260       TRACE("dwTimeFormat=%08lX\n", lpParms->dwTimeFormat);
1261     */
1262     if (dwFlags & MCI_SET_TIME_FORMAT) {
1263         switch (lpParms->dwTimeFormat) {
1264         case MCI_FORMAT_MILLISECONDS:
1265             TRACE("MCI_FORMAT_MILLISECONDS !\n");
1266             break;
1267         case MCI_FORMAT_MSF:
1268             TRACE("MCI_FORMAT_MSF !\n");
1269             break;
1270         case MCI_FORMAT_TMSF:
1271             TRACE("MCI_FORMAT_TMSF !\n");
1272             break;
1273         default:
1274             return MCIERR_BAD_TIME_FORMAT;
1275         }
1276         wmcda->dwTimeFormat = lpParms->dwTimeFormat;
1277     }
1278     if (dwFlags & MCI_SET_AUDIO) /* one xp machine ignored it */
1279         TRACE("SET_AUDIO %X %x\n", dwFlags, lpParms->dwAudio);
1280
1281     if (dwFlags & MCI_NOTIFY)
1282         MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL);
1283     return 0;
1284 }
1285
1286 /**************************************************************************
1287  *                      DriverProc (MCICDA.@)
1288  */
1289 LRESULT CALLBACK MCICDA_DriverProc(DWORD_PTR dwDevID, HDRVR hDriv, UINT wMsg,
1290                                    LPARAM dwParam1, LPARAM dwParam2)
1291 {
1292     switch(wMsg) {
1293     case DRV_LOAD:              return 1;
1294     case DRV_FREE:              return 1;
1295     case DRV_OPEN:              return MCICDA_drvOpen((LPCWSTR)dwParam1, (LPMCI_OPEN_DRIVER_PARMSW)dwParam2);
1296     case DRV_CLOSE:             return MCICDA_drvClose(dwDevID);
1297     case DRV_ENABLE:            return 1;
1298     case DRV_DISABLE:           return 1;
1299     case DRV_QUERYCONFIGURE:    return 1;
1300     case DRV_CONFIGURE:         MessageBoxA(0, "MCI audio CD driver !", "Wine Driver", MB_OK); return 1;
1301     case DRV_INSTALL:           return DRVCNF_RESTART;
1302     case DRV_REMOVE:            return DRVCNF_RESTART;
1303     }
1304
1305     if (dwDevID == 0xFFFFFFFF) return MCIERR_UNSUPPORTED_FUNCTION;
1306
1307     switch (wMsg) {
1308     case MCI_OPEN_DRIVER:       return MCICDA_Open(dwDevID, dwParam1, (LPMCI_OPEN_PARMSW)dwParam2);
1309     case MCI_CLOSE_DRIVER:      return MCICDA_Close(dwDevID, dwParam1, (LPMCI_GENERIC_PARMS)dwParam2);
1310     case MCI_GETDEVCAPS:        return MCICDA_GetDevCaps(dwDevID, dwParam1, (LPMCI_GETDEVCAPS_PARMS)dwParam2);
1311     case MCI_INFO:              return MCICDA_Info(dwDevID, dwParam1, (LPMCI_INFO_PARMSW)dwParam2);
1312     case MCI_STATUS:            return MCICDA_Status(dwDevID, dwParam1, (LPMCI_STATUS_PARMS)dwParam2);
1313     case MCI_SET:               return MCICDA_Set(dwDevID, dwParam1, (LPMCI_SET_PARMS)dwParam2);
1314     case MCI_PLAY:              return MCICDA_Play(dwDevID, dwParam1, (LPMCI_PLAY_PARMS)dwParam2);
1315     case MCI_STOP:              return MCICDA_Stop(dwDevID, dwParam1, (LPMCI_GENERIC_PARMS)dwParam2);
1316     case MCI_PAUSE:             return MCICDA_Pause(dwDevID, dwParam1, (LPMCI_GENERIC_PARMS)dwParam2);
1317     case MCI_RESUME:            return MCICDA_Resume(dwDevID, dwParam1, (LPMCI_GENERIC_PARMS)dwParam2);
1318     case MCI_SEEK:              return MCICDA_Seek(dwDevID, dwParam1, (LPMCI_SEEK_PARMS)dwParam2);
1319     /* commands that should report an error as they are not supported in
1320      * the native version */
1321     case MCI_RECORD:
1322     case MCI_LOAD:
1323     case MCI_SAVE:
1324         return MCIERR_UNSUPPORTED_FUNCTION;
1325     case MCI_BREAK:
1326     case MCI_FREEZE:
1327     case MCI_PUT:
1328     case MCI_REALIZE:
1329     case MCI_UNFREEZE:
1330     case MCI_UPDATE:
1331     case MCI_WHERE:
1332     case MCI_STEP:
1333     case MCI_SPIN:
1334     case MCI_ESCAPE:
1335     case MCI_COPY:
1336     case MCI_CUT:
1337     case MCI_DELETE:
1338     case MCI_PASTE:
1339     case MCI_WINDOW:
1340         TRACE("Unsupported command [0x%x]\n", wMsg);
1341         break;
1342     case MCI_OPEN:
1343     case MCI_CLOSE:
1344         ERR("Shouldn't receive a MCI_OPEN or CLOSE message\n");
1345         break;
1346     default:
1347         TRACE("Sending msg [0x%x] to default driver proc\n", wMsg);
1348         return DefDriverProc(dwDevID, hDriv, wMsg, dwParam1, dwParam2);
1349     }
1350     return MCIERR_UNRECOGNIZED_COMMAND;
1351 }
1352
1353 /*-----------------------------------------------------------------------*/