kernel32: Fix the case where memory is freed twice in GlobalFree.
[wine] / dlls / wineaudioio.drv / audio.c
1 /*
2  * Wine Driver for Libaudioio
3  * Derived from the Wine OSS Sample Driver
4  * Copyright 1994 Martin Ayotte
5  *           1999 Eric Pouech (async playing in waveOut/waveIn)
6  *           2000 Eric Pouech (loops in waveOut)
7  *           2002 Robert Lunnon (Modifications for libaudioio)
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  *
23  *
24  * Note large hacks done to effectively disable DSound altogether
25  * Also Input is not yet working (Lots more work to be done there)
26  * But this does make a reasonable output driver for solaris until the arts
27  * driver comes up to speed
28  */
29
30 /*
31  * FIXME:
32  *      pause in waveOut does not work correctly
33  *      full duplex (in/out) is not working (device is opened twice for Out
34  *      and In) (OSS is known for its poor duplex capabilities, alsa is
35  *      better)
36  */
37
38 #include "config.h"
39
40 #include <stdlib.h>
41 #include <stdarg.h>
42 #include <stdio.h>
43 #include <string.h>
44 #ifdef HAVE_UNISTD_H
45 # include <unistd.h>
46 #endif
47 #include <errno.h>
48 #include <fcntl.h>
49 #ifdef HAVE_SYS_IOCTL_H
50 # include <sys/ioctl.h>
51 #endif
52 #ifdef HAVE_SYS_MMAN_H
53 # include <sys/mman.h>
54 #endif
55 #ifdef HAVE_LIBAUDIOIO_H
56 #include <libaudioio.h>
57 #endif
58 #include "windef.h"
59 #include "winbase.h"
60 #include "wine/unicode.h"
61 #include "wingdi.h"
62 #include "winerror.h"
63 #include "winuser.h"
64 #include "mmddk.h"
65 #include "dsound.h"
66 #include "dsdriver.h"
67 #include "wine/debug.h"
68
69 WINE_DEFAULT_DEBUG_CHANNEL(wave);
70
71 #ifdef HAVE_LIBAUDIOIO
72
73 /* Allow 1% deviation for sample rates (some ES137x cards) */
74 #define NEAR_MATCH(rate1,rate2) (((100*((int)(rate1)-(int)(rate2)))/(rate1))==0)
75
76 #define SOUND_DEV "/dev/audio"
77 #define DEFAULT_FRAGMENT_SIZE 4096
78
79
80
81 #define MAX_WAVEOUTDRV  (1)
82 #define MAX_WAVEINDRV   (1)
83
84 /* state diagram for waveOut writing:
85  *
86  * +---------+-------------+---------------+---------------------------------+
87  * |  state  |  function   |     event     |            new state            |
88  * +---------+-------------+---------------+---------------------------------+
89  * |         | open()      |               | STOPPED                         |
90  * | PAUSED  | write()     |               | PAUSED                          |
91  * | STOPPED | write()     | <thrd create> | PLAYING                         |
92  * | PLAYING | write()     | HEADER        | PLAYING                         |
93  * | (other) | write()     | <error>       |                                 |
94  * | (any)   | pause()     | PAUSING       | PAUSED                          |
95  * | PAUSED  | restart()   | RESTARTING    | PLAYING (if no thrd => STOPPED) |
96  * | (any)   | reset()     | RESETTING     | STOPPED                         |
97  * | (any)   | close()     | CLOSING       | CLOSED                          |
98  * +---------+-------------+---------------+---------------------------------+
99  */
100
101 /* states of the playing device */
102 #define WINE_WS_PLAYING         0
103 #define WINE_WS_PAUSED          1
104 #define WINE_WS_STOPPED         2
105 #define WINE_WS_CLOSED          3
106
107 /* events to be send to device */
108 #define WINE_WM_PAUSING         (WM_USER + 1)
109 #define WINE_WM_RESTARTING      (WM_USER + 2)
110 #define WINE_WM_RESETTING       (WM_USER + 3)
111 #define WINE_WM_CLOSING         (WM_USER + 4)
112 #define WINE_WM_HEADER          (WM_USER + 5)
113
114 #define WINE_WM_FIRST WINE_WM_PAUSING
115 #define WINE_WM_LAST WINE_WM_HEADER
116
117 typedef struct {
118     int msg;
119     DWORD param;
120 } WWO_MSG;
121
122 typedef struct {
123     int                         unixdev;
124     volatile int                state;                  /* one of the WINE_WS_ manifest constants */
125     DWORD                       dwFragmentSize;         /* size of OSS buffer fragment */
126     WAVEOPENDESC                waveDesc;
127     WORD                        wFlags;
128     PCMWAVEFORMAT               format;
129     LPWAVEHDR                   lpQueuePtr;             /* start of queued WAVEHDRs (waiting to be notified) */
130     LPWAVEHDR                   lpPlayPtr;              /* start of not yet fully played buffers */
131     LPWAVEHDR                   lpLoopPtr;              /* pointer of first buffer in loop, if any */
132     DWORD                       dwLoops;                /* private copy of loop counter */
133
134     DWORD                       dwLastFragDone;         /* time in ms, when last played fragment will be actually played */
135     DWORD                       dwPlayedTotal;          /* number of bytes played since opening */
136
137     /* info on current lpQueueHdr->lpWaveHdr */
138     DWORD                       dwOffCurrHdr;           /* offset in lpPlayPtr->lpData for fragments */
139     DWORD                       dwRemain;               /* number of bytes to write to end the current fragment  */
140
141     /* synchronization stuff */
142     HANDLE                      hThread;
143     DWORD                       dwThreadID;
144     HANDLE                      hEvent;
145 #define WWO_RING_BUFFER_SIZE    30
146     WWO_MSG                     messages[WWO_RING_BUFFER_SIZE];
147     int                         msg_tosave;
148     int                         msg_toget;
149     HANDLE                      msg_event;
150     CRITICAL_SECTION            msg_crst;
151     WAVEOUTCAPSW                caps;
152
153     /* DirectSound stuff */
154     LPBYTE                      mapping;
155     DWORD                       maplen;
156 } WINE_WAVEOUT;
157
158 typedef struct {
159     int                         unixdev;
160     volatile int                state;
161     DWORD                       dwFragmentSize;         /* OpenSound '/dev/dsp' give us that size */
162     WAVEOPENDESC                waveDesc;
163     WORD                        wFlags;
164     PCMWAVEFORMAT               format;
165     LPWAVEHDR                   lpQueuePtr;
166     DWORD                       dwTotalRecorded;
167     WAVEINCAPSW                 caps;
168     BOOL                        bTriggerSupport;
169
170     /* synchronization stuff */
171     HANDLE                      hThread;
172     DWORD                       dwThreadID;
173     HANDLE                      hEvent;
174 } WINE_WAVEIN;
175
176 static WINE_WAVEOUT     WOutDev   [MAX_WAVEOUTDRV];
177 static WINE_WAVEIN      WInDev    [MAX_WAVEINDRV ];
178
179 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
180 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv);
181 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
182 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc);
183
184 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
185                              PCMWAVEFORMAT* format)
186 {
187     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%u nChannels=%u nAvgBytesPerSec=%u\n",
188           lpTime->wType, format->wBitsPerSample, format->wf.nSamplesPerSec,
189           format->wf.nChannels, format->wf.nAvgBytesPerSec);
190     TRACE("Position in bytes=%u\n", position);
191
192     switch (lpTime->wType) {
193     case TIME_SAMPLES:
194         lpTime->u.sample = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
195         TRACE("TIME_SAMPLES=%u\n", lpTime->u.sample);
196         break;
197     case TIME_MS:
198         lpTime->u.ms = 1000.0 * position / (format->wBitsPerSample / 8 * format->wf.nChannels * format->wf.nSamplesPerSec);
199         TRACE("TIME_MS=%u\n", lpTime->u.ms);
200         break;
201     case TIME_SMPTE:
202         lpTime->u.smpte.fps = 30;
203         position = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
204         position += (format->wf.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
205         lpTime->u.smpte.sec = position / format->wf.nSamplesPerSec;
206         position -= lpTime->u.smpte.sec * format->wf.nSamplesPerSec;
207         lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
208         lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
209         lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
210         lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
211         lpTime->u.smpte.fps = 30;
212         lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->wf.nSamplesPerSec;
213         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
214               lpTime->u.smpte.hour, lpTime->u.smpte.min,
215               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
216         break;
217     default:
218         FIXME("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
219         lpTime->wType = TIME_BYTES;
220         /* fall through */
221     case TIME_BYTES:
222         lpTime->u.cb = position;
223         TRACE("TIME_BYTES=%u\n", lpTime->u.cb);
224         break;
225     }
226     return MMSYSERR_NOERROR;
227 }
228
229 /*======================================================================*
230  *                  Low level WAVE implementation                       *
231  *======================================================================*/
232 SampleSpec_t spec[2];
233
234
235
236 LONG LIBAUDIOIO_WaveInit(void)
237 {
238     int         audio;
239     int         smplrate;
240     int         samplesize = 16;
241     int         dsp_stereo = 1;
242     int         bytespersmpl;
243     int         caps;
244     int         mask;
245     int         i;
246
247     int audio_fd;
248     int mode;
249
250     static const WCHAR ini_out[] = {'A','u','d','i','o','I','O',' ','W','a','v','e','O','u','t',' ','D','r','i','v','e','r',0};
251     static const WCHAR ini_in [] = {'A','u','d','i','o','I','O',' ','W','a','v','e','I','n',' ',' ','D','r','i','v','e','r',0};
252
253     TRACE("Init ENTERED (%d) (%d) rate = %d\n",CLIENT_PLAYBACK,CLIENT_RECORD,spec[CLIENT_PLAYBACK].rate);
254     spec[CLIENT_RECORD].channels=spec[CLIENT_PLAYBACK].channels=2;
255     spec[CLIENT_RECORD].max_blocks=spec[CLIENT_PLAYBACK].max_blocks=16;
256     spec[CLIENT_RECORD].rate=spec[CLIENT_PLAYBACK].rate=44100;
257     spec[CLIENT_RECORD].encoding=spec[CLIENT_PLAYBACK].encoding= ENCODE_PCM;
258     spec[CLIENT_RECORD].precision=spec[CLIENT_PLAYBACK].precision=16 ;
259     spec[CLIENT_RECORD].endian=spec[CLIENT_PLAYBACK].endian=ENDIAN_INTEL;
260     spec[CLIENT_RECORD].disable_threads=spec[CLIENT_PLAYBACK].disable_threads=1;
261     spec[CLIENT_RECORD].type=spec[CLIENT_PLAYBACK].type=TYPE_SIGNED; /* in 16 bit mode this is what typical PC hardware expects */
262
263     mode = O_WRONLY|O_NDELAY;
264
265     /* start with output device */
266
267     /* initialize all device handles to -1 */
268     for (i = 0; i < MAX_WAVEOUTDRV; ++i)
269     {
270         WOutDev[i].unixdev = -1;
271     }
272
273     /* FIXME: only one device is supported */
274     memset(&WOutDev[0].caps, 0, sizeof(WOutDev[0].caps));
275
276     WOutDev[0].caps.wMid = 0x00FF;      /* Manufac ID */
277     WOutDev[0].caps.wPid = 0x0001;      /* Product ID */
278     strcpyW(WOutDev[0].caps.szPname, ini_out);
279     WOutDev[0].caps.vDriverVersion = 0x0100;
280     WOutDev[0].caps.dwFormats = 0x00000000;
281     WOutDev[0].caps.dwSupport = WAVECAPS_VOLUME;
282
283     /*
284      * Libaudioio works differently, you tell it what spec audio you want to write
285      * and it guarantees to match it by converting to the final format on the fly.
286      * So we don't need to read  back and compare.
287      */
288
289     bytespersmpl = spec[CLIENT_PLAYBACK].precision/8;
290
291     WOutDev[0].caps.wChannels = spec[CLIENT_PLAYBACK].channels;
292
293
294 /* Fixme: Libaudioio 0.2 doesn't support balance yet (Libaudioio 0.3 does so this must be fixed later)*/
295
296 /*    if (WOutDev[0].caps.wChannels > 1) WOutDev[0].caps.dwSupport |= WAVECAPS_LRVOLUME;*/
297     TRACE("Init sammplerate= %d\n",spec[CLIENT_PLAYBACK].rate);
298
299     smplrate = spec[CLIENT_PLAYBACK].rate;
300 /*
301  * We have set up the data format to be 16 bit signed in intel format
302  * For Big Endian machines libaudioio will convert the data to bigendian for us
303  */
304
305     WOutDev[0].caps.dwFormats |= WAVE_FORMAT_4M16;
306     if (WOutDev[0].caps.wChannels > 1)
307         WOutDev[0].caps.dwFormats |= WAVE_FORMAT_4S16;
308
309 /* Don't understand this yet, but I don't think this functionality is portable, leave it here for future evaluation
310  *   if (IOCTL(audio, SNDCTL_DSP_GETCAPS, caps) == 0) {
311  *      TRACE("OSS dsp out caps=%08X\n", caps);
312  *      if ((caps & DSP_CAP_REALTIME) && !(caps & DSP_CAP_BATCH)) {
313  *          WOutDev[0].caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
314  *      }
315  */     /* well, might as well use the DirectSound cap flag for something */
316 /*      if ((caps & DSP_CAP_TRIGGER) && (caps & DSP_CAP_MMAP) &&
317  *          !(caps & DSP_CAP_BATCH))
318  *          WOutDev[0].caps.dwSupport |= WAVECAPS_DIRECTSOUND;
319  *   }
320  */
321
322
323 /*
324  * Note that libaudioio audio capture is not proven yet, in our open call
325  * set the spec for input audio the same as for output
326  */
327     TRACE("out dwFormats = %08X, dwSupport = %08X\n",
328           WOutDev[0].caps.dwFormats, WOutDev[0].caps.dwSupport);
329
330     for (i = 0; i < MAX_WAVEINDRV; ++i)
331     {
332         WInDev[i].unixdev = -1;
333     }
334
335     memset(&WInDev[0].caps, 0, sizeof(WInDev[0].caps));
336
337     WInDev[0].caps.wMid = 0x00FF;       /* Manufac ID */
338     WInDev[0].caps.wPid = 0x0001;       /* Product ID */
339     strcpyW(WInDev[0].caps.szPname, ini_in);
340     WInDev[0].caps.dwFormats = 0x00000000;
341     WInDev[0].caps.wChannels = spec[CLIENT_RECORD].channels;
342
343     WInDev[0].bTriggerSupport = TRUE;    /* Maybe :-) */
344
345     bytespersmpl = spec[CLIENT_RECORD].precision/8;
346     smplrate = spec[CLIENT_RECORD].rate;
347
348             WInDev[0].caps.dwFormats |= WAVE_FORMAT_4M16;
349             if (WInDev[0].caps.wChannels > 1)
350                 WInDev[0].caps.dwFormats |= WAVE_FORMAT_4S16;
351
352
353     TRACE("in dwFormats = %08X\n", WInDev[0].caps.dwFormats);
354
355     return 0;
356 }
357
358 /**************************************************************************
359  *                      LIBAUDIOIO_NotifyClient                 [internal]
360  */
361 static DWORD LIBAUDIOIO_NotifyClient(UINT wDevID, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
362 {
363     TRACE("wDevID = %04X wMsg = 0x%04x dwParm1 = %04X dwParam2 = %04X\n",wDevID, wMsg, dwParam1, dwParam2);
364
365     switch (wMsg) {
366     case WOM_OPEN:
367     case WOM_CLOSE:
368     case WOM_DONE:
369         if (wDevID >= MAX_WAVEOUTDRV) return MCIERR_INTERNAL;
370
371         if (WOutDev[wDevID].wFlags != DCB_NULL &&
372             !DriverCallback(WOutDev[wDevID].waveDesc.dwCallback,
373                             WOutDev[wDevID].wFlags,
374                             WOutDev[wDevID].waveDesc.hWave,
375                             wMsg,
376                             WOutDev[wDevID].waveDesc.dwInstance,
377                             dwParam1,
378                             dwParam2)) {
379             WARN("can't notify client !\n");
380             return MMSYSERR_NOERROR;
381         }
382         break;
383
384     case WIM_OPEN:
385     case WIM_CLOSE:
386     case WIM_DATA:
387         if (wDevID >= MAX_WAVEINDRV) return MCIERR_INTERNAL;
388
389         if (WInDev[wDevID].wFlags != DCB_NULL &&
390             !DriverCallback(WInDev[wDevID].waveDesc.dwCallback,
391                             WInDev[wDevID].wFlags,
392                             WInDev[wDevID].waveDesc.hWave,
393                             wMsg,
394                             WInDev[wDevID].waveDesc.dwInstance,
395                             dwParam1,
396                             dwParam2)) {
397             WARN("can't notify client !\n");
398             return MMSYSERR_NOERROR;
399         }
400         break;
401     default:
402         FIXME("Unknown CB message %u\n", wMsg);
403         break;
404     }
405     return 0;
406 }
407
408 /*======================================================================*
409  *                  Low level WAVE OUT implementation                   *
410  *======================================================================*/
411
412 /**************************************************************************
413  *                              wodPlayer_WriteFragments        [internal]
414  *
415  * wodPlayer helper. Writes as many fragments as it can to unixdev.
416  * Returns TRUE in case of buffer underrun.
417  */
418 static  BOOL    wodPlayer_WriteFragments(WINE_WAVEOUT* wwo)
419 {
420     LPWAVEHDR           lpWaveHdr;
421     LPBYTE              lpData;
422     int                 count;
423
424     TRACE("wodPlayer_WriteFragments sammplerate= %d\n",spec[CLIENT_PLAYBACK].rate);
425     for (;;) {
426
427
428 /*
429  * Libaudioio doesn't buffer the same way as linux, you can write data is any block size
430  *And libaudioio just tracks the number of blocks in the streams queue to control latency
431  */
432
433         if (!AudioIOCheckWriteReady()) return FALSE;   /*  Returns false if you have execeeded your specified latency (No space left)*/
434
435         lpWaveHdr = wwo->lpPlayPtr;
436         if (!lpWaveHdr) {
437             if (wwo->dwRemain > 0 &&            /* still data to send to complete current fragment */
438                 wwo->dwLastFragDone &&          /* first fragment has been played */
439                 AudioIOCheckUnderrun()) {   /* done with all waveOutWrite()' fragments */
440                 /* FIXME: should do better handling here */
441                 WARN("Oooch, buffer underrun !\n");
442                 return TRUE; /* force resetting of waveOut device */
443             }
444             return FALSE;       /* wait a bit */
445         }
446
447         if (wwo->dwOffCurrHdr == 0) {
448             TRACE("Starting a new wavehdr %p of %d bytes\n", lpWaveHdr, lpWaveHdr->dwBufferLength);
449             if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
450                 if (wwo->lpLoopPtr) {
451                     WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
452                 } else {
453                     TRACE("Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
454                     wwo->lpLoopPtr = lpWaveHdr;
455                     /* Windows does not touch WAVEHDR.dwLoops,
456                      * so we need to make an internal copy */
457                     wwo->dwLoops = lpWaveHdr->dwLoops;
458                 }
459             }
460         }
461
462         lpData = lpWaveHdr->lpData;
463
464         /* finish current wave hdr ? */
465         if (wwo->dwOffCurrHdr + wwo->dwRemain >= lpWaveHdr->dwBufferLength) {
466             DWORD       toWrite = lpWaveHdr->dwBufferLength - wwo->dwOffCurrHdr;
467
468             /* write end of current wave hdr */
469             count = AudioIOWrite(lpData + wwo->dwOffCurrHdr, toWrite);
470             TRACE("write(%p[%5u], %5u) => %d\n", lpData, wwo->dwOffCurrHdr, toWrite, count);
471
472             if (count > 0 || toWrite == 0) {
473                 DWORD   tc = GetTickCount();
474
475                 if (wwo->dwLastFragDone /* + guard time ?? */ < tc)
476                     wwo->dwLastFragDone = tc;
477                 wwo->dwLastFragDone += (toWrite * 1000) / wwo->format.wf.nAvgBytesPerSec;
478
479                 lpWaveHdr->reserved = wwo->dwLastFragDone;
480                 TRACE("Tagging hdr %p with %08x\n", lpWaveHdr, wwo->dwLastFragDone);
481
482                 /* WAVEHDR written, go to next one */
483                 if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
484                     if (--wwo->dwLoops > 0) {
485                         wwo->lpPlayPtr = wwo->lpLoopPtr;
486                     } else {
487                         /* last one played */
488                         if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
489                             FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
490                             /* shall we consider the END flag for the closing loop or for
491                              * the opening one or for both ???
492                              * code assumes for closing loop only
493                              */
494                             wwo->lpLoopPtr = lpWaveHdr;
495                         } else {
496                             wwo->lpLoopPtr = NULL;
497                         }
498                         wwo->lpPlayPtr = lpWaveHdr->lpNext;
499                     }
500                 } else {
501                     wwo->lpPlayPtr = lpWaveHdr->lpNext;
502                 }
503                 wwo->dwOffCurrHdr = 0;
504                 if ((wwo->dwRemain -= count) == 0) {
505                     wwo->dwRemain = wwo->dwFragmentSize;
506                 }
507             }
508             continue; /* try to go to use next wavehdr */
509         }  else {
510             count = AudioIOWrite( lpData + wwo->dwOffCurrHdr, wwo->dwRemain);
511             TRACE("write(%p[%5u], %5u) => %d\n", lpData, wwo->dwOffCurrHdr, wwo->dwRemain, count);
512             if (count > 0) {
513                 DWORD   tc = GetTickCount();
514
515                 if (wwo->dwLastFragDone /* + guard time ?? */ < tc)
516                     wwo->dwLastFragDone = tc;
517                 wwo->dwLastFragDone += (wwo->dwRemain * 1000) / wwo->format.wf.nAvgBytesPerSec;
518
519                 TRACE("Tagging frag with %08x\n", wwo->dwLastFragDone);
520
521                 wwo->dwOffCurrHdr += count;
522                 wwo->dwRemain = wwo->dwFragmentSize;
523             }
524         }
525     }
526
527 }
528
529 int wodPlayer_Message(WINE_WAVEOUT *wwo, int msg, DWORD param)
530 {
531     TRACE("wodPlayerMessage sammplerate= %d  msg=%d\n",spec[CLIENT_PLAYBACK].rate,msg);
532     EnterCriticalSection(&wwo->msg_crst);
533     if ((wwo->msg_tosave == wwo->msg_toget) /* buffer overflow ? */
534     &&  (wwo->messages[wwo->msg_toget].msg))
535     {
536         ERR("buffer overflow !?\n");
537         LeaveCriticalSection(&wwo->msg_crst);
538         return 0;
539     }
540
541     wwo->messages[wwo->msg_tosave].msg = msg;
542     wwo->messages[wwo->msg_tosave].param = param;
543     wwo->msg_tosave++;
544     if (wwo->msg_tosave > WWO_RING_BUFFER_SIZE-1)
545         wwo->msg_tosave = 0;
546     LeaveCriticalSection(&wwo->msg_crst);
547     /* signal a new message */
548     SetEvent(wwo->msg_event);
549     return 1;
550 }
551
552 int wodPlayer_RetrieveMessage(WINE_WAVEOUT *wwo, int *msg, DWORD *param)
553 {
554     EnterCriticalSection(&wwo->msg_crst);
555
556     if (wwo->msg_toget == wwo->msg_tosave) /* buffer empty ? */
557     {
558         LeaveCriticalSection(&wwo->msg_crst);
559         return 0;
560     }
561
562     *msg = wwo->messages[wwo->msg_toget].msg;
563     wwo->messages[wwo->msg_toget].msg = 0;
564     *param = wwo->messages[wwo->msg_toget].param;
565     wwo->msg_toget++;
566     if (wwo->msg_toget > WWO_RING_BUFFER_SIZE-1)
567         wwo->msg_toget = 0;
568     LeaveCriticalSection(&wwo->msg_crst);
569     return 1;
570 }
571
572 /**************************************************************************
573  *                              wodPlayer_Notify                [internal]
574  *
575  * wodPlayer helper. Notifies (and remove from queue) all the wavehdr which content
576  * have been played (actually to speaker, not to unixdev fd).
577  */
578 static  void    wodPlayer_Notify(WINE_WAVEOUT* wwo, WORD uDevID, BOOL force)
579 {
580     LPWAVEHDR           lpWaveHdr;
581     DWORD               tc = GetTickCount();
582
583     while (wwo->lpQueuePtr &&
584            (force ||
585             (wwo->lpQueuePtr != wwo->lpPlayPtr && wwo->lpQueuePtr != wwo->lpLoopPtr))) {
586         lpWaveHdr = wwo->lpQueuePtr;
587
588         if (lpWaveHdr->reserved > tc && !force) break;
589
590         wwo->dwPlayedTotal += lpWaveHdr->dwBufferLength;
591         wwo->lpQueuePtr = lpWaveHdr->lpNext;
592
593         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
594         lpWaveHdr->dwFlags |= WHDR_DONE;
595
596         TRACE("Notifying client with %p\n", lpWaveHdr);
597         if (LIBAUDIOIO_NotifyClient(uDevID, WOM_DONE, (DWORD)lpWaveHdr, 0) != MMSYSERR_NOERROR) {
598             WARN("can't notify client !\n");
599         }
600     }
601 }
602
603 /**************************************************************************
604  *                              wodPlayer_Reset                 [internal]
605  *
606  * wodPlayer helper. Resets current output stream.
607  */
608 static  void    wodPlayer_Reset(WINE_WAVEOUT* wwo, WORD uDevID, BOOL reset)
609 {
610     /* updates current notify list */
611     wodPlayer_Notify(wwo, uDevID, FALSE);
612
613     /* flush all possible output */
614 /*
615  *FIXME In the original code I think this aborted IO. With Libaudioio you have to wait
616  * The following function just blocks until I/O is complete
617  * There is possibly a way to abort the blocks buffered in streams
618  * but this approach seems to work OK
619  */
620         AudioIOFlush();
621
622
623
624     wwo->dwOffCurrHdr = 0;
625     wwo->dwRemain = wwo->dwFragmentSize;
626     if (reset) {
627         /* empty notify list */
628         wodPlayer_Notify(wwo, uDevID, TRUE);
629
630         wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
631         wwo->state = WINE_WS_STOPPED;
632         wwo->dwPlayedTotal = 0;
633     } else {
634         /* FIXME: this is not accurate when looping, but can be do better ? */
635         wwo->lpPlayPtr = (wwo->lpLoopPtr) ? wwo->lpLoopPtr : wwo->lpQueuePtr;
636         wwo->state = WINE_WS_PAUSED;
637     }
638 }
639
640 /**************************************************************************
641  *                              wodPlayer                       [internal]
642  */
643 static  DWORD   CALLBACK        wodPlayer(LPVOID pmt)
644 {
645     WORD                uDevID = (DWORD)pmt;
646     WINE_WAVEOUT*       wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
647     WAVEHDR*            lpWaveHdr;
648     DWORD               dwSleepTime;
649     int                 msg;
650     DWORD               param;
651     DWORD               tc;
652     BOOL                had_msg;
653
654     wwo->state = WINE_WS_STOPPED;
655
656     wwo->dwLastFragDone = 0;
657     wwo->dwOffCurrHdr = 0;
658     wwo->dwRemain = wwo->dwFragmentSize;
659     wwo->lpQueuePtr = wwo->lpPlayPtr = wwo->lpLoopPtr = NULL;
660     wwo->dwPlayedTotal = 0;
661
662     TRACE("imhere[0]\n");
663     SetEvent(wwo->hEvent);
664
665     for (;;) {
666         /* wait for dwSleepTime or an event in thread's queue
667          * FIXME:
668          * - is wait time calculation optimal ?
669          * - these 100 ms parts should be changed, but Eric reports
670          *   that the wodPlayer thread might lock up if we use INFINITE
671          *   (strange !), so I better don't change that now... */
672         if (wwo->state != WINE_WS_PLAYING)
673             dwSleepTime = 100;
674         else
675         {
676             tc = GetTickCount();
677             if (tc < wwo->dwLastFragDone)
678             {
679                 /* calculate sleep time depending on when the last fragment
680                    will be played */
681                 dwSleepTime = (wwo->dwLastFragDone - tc)*7/10;
682                 if (dwSleepTime > 100)
683                     dwSleepTime = 100;
684             }
685             else
686                 dwSleepTime = 0;
687         }
688
689         TRACE("imhere[1] tc = %08x\n", GetTickCount());
690         if (dwSleepTime)
691             WaitForSingleObject(wwo->msg_event, dwSleepTime);
692         TRACE("imhere[2] (q=%p p=%p) tc = %08x\n", wwo->lpQueuePtr,
693               wwo->lpPlayPtr, GetTickCount());
694         had_msg = FALSE;
695                 TRACE("Looking for message\n");
696         while (wodPlayer_RetrieveMessage(wwo, &msg, &param)) {
697             had_msg = TRUE;
698                 TRACE("Processing message\n");
699             switch (msg) {
700             case WINE_WM_PAUSING:
701                 TRACE("WINE_WM_PAUSING\n");
702                 wodPlayer_Reset(wwo, uDevID, FALSE);
703                 wwo->state = WINE_WS_PAUSED;
704                 SetEvent(wwo->hEvent);
705                 break;
706             case WINE_WM_RESTARTING:
707                 TRACE("WINE_WM_RESTARTING\n");
708                 wwo->state = WINE_WS_PLAYING;
709                 SetEvent(wwo->hEvent);
710                 break;
711             case WINE_WM_HEADER:
712                 TRACE("WINE_WM_HEADER\n");
713                 lpWaveHdr = (LPWAVEHDR)param;
714
715                 /* insert buffer at the end of queue */
716                 {
717                     LPWAVEHDR*  wh;
718                     for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
719                     *wh = lpWaveHdr;
720                 }
721                 if (!wwo->lpPlayPtr) wwo->lpPlayPtr = lpWaveHdr;
722                 if (wwo->state == WINE_WS_STOPPED)
723                     wwo->state = WINE_WS_PLAYING;
724                 break;
725             case WINE_WM_RESETTING:
726                 TRACE("WINE_WM_RESETTING\n");       
727                 wodPlayer_Reset(wwo, uDevID, TRUE);
728                 SetEvent(wwo->hEvent);
729                 break;
730             case WINE_WM_CLOSING:
731                 TRACE("WINE_WM_CLOSING\n");         
732                 /* sanity check: this should not happen since the device must have been reset before */
733                 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
734                 wwo->hThread = 0;
735                 wwo->state = WINE_WS_CLOSED;
736                 SetEvent(wwo->hEvent);
737                 ExitThread(0);
738                 /* shouldn't go here */
739             default:
740                 FIXME("unknown message %d\n", msg);
741                 break;
742             }
743             if (wwo->state == WINE_WS_PLAYING) {
744                 TRACE("Writing Fragment\n");
745                 wodPlayer_WriteFragments(wwo);
746             }
747             wodPlayer_Notify(wwo, uDevID, FALSE);
748         }
749
750         if (!had_msg) { /* if we've received a msg we've just done this so we
751                            won't repeat it */
752             if (wwo->state == WINE_WS_PLAYING) {
753                 TRACE("Writing Fragment (entry 2)\n");
754                 wodPlayer_WriteFragments(wwo);
755             }
756             wodPlayer_Notify(wwo, uDevID, FALSE);
757         }
758     }
759     ExitThread(0);
760     /* just for not generating compilation warnings... should never be executed */
761     return 0;
762 }
763
764 /**************************************************************************
765  *                      wodGetDevCaps                           [internal]
766  */
767 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
768 {
769     TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
770
771     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
772
773     if (wDevID >= MAX_WAVEOUTDRV) {
774         TRACE("MAX_WAVOUTDRV reached !\n");
775         return MMSYSERR_BADDEVICEID;
776     }
777
778     memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
779     return MMSYSERR_NOERROR;
780 }
781
782 /**************************************************************************
783  *                              wodOpen                         [internal]
784  */
785 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
786 {
787     int                 audio;
788     int                 format;
789     int                 sample_rate;
790     int                 dsp_stereo;
791     int                 fragment_size;
792     int                 audio_fragment;
793     WINE_WAVEOUT*       wwo;
794
795     TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
796     if (lpDesc == NULL) {
797         WARN("Invalid Parameter !\n");
798         return MMSYSERR_INVALPARAM;
799     }
800     if (wDevID >= MAX_WAVEOUTDRV) {
801         TRACE("MAX_WAVOUTDRV reached !\n");
802         return MMSYSERR_BADDEVICEID;
803     }
804
805     /* only PCM format is supported so far... */
806     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
807         lpDesc->lpFormat->nChannels == 0 ||
808         lpDesc->lpFormat->nSamplesPerSec == 0 ||
809         (lpDesc->lpFormat->wBitsPerSample!=8 && lpDesc->lpFormat->wBitsPerSample!=16)) {
810         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
811              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
812              lpDesc->lpFormat->nSamplesPerSec);
813         return WAVERR_BADFORMAT;
814     }
815
816     if (dwFlags & WAVE_FORMAT_QUERY) {
817         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
818              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
819              lpDesc->lpFormat->nSamplesPerSec);
820         return MMSYSERR_NOERROR;
821     }
822
823     wwo = &WOutDev[wDevID];
824
825     if ((dwFlags & WAVE_DIRECTSOUND) && !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
826         /* not supported, ignore it */
827         dwFlags &= ~WAVE_DIRECTSOUND;
828
829     if (access(SOUND_DEV, 0) != 0)
830         return MMSYSERR_NOTENABLED;
831
832         audio = AudioIOOpenX( O_WRONLY|O_NDELAY,&spec[CLIENT_PLAYBACK],&spec[CLIENT_PLAYBACK]);
833
834     if (audio == -1) {
835         WARN("can't open sound device %s (%s)!\n", SOUND_DEV, strerror(errno));
836         return MMSYSERR_ALLOCATED;
837     }
838  /*   fcntl(audio, F_SETFD, 1); *//* set close on exec flag - Dunno about this (RL)*/
839     wwo->unixdev = audio;
840     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
841
842     memcpy(&wwo->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
843     memcpy(&wwo->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
844
845     if (wwo->format.wBitsPerSample == 0) {
846         WARN("Resetting zeroed wBitsPerSample\n");
847         wwo->format.wBitsPerSample = 8 *
848             (wwo->format.wf.nAvgBytesPerSec /
849              wwo->format.wf.nSamplesPerSec) /
850             wwo->format.wf.nChannels;
851     }
852
853     if (dwFlags & WAVE_DIRECTSOUND) {
854         if (wwo->caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
855             /* we have realtime DirectSound, fragments just waste our time,
856              * but a large buffer is good, so choose 64KB (32 * 2^11) */
857             audio_fragment = 0x0020000B;
858         else
859             /* to approximate realtime, we must use small fragments,
860              * let's try to fragment the above 64KB (256 * 2^8) */
861             audio_fragment = 0x01000008;
862     } else {
863         /* shockwave player uses only 4 1k-fragments at a rate of 22050 bytes/sec
864          * thus leading to 46ms per fragment, and a turnaround time of 185ms
865          */
866         /* 16 fragments max, 2^10=1024 bytes per fragment */
867         audio_fragment = 0x000F000A;
868     }
869     sample_rate = wwo->format.wf.nSamplesPerSec;
870     dsp_stereo = (wwo->format.wf.nChannels > 1) ? 1 : 0;
871
872
873
874     /*Set the sample rate*/
875     spec[CLIENT_PLAYBACK].rate=sample_rate;
876
877     /*And the size and signedness*/
878     spec[CLIENT_PLAYBACK].precision=(wwo->format.wBitsPerSample );
879     if (spec[CLIENT_PLAYBACK].precision==16) spec[CLIENT_PLAYBACK].type=TYPE_SIGNED; else spec[CLIENT_PLAYBACK].type=TYPE_UNSIGNED;
880     spec[CLIENT_PLAYBACK].channels=(wwo->format.wf.nChannels);
881     spec[CLIENT_PLAYBACK].encoding=ENCODE_PCM;
882     spec[CLIENT_PLAYBACK].endian=ENDIAN_INTEL;
883     spec[CLIENT_PLAYBACK].max_blocks=16;  /*FIXME This is the libaudioio equivalent to fragments, it controls latency*/
884
885         audio = AudioIOOpenX( O_WRONLY|O_NDELAY,&spec[CLIENT_PLAYBACK],&spec[CLIENT_PLAYBACK]);
886
887     if (audio == -1) {
888         WARN("can't open sound device %s (%s)!\n", SOUND_DEV, strerror(errno));
889         return MMSYSERR_ALLOCATED;
890     }
891  /*   fcntl(audio, F_SETFD, 1); *//* set close on exec flag */
892     wwo->unixdev = audio;
893
894
895     /* even if we set fragment size above, read it again, just in case */
896
897     wwo->dwFragmentSize = DEFAULT_FRAGMENT_SIZE;
898
899     wwo->msg_toget = 0;
900     wwo->msg_tosave = 0;
901     wwo->msg_event = CreateEventW(NULL, FALSE, FALSE, NULL);
902     memset(wwo->messages, 0, sizeof(WWO_MSG)*WWO_RING_BUFFER_SIZE);
903     InitializeCriticalSection(&wwo->msg_crst);
904     wwo->msg_crst.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": WINE_WAVEOUT.msg_crst");
905
906     if (!(dwFlags & WAVE_DIRECTSOUND)) {
907         TRACE("Starting wodPlayer Thread\n");
908         wwo->hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
909         wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
910         if (wwo->hThread)
911             SetThreadPriority(wwo->hThread, THREAD_PRIORITY_TIME_CRITICAL);
912         WaitForSingleObject(wwo->hEvent, INFINITE);
913     } else {
914         wwo->hEvent = INVALID_HANDLE_VALUE;
915         wwo->hThread = INVALID_HANDLE_VALUE;
916         wwo->dwThreadID = 0;
917     }
918
919     TRACE("fd=%d fragmentSize=%d\n",
920           wwo->unixdev, wwo->dwFragmentSize);
921     if (wwo->dwFragmentSize % wwo->format.wf.nBlockAlign)
922         ERR("Fragment doesn't contain an integral number of data blocks\n");
923
924     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%u, nSamplesPerSec=%u, nChannels=%u nBlockAlign=%u!\n",
925           wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec,
926           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
927           wwo->format.wf.nBlockAlign);
928
929     if (LIBAUDIOIO_NotifyClient(wDevID, WOM_OPEN, 0L, 0L) != MMSYSERR_NOERROR) {
930         WARN("can't notify client !\n");
931         return MMSYSERR_INVALPARAM;
932     }
933     return MMSYSERR_NOERROR;
934 }
935
936 /**************************************************************************
937  *                              wodClose                        [internal]
938  */
939 static DWORD wodClose(WORD wDevID)
940 {
941     DWORD               ret = MMSYSERR_NOERROR;
942     WINE_WAVEOUT*       wwo;
943
944     TRACE("(%u);\n", wDevID);
945
946     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
947         WARN("bad device ID !\n");
948         return MMSYSERR_BADDEVICEID;
949     }
950
951     wwo = &WOutDev[wDevID];
952     if (wwo->lpQueuePtr) {
953         WARN("buffers still playing !\n");
954         ret = WAVERR_STILLPLAYING;
955     } else {
956         TRACE("imhere[3-close]\n");
957
958         wwo->msg_crst.DebugInfo->Spare[0] = 0;
959         DeleteCriticalSection(&wwo->msg_crst);
960
961         if (wwo->hEvent != INVALID_HANDLE_VALUE) {
962             wodPlayer_Message(wwo, WINE_WM_CLOSING, 0);
963             WaitForSingleObject(wwo->hEvent, INFINITE);
964             CloseHandle(wwo->hEvent);
965         }
966         if (wwo->mapping) {
967             munmap(wwo->mapping, wwo->maplen);
968             wwo->mapping = NULL;
969         }
970
971         AudioIOClose();
972         wwo->unixdev = -1;
973         wwo->dwFragmentSize = 0;
974         if (LIBAUDIOIO_NotifyClient(wDevID, WOM_CLOSE, 0L, 0L) != MMSYSERR_NOERROR) {
975             WARN("can't notify client !\n");
976             ret = MMSYSERR_INVALPARAM;
977         }
978     }
979     return ret;
980 }
981
982 /**************************************************************************
983  *                              wodWrite                        [internal]
984  *
985  */
986 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
987 {
988     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
989
990     /* first, do the sanity checks... */
991     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
992         WARN("bad dev ID !\n");
993         return MMSYSERR_BADDEVICEID;
994     }
995
996     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
997         return WAVERR_UNPREPARED;
998
999     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1000         return WAVERR_STILLPLAYING;
1001
1002     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1003     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1004     lpWaveHdr->lpNext = 0;
1005
1006     TRACE("imhere[3-HEADER]\n");
1007     wodPlayer_Message(&WOutDev[wDevID], WINE_WM_HEADER, (DWORD)lpWaveHdr);
1008
1009     return MMSYSERR_NOERROR;
1010 }
1011
1012 /**************************************************************************
1013  *                      wodPause                                [internal]
1014  */
1015 static DWORD wodPause(WORD wDevID)
1016 {
1017     TRACE("(%u);!\n", wDevID);
1018
1019     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1020         WARN("bad device ID !\n");
1021         return MMSYSERR_BADDEVICEID;
1022     }
1023
1024     TRACE("imhere[3-PAUSING]\n");
1025     wodPlayer_Message(&WOutDev[wDevID], WINE_WM_PAUSING, 0);
1026     WaitForSingleObject(WOutDev[wDevID].hEvent, INFINITE);
1027
1028     return MMSYSERR_NOERROR;
1029 }
1030
1031 /**************************************************************************
1032  *                      wodRestart                              [internal]
1033  */
1034 static DWORD wodRestart(WORD wDevID)
1035 {
1036     TRACE("(%u);\n", wDevID);
1037
1038     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1039         WARN("bad device ID !\n");
1040         return MMSYSERR_BADDEVICEID;
1041     }
1042
1043     if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1044         TRACE("imhere[3-RESTARTING]\n");
1045         wodPlayer_Message(&WOutDev[wDevID], WINE_WM_RESTARTING, 0);
1046         WaitForSingleObject(WOutDev[wDevID].hEvent, INFINITE);
1047     }
1048
1049     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1050     /* FIXME: Myst crashes with this ... hmm -MM
1051        if (LIBAUDIOIO_NotifyClient(wDevID, WOM_DONE, 0L, 0L) != MMSYSERR_NOERROR) {
1052        WARN("can't notify client !\n");
1053        return MMSYSERR_INVALPARAM;
1054        }
1055     */
1056
1057     return MMSYSERR_NOERROR;
1058 }
1059
1060 /**************************************************************************
1061  *                      wodReset                                [internal]
1062  */
1063 static DWORD wodReset(WORD wDevID)
1064 {
1065     TRACE("(%u);\n", wDevID);
1066
1067     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1068         WARN("bad device ID !\n");
1069         return MMSYSERR_BADDEVICEID;
1070     }
1071
1072     TRACE("imhere[3-RESET]\n");
1073     wodPlayer_Message(&WOutDev[wDevID], WINE_WM_RESETTING, 0);
1074     WaitForSingleObject(WOutDev[wDevID].hEvent, INFINITE);
1075
1076     return MMSYSERR_NOERROR;
1077 }
1078
1079
1080 /**************************************************************************
1081  *                              wodGetPosition                  [internal]
1082  */
1083 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1084 {
1085     WINE_WAVEOUT*       wwo;
1086
1087     TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
1088
1089     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1090         WARN("bad device ID !\n");
1091         return MMSYSERR_BADDEVICEID;
1092     }
1093
1094     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1095
1096     wwo = &WOutDev[wDevID];
1097
1098     return bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->format);
1099 }
1100
1101 /**************************************************************************
1102  *                              wodGetVolume                    [internal]
1103  */
1104 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1105 {
1106     int         vol,bal;
1107     DWORD       left, right;
1108
1109     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1110
1111     if (lpdwVol == NULL)
1112         return MMSYSERR_NOTENABLED;
1113
1114      vol=AudioIOGetPlaybackVolume();
1115      bal=AudioIOGetPlaybackBalance();
1116
1117
1118      if(bal<0) {
1119         left = vol;
1120         right=-(vol*(-100+bal)/100);
1121      }
1122       else
1123      {
1124         right = vol;
1125         left=(vol*(100-bal)/100);
1126      }
1127
1128     *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) << 16);
1129     return MMSYSERR_NOERROR;
1130 }
1131
1132
1133 /**************************************************************************
1134  *                              wodSetVolume                    [internal]
1135  */
1136 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1137 {
1138     int         volume,bal;
1139     DWORD       left, right;
1140
1141     TRACE("(%u, %08X);\n", wDevID, dwParam);
1142
1143     left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
1144     right = (HIWORD(dwParam) * 100) / 0xFFFFl;
1145     volume = max(left , right );
1146     bal=min(left,right);
1147     bal=bal*100/volume;
1148     if(right>left) bal=-100+bal; else bal=100-bal;
1149
1150     AudioIOSetPlaybackVolume(volume);
1151     AudioIOSetPlaybackBalance(bal);
1152
1153     return MMSYSERR_NOERROR;
1154 }
1155
1156 /**************************************************************************
1157  *                              wodGetNumDevs                   [internal]
1158  */
1159 static  DWORD   wodGetNumDevs(void)
1160 {
1161     DWORD       ret = 1;
1162
1163     /* FIXME: For now, only one sound device (SOUND_DEV) is allowed */
1164     int audio = open(SOUND_DEV, O_WRONLY|O_NDELAY, 0);
1165
1166     if (audio == -1) {
1167         if (errno != EBUSY)
1168             ret = 0;
1169     } else {
1170         close(audio);
1171
1172     }
1173     TRACE("NumDrivers = %d\n",ret);
1174     return ret;
1175 }
1176
1177 /**************************************************************************
1178  *                              wodMessage (WINEAUDIOIO.@)
1179  */
1180 DWORD WINAPI LIBAUDIOIO_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1181                             DWORD dwParam1, DWORD dwParam2)
1182 {
1183     TRACE("(%u, %04X, %08X, %08X, %08X);\n",
1184           wDevID, wMsg, dwUser, dwParam1, dwParam2);
1185
1186     switch (wMsg) {
1187     case DRVM_INIT:
1188     case DRVM_EXIT:
1189     case DRVM_ENABLE:
1190     case DRVM_DISABLE:
1191         /* FIXME: Pretend this is supported */
1192         return 0;
1193     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1194     case WODM_CLOSE:            return wodClose         (wDevID);
1195     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1196     case WODM_PAUSE:            return wodPause         (wDevID);
1197     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
1198     case WODM_BREAKLOOP:        return MMSYSERR_NOTSUPPORTED;
1199     case WODM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
1200     case WODM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
1201     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSW)dwParam1,      dwParam2);
1202     case WODM_GETNUMDEVS:       return wodGetNumDevs    ();
1203     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1204     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1205     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1206     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1207     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
1208     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
1209     case WODM_RESTART:          return wodRestart       (wDevID);
1210     case WODM_RESET:            return wodReset         (wDevID);
1211
1212     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate      (wDevID, (PIDSDRIVER*)dwParam1);
1213     case DRV_QUERYDSOUNDDESC:   return wodDsDesc        (wDevID, (PDSDRIVERDESC)dwParam1);
1214     default:
1215         FIXME("unknown message %d!\n", wMsg);
1216     }
1217     return MMSYSERR_NOTSUPPORTED;
1218 }
1219
1220 /*======================================================================*
1221  *                  Low level DSOUND implementation                     *
1222  *              While I have tampered somewhat with this code it is wholely unlikely that it works
1223  *              Elsewhere the driver returns Not Implemented for DIrectSound
1224  *              While it may be possible to map the sound device on Solaris
1225  *              Doing so would bypass the libaudioio library and therefore break any conversions
1226  *              that the libaudioio sample specification converter is doing
1227  *              **** All this is untested so far
1228  *======================================================================*/
1229
1230 typedef struct IDsDriverImpl IDsDriverImpl;
1231 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1232
1233 struct IDsDriverImpl
1234 {
1235     /* IUnknown fields */
1236     const IDsDriverVtbl *lpVtbl;
1237     LONG                ref;
1238     /* IDsDriverImpl fields */
1239     UINT                wDevID;
1240     IDsDriverBufferImpl*primary;
1241 };
1242
1243 struct IDsDriverBufferImpl
1244 {
1245     /* IUnknown fields */
1246     const IDsDriverBufferVtbl *lpVtbl;
1247     LONG                ref;
1248     /* IDsDriverBufferImpl fields */
1249     IDsDriverImpl*      drv;
1250     DWORD               buflen;
1251 };
1252
1253 static HRESULT DSDB_MapPrimary(IDsDriverBufferImpl *dsdb)
1254 {
1255     WINE_WAVEOUT *wwo = &(WOutDev[dsdb->drv->wDevID]);
1256     if (!wwo->mapping) {
1257         wwo->mapping = mmap(NULL, wwo->maplen, PROT_WRITE, MAP_SHARED,
1258                             wwo->unixdev, 0);
1259         if (wwo->mapping == (LPBYTE)-1) {
1260             ERR("(%p): Could not map sound device for direct access (errno=%d)\n", dsdb, errno);
1261             return DSERR_GENERIC;
1262         }
1263         TRACE("(%p): sound device has been mapped for direct access at %p, size=%d\n", dsdb, wwo->mapping, wwo->maplen);
1264
1265         /* for some reason, es1371 and sblive! sometimes have junk in here. */
1266         memset(wwo->mapping,0,wwo->maplen); /* clear it, or we get junk noise */
1267     }
1268     return DS_OK;
1269 }
1270
1271 static HRESULT DSDB_UnmapPrimary(IDsDriverBufferImpl *dsdb)
1272 {
1273     WINE_WAVEOUT *wwo = &(WOutDev[dsdb->drv->wDevID]);
1274     if (wwo->mapping) {
1275         if (munmap(wwo->mapping, wwo->maplen) < 0) {
1276             ERR("(%p): Could not unmap sound device (errno=%d)\n", dsdb, errno);
1277             return DSERR_GENERIC;
1278         }
1279         wwo->mapping = NULL;
1280         TRACE("(%p): sound device unmapped\n", dsdb);
1281     }
1282     return DS_OK;
1283 }
1284
1285 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
1286 {
1287     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
1288     FIXME("(): stub!\n");
1289     return DSERR_UNSUPPORTED;
1290 }
1291
1292 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
1293 {
1294     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
1295     return InterlockedIncrement(&This->ref);
1296 }
1297
1298 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
1299 {
1300     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
1301     ULONG refCount = InterlockedDecrement(&This->ref);
1302
1303     if (refCount)
1304         return refCount;
1305     if (This == This->drv->primary)
1306         This->drv->primary = NULL;
1307     DSDB_UnmapPrimary(This);
1308     HeapFree(GetProcessHeap(),0,This);
1309     return 0;
1310 }
1311
1312 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
1313                                                LPVOID*ppvAudio1,LPDWORD pdwLen1,
1314                                                LPVOID*ppvAudio2,LPDWORD pdwLen2,
1315                                                DWORD dwWritePosition,DWORD dwWriteLen,
1316                                                DWORD dwFlags)
1317 {
1318     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
1319     /* since we (GetDriverDesc flags) have specified DSDDESC_DONTNEEDPRIMARYLOCK,
1320      * and that we don't support secondary buffers, this method will never be called */
1321     TRACE("(%p): stub\n",iface);
1322     return DSERR_UNSUPPORTED;
1323 }
1324
1325 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
1326                                                  LPVOID pvAudio1,DWORD dwLen1,
1327                                                  LPVOID pvAudio2,DWORD dwLen2)
1328 {
1329     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
1330     TRACE("(%p): stub\n",iface);
1331     return DSERR_UNSUPPORTED;
1332 }
1333
1334 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
1335                                                     LPWAVEFORMATEX pwfx)
1336 {
1337     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
1338
1339     TRACE("(%p,%p)\n",iface,pwfx);
1340     /* On our request (GetDriverDesc flags), DirectSound has by now used
1341      * waveOutClose/waveOutOpen to set the format...
1342      * unfortunately, this means our mmap() is now gone...
1343      * so we need to somehow signal to our DirectSound implementation
1344      * that it should completely recreate this HW buffer...
1345      * this unexpected error code should do the trick... */
1346     return DSERR_BUFFERLOST;
1347 }
1348
1349 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
1350 {
1351     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
1352     TRACE("(%p,%d): stub\n",iface,dwFreq);
1353     return DSERR_UNSUPPORTED;
1354 }
1355
1356 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
1357 {
1358     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
1359     FIXME("(%p,%p): stub!\n",iface,pVolPan);
1360     return DS_OK;
1361 }
1362
1363 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
1364 {
1365     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
1366     TRACE("(%p,%d): stub\n",iface,dwNewPos);
1367     return DSERR_UNSUPPORTED;
1368 }
1369
1370 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
1371                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
1372 {
1373     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
1374 #if 0
1375     count_info info;
1376 #endif
1377
1378     TRACE("(%p)\n",iface);
1379     if (WOutDev[This->drv->wDevID].unixdev == -1) {
1380         ERR("device not open, but accessing?\n");
1381         return DSERR_UNINITIALIZED;
1382     }
1383     /*Libaudioio doesn't support this (Yet anyway)*/
1384      return DSERR_UNSUPPORTED;
1385
1386 }
1387
1388 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
1389 {
1390 #if 0
1391     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
1392     int enable = PCM_ENABLE_OUTPUT;
1393     TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
1394     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1395         ERR("ioctl failed (%d)\n", errno);
1396         return DSERR_GENERIC;
1397     }
1398 #endif
1399     return DS_OK;
1400 }
1401
1402 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
1403 {
1404 #if 0
1405     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
1406     int enable = 0;
1407     TRACE("(%p)\n",iface);
1408     /* no more playing */
1409     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1410         ERR("ioctl failed (%d)\n", errno);
1411         return DSERR_GENERIC;
1412     }
1413 #endif
1414 #if 0
1415     /* the play position must be reset to the beginning of the buffer */
1416     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_RESET, 0) < 0) {
1417         ERR("ioctl failed (%d)\n", errno);
1418         return DSERR_GENERIC;
1419     }
1420 #endif
1421     /* Most OSS drivers just can't stop the playback without closing the device...
1422      * so we need to somehow signal to our DirectSound implementation
1423      * that it should completely recreate this HW buffer...
1424      * this unexpected error code should do the trick... */
1425     return DSERR_BUFFERLOST;
1426 }
1427
1428 static const IDsDriverBufferVtbl dsdbvt =
1429 {
1430     IDsDriverBufferImpl_QueryInterface,
1431     IDsDriverBufferImpl_AddRef,
1432     IDsDriverBufferImpl_Release,
1433     IDsDriverBufferImpl_Lock,
1434     IDsDriverBufferImpl_Unlock,
1435     IDsDriverBufferImpl_SetFormat,
1436     IDsDriverBufferImpl_SetFrequency,
1437     IDsDriverBufferImpl_SetVolumePan,
1438     IDsDriverBufferImpl_SetPosition,
1439     IDsDriverBufferImpl_GetPosition,
1440     IDsDriverBufferImpl_Play,
1441     IDsDriverBufferImpl_Stop
1442 };
1443
1444 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
1445 {
1446     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
1447     FIXME("(%p): stub!\n",iface);
1448     return DSERR_UNSUPPORTED;
1449 }
1450
1451 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
1452 {
1453     IDsDriverImpl *This = (IDsDriverImpl *)iface;
1454     return InterlockedIncrement(&This->ref);
1455 }
1456
1457 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
1458 {
1459     IDsDriverImpl *This = (IDsDriverImpl *)iface;
1460     ULONG refCount = InterlockedDecrement(&This->ref);
1461
1462     if (refCount)
1463         return refCount;
1464     HeapFree(GetProcessHeap(),0,This);
1465     return 0;
1466 }
1467
1468 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
1469 {
1470     IDsDriverImpl *This = (IDsDriverImpl *)iface;
1471     TRACE("(%p,%p)\n",iface,pDesc);
1472     pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
1473         DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK;
1474     strcpy(pDesc->szDesc,"Wine AudioIO DirectSound Driver");
1475     strcpy(pDesc->szDrvname,"wineaudioio.drv");
1476     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
1477     pDesc->wVxdId               = 0;
1478     pDesc->wReserved            = 0;
1479     pDesc->ulDeviceNum          = This->wDevID;
1480     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
1481     pDesc->pvDirectDrawHeap     = NULL;
1482     pDesc->dwMemStartAddress    = 0;
1483     pDesc->dwMemEndAddress      = 0;
1484     pDesc->dwMemAllocExtra      = 0;
1485     pDesc->pvReserved1          = NULL;
1486     pDesc->pvReserved2          = NULL;
1487     return DS_OK;
1488 }
1489
1490 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
1491 {
1492 #if 0
1493     IDsDriverImpl *This = (IDsDriverImpl *)iface;
1494     int enable = 0;
1495
1496     TRACE("(%p)\n",iface);
1497     /* make sure the card doesn't start playing before we want it to */
1498     if (ioctl(WOutDev[This->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1499         ERR("ioctl failed (%d)\n", errno);
1500         return DSERR_GENERIC;
1501     }
1502 #endif
1503     return DS_OK;
1504 }
1505
1506 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
1507 {
1508     IDsDriverImpl *This = (IDsDriverImpl *)iface;
1509     TRACE("(%p)\n",iface);
1510     if (This->primary) {
1511         ERR("problem with DirectSound: primary not released\n");
1512         return DSERR_GENERIC;
1513     }
1514     return DS_OK;
1515 }
1516
1517 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
1518 {
1519     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
1520     TRACE("(%p,%p)\n",iface,pCaps);
1521     memset(pCaps, 0, sizeof(*pCaps));
1522     /* FIXME: need to check actual capabilities */
1523     pCaps->dwFlags = DSCAPS_PRIMARYMONO | DSCAPS_PRIMARYSTEREO |
1524         DSCAPS_PRIMARY8BIT | DSCAPS_PRIMARY16BIT;
1525     pCaps->dwPrimaryBuffers = 1;
1526     pCaps->dwMinSecondarySampleRate = DSBFREQUENCY_MIN;
1527     pCaps->dwMaxSecondarySampleRate = DSBFREQUENCY_MAX;
1528     /* the other fields only apply to secondary buffers, which we don't support
1529      * (unless we want to mess with wavetable synthesizers and MIDI) */
1530     return DS_OK;
1531 }
1532
1533 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
1534                                                       LPWAVEFORMATEX pwfx,
1535                                                       DWORD dwFlags, DWORD dwCardAddress,
1536                                                       LPDWORD pdwcbBufferSize,
1537                                                       LPBYTE *ppbBuffer,
1538                                                       LPVOID *ppvObj)
1539 {
1540     IDsDriverImpl *This = (IDsDriverImpl *)iface;
1541     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
1542     HRESULT err;
1543 #if 0
1544     audio_buf_info info;
1545     int enable = 0;
1546 #endif
1547
1548     TRACE("(%p,%p,%x,%x)\n",iface,pwfx,dwFlags,dwCardAddress);
1549     /* we only support primary buffers */
1550     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
1551         return DSERR_UNSUPPORTED;
1552     if (This->primary)
1553         return DSERR_ALLOCATED;
1554     if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
1555         return DSERR_CONTROLUNAVAIL;
1556
1557     *ippdsdb = HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
1558     if (*ippdsdb == NULL)
1559         return DSERR_OUTOFMEMORY;
1560     (*ippdsdb)->lpVtbl  = &dsdbvt;
1561     (*ippdsdb)->ref     = 1;
1562     (*ippdsdb)->drv     = This;
1563
1564     /* check how big the DMA buffer is now */
1565 #if 0
1566     if (ioctl(WOutDev[This->wDevID].unixdev, SNDCTL_DSP_GETOSPACE, &info) < 0) {
1567         ERR("ioctl failed (%d)\n", errno);
1568         HeapFree(GetProcessHeap(),0,*ippdsdb);
1569         *ippdsdb = NULL;
1570         return DSERR_GENERIC;
1571     }
1572 #endif
1573     WOutDev[This->wDevID].maplen =64*1024; /* Map 64 K at a time */
1574
1575 #if 0
1576     (*ippdsdb)->buflen = info.fragstotal * info.fragsize;
1577 #endif
1578     /* map the DMA buffer */
1579     err = DSDB_MapPrimary(*ippdsdb);
1580     if (err != DS_OK) {
1581         HeapFree(GetProcessHeap(),0,*ippdsdb);
1582         *ippdsdb = NULL;
1583         return err;
1584     }
1585
1586     /* primary buffer is ready to go */
1587     *pdwcbBufferSize    = WOutDev[This->wDevID].maplen;
1588     *ppbBuffer          = WOutDev[This->wDevID].mapping;
1589
1590     /* some drivers need some extra nudging after mapping */
1591 #if 0
1592     if (ioctl(WOutDev[This->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1593         ERR("ioctl failed (%d)\n", errno);
1594         return DSERR_GENERIC;
1595     }
1596 #endif
1597
1598     This->primary = *ippdsdb;
1599
1600     return DS_OK;
1601 }
1602
1603 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
1604                                                          PIDSDRIVERBUFFER pBuffer,
1605                                                          LPVOID *ppvObj)
1606 {
1607     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
1608     TRACE("(%p,%p): stub\n",iface,pBuffer);
1609     return DSERR_INVALIDCALL;
1610 }
1611
1612 static const IDsDriverVtbl dsdvt =
1613 {
1614     IDsDriverImpl_QueryInterface,
1615     IDsDriverImpl_AddRef,
1616     IDsDriverImpl_Release,
1617     IDsDriverImpl_GetDriverDesc,
1618     IDsDriverImpl_Open,
1619     IDsDriverImpl_Close,
1620     IDsDriverImpl_GetCaps,
1621     IDsDriverImpl_CreateSoundBuffer,
1622     IDsDriverImpl_DuplicateSoundBuffer
1623 };
1624
1625 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1626 {
1627     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
1628
1629     /* the HAL isn't much better than the HEL if we can't do mmap() */
1630     if (!(WOutDev[wDevID].caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
1631         ERR("DirectSound flag not set\n");
1632         MESSAGE("This sound card's driver does not support direct access\n");
1633         MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
1634         return MMSYSERR_NOTSUPPORTED;
1635     }
1636
1637     *idrv = HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
1638     if (!*idrv)
1639         return MMSYSERR_NOMEM;
1640     (*idrv)->lpVtbl     = &dsdvt;
1641     (*idrv)->ref        = 1;
1642
1643     (*idrv)->wDevID     = wDevID;
1644     (*idrv)->primary    = NULL;
1645     return MMSYSERR_NOERROR;
1646 }
1647
1648 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1649 {
1650     memset(desc, 0, sizeof(*desc));
1651     strcpy(desc->szDesc, "Wine LIBAUDIOIO DirectSound Driver");
1652     strcpy(desc->szDrvname, "wineaudioio.drv");
1653     return MMSYSERR_NOERROR;
1654 }
1655
1656 /*======================================================================*
1657  *                  Low level WAVE IN implementation                    *
1658  *======================================================================*/
1659
1660 /**************************************************************************
1661  *                      widGetDevCaps                           [internal]
1662  */
1663 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1664 {
1665     TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1666
1667     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1668
1669     if (wDevID >= MAX_WAVEINDRV) {
1670         TRACE("MAX_WAVINDRV reached !\n");
1671         return MMSYSERR_BADDEVICEID;
1672     }
1673
1674     memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1675     return MMSYSERR_NOERROR;
1676 }
1677
1678 /**************************************************************************
1679  *                              widRecorder                     [internal]
1680  */
1681 static  DWORD   CALLBACK        widRecorder(LPVOID pmt)
1682 {
1683     WORD                uDevID = (DWORD)pmt;
1684     WINE_WAVEIN*        wwi = (WINE_WAVEIN*)&WInDev[uDevID];
1685     WAVEHDR*            lpWaveHdr;
1686     DWORD               dwSleepTime;
1687     MSG                 msg;
1688     DWORD               bytesRead;
1689
1690
1691         int fragments;
1692         int fragsize;
1693         int fragstotal;
1694         int bytes;
1695
1696         LPVOID          buffer = HeapAlloc(GetProcessHeap(),
1697                                            HEAP_ZERO_MEMORY,
1698                                        wwi->dwFragmentSize);
1699
1700     BYTE *pOffset = buffer;
1701
1702     PeekMessageA(&msg, 0, 0, 0, 0);
1703     wwi->state = WINE_WS_STOPPED;
1704     wwi->dwTotalRecorded = 0;
1705
1706     SetEvent(wwi->hEvent);
1707
1708
1709         /* make sleep time to be # of ms to output a fragment */
1710     dwSleepTime = (wwi->dwFragmentSize * 1000) / wwi->format.wf.nAvgBytesPerSec;
1711     TRACE("sleeptime=%d ms\n", dwSleepTime);
1712
1713     for (; ; ) {
1714         /* wait for dwSleepTime or an event in thread's queue */
1715         /* FIXME: could improve wait time depending on queue state,
1716          * ie, number of queued fragments
1717          */
1718
1719         if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
1720         {
1721             lpWaveHdr = wwi->lpQueuePtr;
1722
1723             bytes=fragsize=AudioIORecordingAvailable();
1724             fragments=fragstotal=1;
1725
1726             TRACE("info={frag=%d fsize=%d ftotal=%d bytes=%d}\n", fragments, fragsize, fragstotal, bytes);
1727
1728
1729             /* read all the fragments accumulated so far */
1730             while ((fragments > 0) && (wwi->lpQueuePtr))
1731             {
1732                 fragments --;
1733
1734                 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwFragmentSize)
1735                 {
1736                     /* directly read fragment in wavehdr */
1737                     bytesRead = AudioIORead(
1738                                      lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
1739                                      wwi->dwFragmentSize);
1740
1741                     TRACE("bytesRead=%d (direct)\n", bytesRead);
1742                     if (bytesRead != (DWORD) -1)
1743                     {
1744                         /* update number of bytes recorded in current buffer and by this device */
1745                         lpWaveHdr->dwBytesRecorded += bytesRead;
1746                         wwi->dwTotalRecorded       += bytesRead;
1747
1748                         /* buffer is full. notify client */
1749                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
1750                         {
1751                             /* must copy the value of next waveHdr, because we have no idea of what
1752                              * will be done with the content of lpWaveHdr in callback
1753                              */
1754                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
1755
1756                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1757                             lpWaveHdr->dwFlags |=  WHDR_DONE;
1758
1759                             if (LIBAUDIOIO_NotifyClient(uDevID, WIM_DATA,
1760                                                  (DWORD)lpWaveHdr, 0) != MMSYSERR_NOERROR)
1761                             {
1762                                 WARN("can't notify client !\n");
1763                             }
1764                             lpWaveHdr = wwi->lpQueuePtr = lpNext;
1765                         }
1766                     }
1767                 }
1768                 else
1769                 {
1770                     /* read the fragment in a local buffer */
1771                     bytesRead = AudioIORead( buffer, wwi->dwFragmentSize);
1772                     pOffset = buffer;
1773
1774                     TRACE("bytesRead=%d (local)\n", bytesRead);
1775
1776                     /* copy data in client buffers */
1777                     while (bytesRead != (DWORD) -1 && bytesRead > 0)
1778                     {
1779                         DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
1780
1781                         memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
1782                                pOffset,
1783                                dwToCopy);
1784
1785                         /* update number of bytes recorded in current buffer and by this device */
1786                         lpWaveHdr->dwBytesRecorded += dwToCopy;
1787                         wwi->dwTotalRecorded += dwToCopy;
1788                         bytesRead -= dwToCopy;
1789                         pOffset   += dwToCopy;
1790
1791                         /* client buffer is full. notify client */
1792                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
1793                         {
1794                             /* must copy the value of next waveHdr, because we have no idea of what
1795                              * will be done with the content of lpWaveHdr in callback
1796                              */
1797                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
1798                             TRACE("lpNext=%p\n", lpNext);
1799
1800                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1801                             lpWaveHdr->dwFlags |=  WHDR_DONE;
1802
1803                             if (LIBAUDIOIO_NotifyClient(uDevID, WIM_DATA,
1804                                                  (DWORD)lpWaveHdr, 0) != MMSYSERR_NOERROR)
1805                             {
1806                                 WARN("can't notify client !\n");
1807                             }
1808
1809                             wwi->lpQueuePtr = lpWaveHdr = lpNext;
1810                             if (!lpNext && bytesRead) {
1811                                 /* no more buffer to copy data to, but we did read more.
1812                                  * what hasn't been copied will be dropped
1813                                  */
1814                                 WARN("buffer under run! %u bytes dropped.\n", bytesRead);
1815                                 wwi->lpQueuePtr = NULL;
1816                                 break;
1817                             }
1818                         }
1819                     }
1820                 }
1821             }
1822         }
1823
1824         MsgWaitForMultipleObjects(0, NULL, FALSE, dwSleepTime, QS_POSTMESSAGE);
1825
1826         while (PeekMessageA(&msg, 0, WINE_WM_FIRST, WINE_WM_LAST, PM_REMOVE)) {
1827
1828             TRACE("msg=0x%x wParam=0x%x lParam=0x%lx\n", msg.message, msg.wParam, msg.lParam);
1829             switch (msg.message) {
1830             case WINE_WM_PAUSING:
1831                 wwi->state = WINE_WS_PAUSED;
1832
1833                 AudioIORecordingPause();
1834                 SetEvent(wwi->hEvent);
1835                 break;
1836             case WINE_WM_RESTARTING:
1837             {
1838
1839                 wwi->state = WINE_WS_PLAYING;
1840
1841                 if (wwi->bTriggerSupport)
1842                 {
1843                     /* start the recording */
1844                     AudioIORecordingResume();
1845                 }
1846                 else
1847                 {
1848                     unsigned char data[4];
1849                     /* read 4 bytes to start the recording */
1850                     AudioIORead( data, 4);
1851                 }
1852
1853                 SetEvent(wwi->hEvent);
1854                 break;
1855             }
1856             case WINE_WM_HEADER:
1857                 lpWaveHdr = (LPWAVEHDR)msg.lParam;
1858                 lpWaveHdr->lpNext = 0;
1859
1860                 /* insert buffer at the end of queue */
1861                 {
1862                     LPWAVEHDR*  wh;
1863                     for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1864                     *wh = lpWaveHdr;
1865                 }
1866                 break;
1867             case WINE_WM_RESETTING:
1868                 wwi->state = WINE_WS_STOPPED;
1869                 /* return all buffers to the app */
1870                 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
1871                     TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
1872                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1873                     lpWaveHdr->dwFlags |= WHDR_DONE;
1874
1875                     if (LIBAUDIOIO_NotifyClient(uDevID, WIM_DATA,
1876                                          (DWORD)lpWaveHdr, 0) != MMSYSERR_NOERROR) {
1877                         WARN("can't notify client !\n");
1878                     }
1879                 }
1880                 wwi->lpQueuePtr = NULL;
1881                 SetEvent(wwi->hEvent);
1882                 break;
1883             case WINE_WM_CLOSING:
1884                 wwi->hThread = 0;
1885                 wwi->state = WINE_WS_CLOSED;
1886                 SetEvent(wwi->hEvent);
1887                 HeapFree(GetProcessHeap(), 0, buffer);
1888                 ExitThread(0);
1889                 /* shouldn't go here */
1890             default:
1891                 FIXME("unknown message %d\n", msg.message);
1892                 break;
1893             }
1894         }
1895   }
1896     ExitThread(0);
1897     /* just for not generating compilation warnings... should never be executed */
1898     return 0;
1899 }
1900
1901
1902 /**************************************************************************
1903  *                              widOpen                         [internal]
1904  */
1905 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1906 {
1907     int                 audio;
1908     int                 fragment_size;
1909     int                 sample_rate;
1910     int                 format;
1911     int                 dsp_stereo;
1912     WINE_WAVEIN*        wwi;
1913     int                 audio_fragment;
1914
1915     TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1916     if (lpDesc == NULL) {
1917         WARN("Invalid Parameter !\n");
1918         return MMSYSERR_INVALPARAM;
1919     }
1920     if (wDevID >= MAX_WAVEINDRV) return MMSYSERR_BADDEVICEID;
1921
1922     /* only PCM format is supported so far... */
1923     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1924         lpDesc->lpFormat->nChannels == 0 ||
1925         lpDesc->lpFormat->nSamplesPerSec == 0 ||
1926         (lpDesc->lpFormat->wBitsPerSample!=8 && lpDesc->lpFormat->wBitsPerSample!=16)) {
1927         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1928              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1929              lpDesc->lpFormat->nSamplesPerSec);
1930         return WAVERR_BADFORMAT;
1931     }
1932
1933     if (dwFlags & WAVE_FORMAT_QUERY) {
1934         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1935              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1936              lpDesc->lpFormat->nSamplesPerSec);
1937         return MMSYSERR_NOERROR;
1938     }
1939
1940     if (access(SOUND_DEV,0) != 0) return MMSYSERR_NOTENABLED;
1941     audio = AudioIOOpenX( O_RDONLY|O_NDELAY, &spec[CLIENT_RECORD],&spec[CLIENT_RECORD]);
1942     if (audio == -1) {
1943         WARN("can't open sound device %s (%s)!\n", SOUND_DEV, strerror(errno));
1944         return MMSYSERR_ALLOCATED;
1945     }
1946     fcntl(audio, F_SETFD, 1); /* set close on exec flag */
1947
1948     wwi = &WInDev[wDevID];
1949     if (wwi->lpQueuePtr) {
1950         WARN("Should have an empty queue (%p)\n", wwi->lpQueuePtr);
1951         wwi->lpQueuePtr = NULL;
1952     }
1953     wwi->unixdev = audio;
1954     wwi->dwTotalRecorded = 0;
1955     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1956
1957     memcpy(&wwi->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
1958     memcpy(&wwi->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1959
1960     if (wwi->format.wBitsPerSample == 0) {
1961         WARN("Resetting zeroed wBitsPerSample\n");
1962         wwi->format.wBitsPerSample = 8 *
1963             (wwi->format.wf.nAvgBytesPerSec /
1964              wwi->format.wf.nSamplesPerSec) /
1965             wwi->format.wf.nChannels;
1966     }
1967
1968     spec[CLIENT_RECORD].rate=sample_rate = wwi->format.wf.nSamplesPerSec;
1969     dsp_stereo = ((spec[CLIENT_RECORD].channels=wwi->format.wf.nChannels) > 1) ? TRUE : FALSE;
1970     spec[CLIENT_RECORD].precision= wwi->format.wBitsPerSample;
1971     spec[CLIENT_RECORD].type=(spec[CLIENT_RECORD].precision==16)?TYPE_SIGNED:TYPE_UNSIGNED;
1972
1973     /* This is actually hand tuned to work so that my SB Live:
1974      * - does not skip
1975      * - does not buffer too much
1976      * when sending with the Shoutcast winamp plugin
1977      */
1978     /* 7 fragments max, 2^10 = 1024 bytes per fragment */
1979     audio_fragment = 0x0007000A;
1980     fragment_size=4096;
1981     if (fragment_size == -1) {
1982         AudioIOClose();
1983         wwi->unixdev = -1;
1984         return MMSYSERR_NOTENABLED;
1985     }
1986     wwi->dwFragmentSize = fragment_size;
1987
1988     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%u, nSamplesPerSec=%u, nChannels=%u nBlockAlign=%u!\n",
1989           wwi->format.wBitsPerSample, wwi->format.wf.nAvgBytesPerSec,
1990           wwi->format.wf.nSamplesPerSec, wwi->format.wf.nChannels,
1991           wwi->format.wf.nBlockAlign);
1992
1993     wwi->hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1994     wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
1995     if (wwi->hThread)
1996         SetThreadPriority(wwi->hThread, THREAD_PRIORITY_TIME_CRITICAL);
1997     WaitForSingleObject(wwi->hEvent, INFINITE);
1998
1999    if (LIBAUDIOIO_NotifyClient(wDevID, WIM_OPEN, 0L, 0L) != MMSYSERR_NOERROR) {
2000         WARN("can't notify client !\n");
2001         return MMSYSERR_INVALPARAM;
2002     }
2003     return MMSYSERR_NOERROR;
2004 }
2005
2006 /**************************************************************************
2007  *                              widClose                        [internal]
2008  */
2009 static DWORD widClose(WORD wDevID)
2010 {
2011     WINE_WAVEIN*        wwi;
2012
2013     TRACE("(%u);\n", wDevID);
2014     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2015         WARN("can't close !\n");
2016         return MMSYSERR_INVALHANDLE;
2017     }
2018
2019     wwi = &WInDev[wDevID];
2020
2021     if (wwi->lpQueuePtr != NULL) {
2022         WARN("still buffers open !\n");
2023         return WAVERR_STILLPLAYING;
2024     }
2025
2026     PostThreadMessageA(wwi->dwThreadID, WINE_WM_CLOSING, 0, 0);
2027     WaitForSingleObject(wwi->hEvent, INFINITE);
2028     CloseHandle(wwi->hEvent);
2029     AudioIOClose();
2030     wwi->unixdev = -1;
2031     wwi->dwFragmentSize = 0;
2032     if (LIBAUDIOIO_NotifyClient(wDevID, WIM_CLOSE, 0L, 0L) != MMSYSERR_NOERROR) {
2033         WARN("can't notify client !\n");
2034         return MMSYSERR_INVALPARAM;
2035     }
2036     return MMSYSERR_NOERROR;
2037 }
2038
2039 /**************************************************************************
2040  *                              widAddBuffer            [internal]
2041  */
2042 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2043 {
2044     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
2045
2046     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2047         WARN("can't do it !\n");
2048         return MMSYSERR_INVALHANDLE;
2049     }
2050     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED)) {
2051         TRACE("never been prepared !\n");
2052         return WAVERR_UNPREPARED;
2053     }
2054     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) {
2055         TRACE("header already in use !\n");
2056         return WAVERR_STILLPLAYING;
2057     }
2058
2059     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2060     lpWaveHdr->dwFlags &= ~WHDR_DONE;
2061     lpWaveHdr->dwBytesRecorded = 0;
2062         lpWaveHdr->lpNext = NULL;
2063
2064     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_HEADER, 0, (DWORD)lpWaveHdr);
2065     return MMSYSERR_NOERROR;
2066 }
2067
2068 /**************************************************************************
2069  *                      widStart                                [internal]
2070  */
2071 static DWORD widStart(WORD wDevID)
2072 {
2073     TRACE("(%u);\n", wDevID);
2074     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2075         WARN("can't start recording !\n");
2076         return MMSYSERR_INVALHANDLE;
2077     }
2078
2079     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_RESTARTING, 0, 0);
2080     WaitForSingleObject(WInDev[wDevID].hEvent, INFINITE);
2081     return MMSYSERR_NOERROR;
2082 }
2083
2084 /**************************************************************************
2085  *                      widStop                                 [internal]
2086  */
2087 static DWORD widStop(WORD wDevID)
2088 {
2089     TRACE("(%u);\n", wDevID);
2090     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2091         WARN("can't stop !\n");
2092         return MMSYSERR_INVALHANDLE;
2093     }
2094     /* FIXME: reset aint stop */
2095     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_RESETTING, 0, 0);
2096     WaitForSingleObject(WInDev[wDevID].hEvent, INFINITE);
2097
2098     return MMSYSERR_NOERROR;
2099 }
2100
2101 /**************************************************************************
2102  *                      widReset                                [internal]
2103  */
2104 static DWORD widReset(WORD wDevID)
2105 {
2106     TRACE("(%u);\n", wDevID);
2107     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2108         WARN("can't reset !\n");
2109         return MMSYSERR_INVALHANDLE;
2110     }
2111     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_RESETTING, 0, 0);
2112     WaitForSingleObject(WInDev[wDevID].hEvent, INFINITE);
2113     return MMSYSERR_NOERROR;
2114 }
2115
2116 /**************************************************************************
2117  *                              widGetPosition                  [internal]
2118  */
2119 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
2120 {
2121     WINE_WAVEIN*        wwi;
2122
2123     TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
2124
2125     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2126         WARN("can't get pos !\n");
2127         return MMSYSERR_INVALHANDLE;
2128     }
2129     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
2130
2131     wwi = &WInDev[wDevID];
2132
2133     return bytes_to_mmtime(lpTime, wwi->dwTotalRecorded, &wwi->format);
2134 }
2135
2136 /**************************************************************************
2137  *                              widMessage (WINEAUDIOIO.@)
2138  */
2139 DWORD WINAPI LIBAUDIOIO_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2140                             DWORD dwParam1, DWORD dwParam2)
2141 {
2142     TRACE("(%u, %04X, %08X, %08X, %08X);\n",
2143           wDevID, wMsg, dwUser, dwParam1, dwParam2);
2144
2145     switch (wMsg) {
2146     case DRVM_INIT:
2147     case DRVM_EXIT:
2148     case DRVM_ENABLE:
2149     case DRVM_DISABLE:
2150         /* FIXME: Pretend this is supported */
2151         return 0;
2152     case WIDM_OPEN:             return widOpen       (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2153     case WIDM_CLOSE:            return widClose      (wDevID);
2154     case WIDM_ADDBUFFER:        return widAddBuffer  (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2155     case WIDM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
2156     case WIDM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
2157     case WIDM_GETDEVCAPS:       return widGetDevCaps (wDevID, (LPWAVEINCAPSW)dwParam1, dwParam2);
2158     case WIDM_GETNUMDEVS:       return wodGetNumDevs ();        /* same number of devices in output as in input */
2159     case WIDM_GETPOS:           return widGetPosition(wDevID, (LPMMTIME)dwParam1, dwParam2);
2160     case WIDM_RESET:            return widReset      (wDevID);
2161     case WIDM_START:            return widStart      (wDevID);
2162     case WIDM_STOP:             return widStop       (wDevID);
2163     case DRV_QUERYDSOUNDIFACE:  return widDsCreate   (wDevID, (PIDSCDRIVER*)dwParam1);
2164     case DRV_QUERYDSOUNDDESC:   return widDsDesc     (wDevID, (PDSDRIVERDESC)dwParam1);
2165     default:
2166         FIXME("unknown message %u!\n", wMsg);
2167     }
2168     return MMSYSERR_NOTSUPPORTED;
2169 }
2170
2171 /*======================================================================*
2172  *                  Low level DSOUND capture implementation             *
2173  *======================================================================*/
2174 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
2175 {
2176     /* we can't perform memory mapping as we don't have a file stream
2177         interface with arts like we do with oss */
2178     MESSAGE("This sound card's driver does not support direct access\n");
2179     MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
2180     return MMSYSERR_NOTSUPPORTED;
2181 }
2182
2183 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2184 {
2185     memset(desc, 0, sizeof(*desc));
2186     strcpy(desc->szDesc, "Wine LIBAUDIOIO DirectSound Driver");
2187     strcpy(desc->szDrvname, "wineaudioio.drv");
2188     return MMSYSERR_NOERROR;
2189 }
2190
2191 #else /* HAVE_LIBAUDIOIO */
2192
2193 /**************************************************************************
2194  *                              wodMessage (WINEAUDIOIO.@)
2195  */
2196 DWORD WINAPI LIBAUDIOIO_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2197                             DWORD dwParam1, DWORD dwParam2)
2198 {
2199     FIXME("(%u, %04X, %08X, %08X, %08X):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2200     return MMSYSERR_NOTENABLED;
2201 }
2202
2203 /**************************************************************************
2204  *                              widMessage (WINEAUDIOIO.@)
2205  */
2206 DWORD WINAPI LIBAUDIOIO_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2207                             DWORD dwParam1, DWORD dwParam2)
2208 {
2209     FIXME("(%u, %04X, %08X, %08X, %08X):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2210     return MMSYSERR_NOTENABLED;
2211 }
2212
2213 #endif /* HAVE_LIBAUDIOIO */