oledlg: Call the hook proc if present.
[wine] / dlls / winmm / wineaudioio / 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=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
188           lpTime->wType, format->wBitsPerSample, format->wf.nSamplesPerSec,
189           format->wf.nChannels, format->wf.nAvgBytesPerSec);
190     TRACE("Position in bytes=%lu\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=%lu\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=%lu\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=%lu\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 = %08lX, dwSupport = %08lX\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 = %08lX\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 = %04lX dwParam2 = %04lX\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 %ld 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 (%ldx) 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[%5lu], %5lu) => %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 %08lx\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[%5lu], %5lu) => %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 %08lx\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 = %08lx\n", GetTickCount());
690         if (dwSleepTime)
691             WaitForSingleObject(wwo->msg_event, dwSleepTime);
692         TRACE("imhere[2] (q=%p p=%p) tc = %08lx\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, %lu);\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, %08lX);\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=%ld !\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=%ld !\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
905     if (!(dwFlags & WAVE_DIRECTSOUND)) {
906         TRACE("Starting wodPlayer Thread\n");
907         wwo->hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
908         wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
909         if (wwo->hThread)
910             SetThreadPriority(wwo->hThread, THREAD_PRIORITY_TIME_CRITICAL);
911         WaitForSingleObject(wwo->hEvent, INFINITE);
912     } else {
913         wwo->hEvent = INVALID_HANDLE_VALUE;
914         wwo->hThread = INVALID_HANDLE_VALUE;
915         wwo->dwThreadID = 0;
916     }
917
918     TRACE("fd=%d fragmentSize=%ld\n",
919           wwo->unixdev, wwo->dwFragmentSize);
920     if (wwo->dwFragmentSize % wwo->format.wf.nBlockAlign)
921         ERR("Fragment doesn't contain an integral number of data blocks\n");
922
923     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
924           wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec,
925           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
926           wwo->format.wf.nBlockAlign);
927
928     if (LIBAUDIOIO_NotifyClient(wDevID, WOM_OPEN, 0L, 0L) != MMSYSERR_NOERROR) {
929         WARN("can't notify client !\n");
930         return MMSYSERR_INVALPARAM;
931     }
932     return MMSYSERR_NOERROR;
933 }
934
935 /**************************************************************************
936  *                              wodClose                        [internal]
937  */
938 static DWORD wodClose(WORD wDevID)
939 {
940     DWORD               ret = MMSYSERR_NOERROR;
941     WINE_WAVEOUT*       wwo;
942
943     TRACE("(%u);\n", wDevID);
944
945     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
946         WARN("bad device ID !\n");
947         return MMSYSERR_BADDEVICEID;
948     }
949
950     wwo = &WOutDev[wDevID];
951     if (wwo->lpQueuePtr) {
952         WARN("buffers still playing !\n");
953         ret = WAVERR_STILLPLAYING;
954     } else {
955         TRACE("imhere[3-close]\n");
956         if (wwo->hEvent != INVALID_HANDLE_VALUE) {
957             wodPlayer_Message(wwo, WINE_WM_CLOSING, 0);
958             WaitForSingleObject(wwo->hEvent, INFINITE);
959             CloseHandle(wwo->hEvent);
960         }
961         if (wwo->mapping) {
962             munmap(wwo->mapping, wwo->maplen);
963             wwo->mapping = NULL;
964         }
965
966         AudioIOClose();
967         wwo->unixdev = -1;
968         wwo->dwFragmentSize = 0;
969         if (LIBAUDIOIO_NotifyClient(wDevID, WOM_CLOSE, 0L, 0L) != MMSYSERR_NOERROR) {
970             WARN("can't notify client !\n");
971             ret = MMSYSERR_INVALPARAM;
972         }
973     }
974     return ret;
975 }
976
977 /**************************************************************************
978  *                              wodWrite                        [internal]
979  *
980  */
981 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
982 {
983     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
984
985     /* first, do the sanity checks... */
986     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
987         WARN("bad dev ID !\n");
988         return MMSYSERR_BADDEVICEID;
989     }
990
991     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
992         return WAVERR_UNPREPARED;
993
994     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
995         return WAVERR_STILLPLAYING;
996
997     lpWaveHdr->dwFlags &= ~WHDR_DONE;
998     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
999     lpWaveHdr->lpNext = 0;
1000
1001     TRACE("imhere[3-HEADER]\n");
1002     wodPlayer_Message(&WOutDev[wDevID], WINE_WM_HEADER, (DWORD)lpWaveHdr);
1003
1004     return MMSYSERR_NOERROR;
1005 }
1006
1007 /**************************************************************************
1008  *                      wodPause                                [internal]
1009  */
1010 static DWORD wodPause(WORD wDevID)
1011 {
1012     TRACE("(%u);!\n", wDevID);
1013
1014     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1015         WARN("bad device ID !\n");
1016         return MMSYSERR_BADDEVICEID;
1017     }
1018
1019     TRACE("imhere[3-PAUSING]\n");
1020     wodPlayer_Message(&WOutDev[wDevID], WINE_WM_PAUSING, 0);
1021     WaitForSingleObject(WOutDev[wDevID].hEvent, INFINITE);
1022
1023     return MMSYSERR_NOERROR;
1024 }
1025
1026 /**************************************************************************
1027  *                      wodRestart                              [internal]
1028  */
1029 static DWORD wodRestart(WORD wDevID)
1030 {
1031     TRACE("(%u);\n", wDevID);
1032
1033     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1034         WARN("bad device ID !\n");
1035         return MMSYSERR_BADDEVICEID;
1036     }
1037
1038     if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1039         TRACE("imhere[3-RESTARTING]\n");
1040         wodPlayer_Message(&WOutDev[wDevID], WINE_WM_RESTARTING, 0);
1041         WaitForSingleObject(WOutDev[wDevID].hEvent, INFINITE);
1042     }
1043
1044     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1045     /* FIXME: Myst crashes with this ... hmm -MM
1046        if (LIBAUDIOIO_NotifyClient(wDevID, WOM_DONE, 0L, 0L) != MMSYSERR_NOERROR) {
1047        WARN("can't notify client !\n");
1048        return MMSYSERR_INVALPARAM;
1049        }
1050     */
1051
1052     return MMSYSERR_NOERROR;
1053 }
1054
1055 /**************************************************************************
1056  *                      wodReset                                [internal]
1057  */
1058 static DWORD wodReset(WORD wDevID)
1059 {
1060     TRACE("(%u);\n", wDevID);
1061
1062     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1063         WARN("bad device ID !\n");
1064         return MMSYSERR_BADDEVICEID;
1065     }
1066
1067     TRACE("imhere[3-RESET]\n");
1068     wodPlayer_Message(&WOutDev[wDevID], WINE_WM_RESETTING, 0);
1069     WaitForSingleObject(WOutDev[wDevID].hEvent, INFINITE);
1070
1071     return MMSYSERR_NOERROR;
1072 }
1073
1074
1075 /**************************************************************************
1076  *                              wodGetPosition                  [internal]
1077  */
1078 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1079 {
1080     WINE_WAVEOUT*       wwo;
1081
1082     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1083
1084     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1085         WARN("bad device ID !\n");
1086         return MMSYSERR_BADDEVICEID;
1087     }
1088
1089     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1090
1091     wwo = &WOutDev[wDevID];
1092
1093     return bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->format);
1094 }
1095
1096 /**************************************************************************
1097  *                              wodGetVolume                    [internal]
1098  */
1099 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1100 {
1101     int         mixer;
1102     int         vol,bal;
1103     DWORD       left, right;
1104
1105     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1106
1107     if (lpdwVol == NULL)
1108         return MMSYSERR_NOTENABLED;
1109
1110      vol=AudioIOGetPlaybackVolume();
1111      bal=AudioIOGetPlaybackBalance();
1112
1113
1114      if(bal<0) {
1115         left = vol;
1116         right=-(vol*(-100+bal)/100);
1117      }
1118       else
1119      {
1120         right = vol;
1121         left=(vol*(100-bal)/100);
1122      }
1123
1124     *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) << 16);
1125     return MMSYSERR_NOERROR;
1126 }
1127
1128
1129 /**************************************************************************
1130  *                              wodSetVolume                    [internal]
1131  */
1132 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1133 {
1134     int         mixer;
1135     int         volume,bal;
1136     DWORD       left, right;
1137
1138     TRACE("(%u, %08lX);\n", wDevID, dwParam);
1139
1140     left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
1141     right = (HIWORD(dwParam) * 100) / 0xFFFFl;
1142     volume = max(left , right );
1143     bal=min(left,right);
1144     bal=bal*100/volume;
1145     if(right>left) bal=-100+bal; else bal=100-bal;
1146
1147     AudioIOSetPlaybackVolume(volume);
1148     AudioIOSetPlaybackBalance(bal);
1149
1150     return MMSYSERR_NOERROR;
1151 }
1152
1153 /**************************************************************************
1154  *                              wodGetNumDevs                   [internal]
1155  */
1156 static  DWORD   wodGetNumDevs(void)
1157 {
1158     DWORD       ret = 1;
1159
1160     /* FIXME: For now, only one sound device (SOUND_DEV) is allowed */
1161     int audio = open(SOUND_DEV, O_WRONLY|O_NDELAY, 0);
1162
1163     if (audio == -1) {
1164         if (errno != EBUSY)
1165             ret = 0;
1166     } else {
1167         close(audio);
1168
1169     }
1170     TRACE("NumDrivers = %d\n",ret);
1171     return ret;
1172 }
1173
1174 /**************************************************************************
1175  *                              wodMessage (WINEAUDIOIO.@)
1176  */
1177 DWORD WINAPI LIBAUDIOIO_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1178                             DWORD dwParam1, DWORD dwParam2)
1179 {
1180     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
1181           wDevID, wMsg, dwUser, dwParam1, dwParam2);
1182
1183     switch (wMsg) {
1184     case DRVM_INIT:
1185     case DRVM_EXIT:
1186     case DRVM_ENABLE:
1187     case DRVM_DISABLE:
1188         /* FIXME: Pretend this is supported */
1189         return 0;
1190     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1191     case WODM_CLOSE:            return wodClose         (wDevID);
1192     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1193     case WODM_PAUSE:            return wodPause         (wDevID);
1194     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
1195     case WODM_BREAKLOOP:        return MMSYSERR_NOTSUPPORTED;
1196     case WODM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
1197     case WODM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
1198     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSW)dwParam1,      dwParam2);
1199     case WODM_GETNUMDEVS:       return wodGetNumDevs    ();
1200     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1201     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1202     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1203     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1204     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
1205     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
1206     case WODM_RESTART:          return wodRestart       (wDevID);
1207     case WODM_RESET:            return wodReset         (wDevID);
1208
1209     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate      (wDevID, (PIDSDRIVER*)dwParam1);
1210     case DRV_QUERYDSOUNDDESC:   return wodDsDesc        (wDevID, (PDSDRIVERDESC)dwParam1);
1211     default:
1212         FIXME("unknown message %d!\n", wMsg);
1213     }
1214     return MMSYSERR_NOTSUPPORTED;
1215 }
1216
1217 /*======================================================================*
1218  *                  Low level DSOUND implementation                     *
1219  *              While I have tampered somewhat with this code it is wholely unlikely that it works
1220  *              Elsewhere the driver returns Not Implemented for DIrectSound
1221  *              While it may be possible to map the sound device on Solaris
1222  *              Doing so would bypass the libaudioio library and therefore break any conversions
1223  *              that the libaudioio sample specification converter is doing
1224  *              **** All this is untested so far
1225  *======================================================================*/
1226
1227 typedef struct IDsDriverImpl IDsDriverImpl;
1228 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1229
1230 struct IDsDriverImpl
1231 {
1232     /* IUnknown fields */
1233     const IDsDriverVtbl *lpVtbl;
1234     DWORD               ref;
1235     /* IDsDriverImpl fields */
1236     UINT                wDevID;
1237     IDsDriverBufferImpl*primary;
1238 };
1239
1240 struct IDsDriverBufferImpl
1241 {
1242     /* IUnknown fields */
1243     const IDsDriverBufferVtbl *lpVtbl;
1244     DWORD               ref;
1245     /* IDsDriverBufferImpl fields */
1246     IDsDriverImpl*      drv;
1247     DWORD               buflen;
1248 };
1249
1250 static HRESULT DSDB_MapPrimary(IDsDriverBufferImpl *dsdb)
1251 {
1252     WINE_WAVEOUT *wwo = &(WOutDev[dsdb->drv->wDevID]);
1253     if (!wwo->mapping) {
1254         wwo->mapping = mmap(NULL, wwo->maplen, PROT_WRITE, MAP_SHARED,
1255                             wwo->unixdev, 0);
1256         if (wwo->mapping == (LPBYTE)-1) {
1257             ERR("(%p): Could not map sound device for direct access (errno=%d)\n", dsdb, errno);
1258             return DSERR_GENERIC;
1259         }
1260         TRACE("(%p): sound device has been mapped for direct access at %p, size=%ld\n", dsdb, wwo->mapping, wwo->maplen);
1261
1262         /* for some reason, es1371 and sblive! sometimes have junk in here. */
1263         memset(wwo->mapping,0,wwo->maplen); /* clear it, or we get junk noise */
1264     }
1265     return DS_OK;
1266 }
1267
1268 static HRESULT DSDB_UnmapPrimary(IDsDriverBufferImpl *dsdb)
1269 {
1270     WINE_WAVEOUT *wwo = &(WOutDev[dsdb->drv->wDevID]);
1271     if (wwo->mapping) {
1272         if (munmap(wwo->mapping, wwo->maplen) < 0) {
1273             ERR("(%p): Could not unmap sound device (errno=%d)\n", dsdb, errno);
1274             return DSERR_GENERIC;
1275         }
1276         wwo->mapping = NULL;
1277         TRACE("(%p): sound device unmapped\n", dsdb);
1278     }
1279     return DS_OK;
1280 }
1281
1282 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
1283 {
1284     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
1285     FIXME("(): stub!\n");
1286     return DSERR_UNSUPPORTED;
1287 }
1288
1289 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
1290 {
1291     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
1292     return InterlockedIncrement(&This->ref);
1293 }
1294
1295 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
1296 {
1297     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
1298     ULONG refCount = InterlockedDecrement(&This->ref);
1299
1300     if (refCount)
1301         return refCount;
1302     if (This == This->drv->primary)
1303         This->drv->primary = NULL;
1304     DSDB_UnmapPrimary(This);
1305     HeapFree(GetProcessHeap(),0,This);
1306     return 0;
1307 }
1308
1309 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
1310                                                LPVOID*ppvAudio1,LPDWORD pdwLen1,
1311                                                LPVOID*ppvAudio2,LPDWORD pdwLen2,
1312                                                DWORD dwWritePosition,DWORD dwWriteLen,
1313                                                DWORD dwFlags)
1314 {
1315     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
1316     /* since we (GetDriverDesc flags) have specified DSDDESC_DONTNEEDPRIMARYLOCK,
1317      * and that we don't support secondary buffers, this method will never be called */
1318     TRACE("(%p): stub\n",iface);
1319     return DSERR_UNSUPPORTED;
1320 }
1321
1322 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
1323                                                  LPVOID pvAudio1,DWORD dwLen1,
1324                                                  LPVOID pvAudio2,DWORD dwLen2)
1325 {
1326     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
1327     TRACE("(%p): stub\n",iface);
1328     return DSERR_UNSUPPORTED;
1329 }
1330
1331 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
1332                                                     LPWAVEFORMATEX pwfx)
1333 {
1334     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
1335
1336     TRACE("(%p,%p)\n",iface,pwfx);
1337     /* On our request (GetDriverDesc flags), DirectSound has by now used
1338      * waveOutClose/waveOutOpen to set the format...
1339      * unfortunately, this means our mmap() is now gone...
1340      * so we need to somehow signal to our DirectSound implementation
1341      * that it should completely recreate this HW buffer...
1342      * this unexpected error code should do the trick... */
1343     return DSERR_BUFFERLOST;
1344 }
1345
1346 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
1347 {
1348     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
1349     TRACE("(%p,%ld): stub\n",iface,dwFreq);
1350     return DSERR_UNSUPPORTED;
1351 }
1352
1353 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
1354 {
1355     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
1356     FIXME("(%p,%p): stub!\n",iface,pVolPan);
1357     return DS_OK;
1358 }
1359
1360 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
1361 {
1362     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
1363     TRACE("(%p,%ld): stub\n",iface,dwNewPos);
1364     return DSERR_UNSUPPORTED;
1365 }
1366
1367 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
1368                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
1369 {
1370     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
1371 #if 0
1372     count_info info;
1373 #endif
1374     DWORD ptr;
1375
1376     TRACE("(%p)\n",iface);
1377     if (WOutDev[This->drv->wDevID].unixdev == -1) {
1378         ERR("device not open, but accessing?\n");
1379         return DSERR_UNINITIALIZED;
1380     }
1381     /*Libaudioio doesn't support this (Yet anyway)*/
1382      return DSERR_UNSUPPORTED;
1383
1384 }
1385
1386 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
1387 {
1388     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
1389 #if 0
1390     int enable = PCM_ENABLE_OUTPUT;
1391     TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
1392     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1393         ERR("ioctl failed (%d)\n", errno);
1394         return DSERR_GENERIC;
1395     }
1396 #endif
1397     return DS_OK;
1398 }
1399
1400 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
1401 {
1402     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
1403     int enable = 0;
1404 #if 0
1405     TRACE("(%p)\n",iface);
1406     /* no more playing */
1407     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1408         ERR("ioctl failed (%d)\n", errno);
1409         return DSERR_GENERIC;
1410     }
1411 #endif
1412 #if 0
1413     /* the play position must be reset to the beginning of the buffer */
1414     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_RESET, 0) < 0) {
1415         ERR("ioctl failed (%d)\n", errno);
1416         return DSERR_GENERIC;
1417     }
1418 #endif
1419     /* Most OSS drivers just can't stop the playback without closing the device...
1420      * so we need to somehow signal to our DirectSound implementation
1421      * that it should completely recreate this HW buffer...
1422      * this unexpected error code should do the trick... */
1423     return DSERR_BUFFERLOST;
1424 }
1425
1426 static const IDsDriverBufferVtbl dsdbvt =
1427 {
1428     IDsDriverBufferImpl_QueryInterface,
1429     IDsDriverBufferImpl_AddRef,
1430     IDsDriverBufferImpl_Release,
1431     IDsDriverBufferImpl_Lock,
1432     IDsDriverBufferImpl_Unlock,
1433     IDsDriverBufferImpl_SetFormat,
1434     IDsDriverBufferImpl_SetFrequency,
1435     IDsDriverBufferImpl_SetVolumePan,
1436     IDsDriverBufferImpl_SetPosition,
1437     IDsDriverBufferImpl_GetPosition,
1438     IDsDriverBufferImpl_Play,
1439     IDsDriverBufferImpl_Stop
1440 };
1441
1442 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
1443 {
1444     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
1445     FIXME("(%p): stub!\n",iface);
1446     return DSERR_UNSUPPORTED;
1447 }
1448
1449 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
1450 {
1451     IDsDriverImpl *This = (IDsDriverImpl *)iface;
1452     return InterlockedIncrement(&This->ref);
1453 }
1454
1455 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
1456 {
1457     IDsDriverImpl *This = (IDsDriverImpl *)iface;
1458     ULONG refCount = InterlockedDecrement(&This->ref);
1459
1460     if (refCount)
1461         return refCount;
1462     HeapFree(GetProcessHeap(),0,This);
1463     return 0;
1464 }
1465
1466 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
1467 {
1468     IDsDriverImpl *This = (IDsDriverImpl *)iface;
1469     TRACE("(%p,%p)\n",iface,pDesc);
1470     pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
1471         DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK;
1472     strcpy(pDesc->szDesc,"Wine AudioIO DirectSound Driver");
1473     strcpy(pDesc->szDrvname,"wineaudioio.drv");
1474     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
1475     pDesc->wVxdId               = 0;
1476     pDesc->wReserved            = 0;
1477     pDesc->ulDeviceNum          = This->wDevID;
1478     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
1479     pDesc->pvDirectDrawHeap     = NULL;
1480     pDesc->dwMemStartAddress    = 0;
1481     pDesc->dwMemEndAddress      = 0;
1482     pDesc->dwMemAllocExtra      = 0;
1483     pDesc->pvReserved1          = NULL;
1484     pDesc->pvReserved2          = NULL;
1485     return DS_OK;
1486 }
1487
1488 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
1489 {
1490     IDsDriverImpl *This = (IDsDriverImpl *)iface;
1491     int enable = 0;
1492
1493     TRACE("(%p)\n",iface);
1494     /* make sure the card doesn't start playing before we want it to */
1495 #if 0
1496     if (ioctl(WOutDev[This->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1497         ERR("ioctl failed (%d)\n", errno);
1498         return DSERR_GENERIC;
1499     }
1500 #endif
1501     return DS_OK;
1502 }
1503
1504 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
1505 {
1506     IDsDriverImpl *This = (IDsDriverImpl *)iface;
1507     TRACE("(%p)\n",iface);
1508     if (This->primary) {
1509         ERR("problem with DirectSound: primary not released\n");
1510         return DSERR_GENERIC;
1511     }
1512     return DS_OK;
1513 }
1514
1515 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
1516 {
1517     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
1518     TRACE("(%p,%p)\n",iface,pCaps);
1519     memset(pCaps, 0, sizeof(*pCaps));
1520     /* FIXME: need to check actual capabilities */
1521     pCaps->dwFlags = DSCAPS_PRIMARYMONO | DSCAPS_PRIMARYSTEREO |
1522         DSCAPS_PRIMARY8BIT | DSCAPS_PRIMARY16BIT;
1523     pCaps->dwPrimaryBuffers = 1;
1524     pCaps->dwMinSecondarySampleRate = DSBFREQUENCY_MIN;
1525     pCaps->dwMaxSecondarySampleRate = DSBFREQUENCY_MAX;
1526     /* the other fields only apply to secondary buffers, which we don't support
1527      * (unless we want to mess with wavetable synthesizers and MIDI) */
1528     return DS_OK;
1529 }
1530
1531 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
1532                                                       LPWAVEFORMATEX pwfx,
1533                                                       DWORD dwFlags, DWORD dwCardAddress,
1534                                                       LPDWORD pdwcbBufferSize,
1535                                                       LPBYTE *ppbBuffer,
1536                                                       LPVOID *ppvObj)
1537 {
1538     IDsDriverImpl *This = (IDsDriverImpl *)iface;
1539     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
1540     HRESULT err;
1541 #if 0
1542     audio_buf_info info;
1543 #endif
1544     int enable = 0;
1545
1546     TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
1547     /* we only support primary buffers */
1548     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
1549         return DSERR_UNSUPPORTED;
1550     if (This->primary)
1551         return DSERR_ALLOCATED;
1552     if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
1553         return DSERR_CONTROLUNAVAIL;
1554
1555     *ippdsdb = HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
1556     if (*ippdsdb == NULL)
1557         return DSERR_OUTOFMEMORY;
1558     (*ippdsdb)->lpVtbl  = &dsdbvt;
1559     (*ippdsdb)->ref     = 1;
1560     (*ippdsdb)->drv     = This;
1561
1562     /* check how big the DMA buffer is now */
1563 #if 0
1564     if (ioctl(WOutDev[This->wDevID].unixdev, SNDCTL_DSP_GETOSPACE, &info) < 0) {
1565         ERR("ioctl failed (%d)\n", errno);
1566         HeapFree(GetProcessHeap(),0,*ippdsdb);
1567         *ippdsdb = NULL;
1568         return DSERR_GENERIC;
1569     }
1570 #endif
1571     WOutDev[This->wDevID].maplen =64*1024; /* Map 64 K at a time */
1572
1573 #if 0
1574     (*ippdsdb)->buflen = info.fragstotal * info.fragsize;
1575 #endif
1576     /* map the DMA buffer */
1577     err = DSDB_MapPrimary(*ippdsdb);
1578     if (err != DS_OK) {
1579         HeapFree(GetProcessHeap(),0,*ippdsdb);
1580         *ippdsdb = NULL;
1581         return err;
1582     }
1583
1584     /* primary buffer is ready to go */
1585     *pdwcbBufferSize    = WOutDev[This->wDevID].maplen;
1586     *ppbBuffer          = WOutDev[This->wDevID].mapping;
1587
1588     /* some drivers need some extra nudging after mapping */
1589 #if 0
1590     if (ioctl(WOutDev[This->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1591         ERR("ioctl failed (%d)\n", errno);
1592         return DSERR_GENERIC;
1593     }
1594 #endif
1595
1596     This->primary = *ippdsdb;
1597
1598     return DS_OK;
1599 }
1600
1601 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
1602                                                          PIDSDRIVERBUFFER pBuffer,
1603                                                          LPVOID *ppvObj)
1604 {
1605     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
1606     TRACE("(%p,%p): stub\n",iface,pBuffer);
1607     return DSERR_INVALIDCALL;
1608 }
1609
1610 static const IDsDriverVtbl dsdvt =
1611 {
1612     IDsDriverImpl_QueryInterface,
1613     IDsDriverImpl_AddRef,
1614     IDsDriverImpl_Release,
1615     IDsDriverImpl_GetDriverDesc,
1616     IDsDriverImpl_Open,
1617     IDsDriverImpl_Close,
1618     IDsDriverImpl_GetCaps,
1619     IDsDriverImpl_CreateSoundBuffer,
1620     IDsDriverImpl_DuplicateSoundBuffer
1621 };
1622
1623 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1624 {
1625     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
1626
1627     /* the HAL isn't much better than the HEL if we can't do mmap() */
1628     if (!(WOutDev[wDevID].caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
1629         ERR("DirectSound flag not set\n");
1630         MESSAGE("This sound card's driver does not support direct access\n");
1631         MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
1632         return MMSYSERR_NOTSUPPORTED;
1633     }
1634
1635     *idrv = HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
1636     if (!*idrv)
1637         return MMSYSERR_NOMEM;
1638     (*idrv)->lpVtbl     = &dsdvt;
1639     (*idrv)->ref        = 1;
1640
1641     (*idrv)->wDevID     = wDevID;
1642     (*idrv)->primary    = NULL;
1643     return MMSYSERR_NOERROR;
1644 }
1645
1646 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1647 {
1648     memset(desc, 0, sizeof(*desc));
1649     strcpy(desc->szDesc, "Wine LIBAUDIOIO DirectSound Driver");
1650     strcpy(desc->szDrvname, "wineaudioio.drv");
1651     return MMSYSERR_NOERROR;
1652 }
1653
1654 /*======================================================================*
1655  *                  Low level WAVE IN implementation                    *
1656  *======================================================================*/
1657
1658 /**************************************************************************
1659  *                      widGetDevCaps                           [internal]
1660  */
1661 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1662 {
1663     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1664
1665     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1666
1667     if (wDevID >= MAX_WAVEINDRV) {
1668         TRACE("MAX_WAVINDRV reached !\n");
1669         return MMSYSERR_BADDEVICEID;
1670     }
1671
1672     memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1673     return MMSYSERR_NOERROR;
1674 }
1675
1676 /**************************************************************************
1677  *                              widRecorder                     [internal]
1678  */
1679 static  DWORD   CALLBACK        widRecorder(LPVOID pmt)
1680 {
1681     WORD                uDevID = (DWORD)pmt;
1682     WINE_WAVEIN*        wwi = (WINE_WAVEIN*)&WInDev[uDevID];
1683     WAVEHDR*            lpWaveHdr;
1684     DWORD               dwSleepTime;
1685     MSG                 msg;
1686     DWORD               bytesRead;
1687
1688
1689         int fragments;
1690         int fragsize;
1691         int fragstotal;
1692         int bytes;
1693
1694
1695     int xs;
1696
1697         LPVOID          buffer = HeapAlloc(GetProcessHeap(),
1698                                            HEAP_ZERO_MEMORY,
1699                                        wwi->dwFragmentSize);
1700
1701     LPVOID              pOffset = buffer;
1702
1703     PeekMessageA(&msg, 0, 0, 0, 0);
1704     wwi->state = WINE_WS_STOPPED;
1705     wwi->dwTotalRecorded = 0;
1706
1707     SetEvent(wwi->hEvent);
1708
1709
1710         /* make sleep time to be # of ms to output a fragment */
1711     dwSleepTime = (wwi->dwFragmentSize * 1000) / wwi->format.wf.nAvgBytesPerSec;
1712     TRACE("sleeptime=%ld ms\n", dwSleepTime);
1713
1714     for (; ; ) {
1715         /* wait for dwSleepTime or an event in thread's queue */
1716         /* FIXME: could improve wait time depending on queue state,
1717          * ie, number of queued fragments
1718          */
1719
1720         if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
1721         {
1722             lpWaveHdr = wwi->lpQueuePtr;
1723
1724             bytes=fragsize=AudioIORecordingAvailable();
1725        fragments=fragstotal=1;
1726
1727             TRACE("info={frag=%d fsize=%d ftotal=%d bytes=%d}\n", fragments, fragsize, fragstotal, bytes);
1728
1729
1730             /* read all the fragments accumulated so far */
1731             while ((fragments > 0) && (wwi->lpQueuePtr))
1732             {
1733                 fragments --;
1734
1735                 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwFragmentSize)
1736                 {
1737                     /* directly read fragment in wavehdr */
1738                     bytesRead = AudioIORead(
1739                                      lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
1740                                      wwi->dwFragmentSize);
1741
1742                     TRACE("bytesRead=%ld (direct)\n", bytesRead);
1743                     if (bytesRead != (DWORD) -1)
1744                     {
1745                         /* update number of bytes recorded in current buffer and by this device */
1746                         lpWaveHdr->dwBytesRecorded += bytesRead;
1747                         wwi->dwTotalRecorded       += bytesRead;
1748
1749                         /* buffer is full. notify client */
1750                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
1751                         {
1752                             /* must copy the value of next waveHdr, because we have no idea of what
1753                              * will be done with the content of lpWaveHdr in callback
1754                              */
1755                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
1756
1757                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1758                             lpWaveHdr->dwFlags |=  WHDR_DONE;
1759
1760                             if (LIBAUDIOIO_NotifyClient(uDevID, WIM_DATA,
1761                                                  (DWORD)lpWaveHdr, 0) != MMSYSERR_NOERROR)
1762                             {
1763                                 WARN("can't notify client !\n");
1764                             }
1765                             lpWaveHdr = wwi->lpQueuePtr = lpNext;
1766                         }
1767                     }
1768                 }
1769                 else
1770                 {
1771                     /* read the fragment in a local buffer */
1772                     bytesRead = AudioIORead( buffer, wwi->dwFragmentSize);
1773                     pOffset = buffer;
1774
1775                     TRACE("bytesRead=%ld (local)\n", bytesRead);
1776
1777                     /* copy data in client buffers */
1778                     while (bytesRead != (DWORD) -1 && bytesRead > 0)
1779                     {
1780                         DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
1781
1782                         memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
1783                                pOffset,
1784                                dwToCopy);
1785
1786                         /* update number of bytes recorded in current buffer and by this device */
1787                         lpWaveHdr->dwBytesRecorded += dwToCopy;
1788                         wwi->dwTotalRecorded += dwToCopy;
1789                         bytesRead -= dwToCopy;
1790                         pOffset   += dwToCopy;
1791
1792                         /* client buffer is full. notify client */
1793                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
1794                         {
1795                             /* must copy the value of next waveHdr, because we have no idea of what
1796                              * will be done with the content of lpWaveHdr in callback
1797                              */
1798                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
1799                             TRACE("lpNext=%p\n", lpNext);
1800
1801                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1802                             lpWaveHdr->dwFlags |=  WHDR_DONE;
1803
1804                             if (LIBAUDIOIO_NotifyClient(uDevID, WIM_DATA,
1805                                                  (DWORD)lpWaveHdr, 0) != MMSYSERR_NOERROR)
1806                             {
1807                                 WARN("can't notify client !\n");
1808                             }
1809
1810                             wwi->lpQueuePtr = lpWaveHdr = lpNext;
1811                             if (!lpNext && bytesRead) {
1812                                 /* no more buffer to copy data to, but we did read more.
1813                                  * what hasn't been copied will be dropped
1814                                  */
1815                                 WARN("buffer under run! %lu bytes dropped.\n", bytesRead);
1816                                 wwi->lpQueuePtr = NULL;
1817                                 break;
1818                             }
1819                         }
1820                     }
1821                 }
1822             }
1823         }
1824
1825         MsgWaitForMultipleObjects(0, NULL, FALSE, dwSleepTime, QS_POSTMESSAGE);
1826
1827         while (PeekMessageA(&msg, 0, WINE_WM_FIRST, WINE_WM_LAST, PM_REMOVE)) {
1828
1829             TRACE("msg=0x%x wParam=0x%x lParam=0x%lx\n", msg.message, msg.wParam, msg.lParam);
1830             switch (msg.message) {
1831             case WINE_WM_PAUSING:
1832                 wwi->state = WINE_WS_PAUSED;
1833
1834                 AudioIORecordingPause();
1835                 SetEvent(wwi->hEvent);
1836                 break;
1837             case WINE_WM_RESTARTING:
1838             {
1839
1840                 wwi->state = WINE_WS_PLAYING;
1841
1842                 if (wwi->bTriggerSupport)
1843                 {
1844                     /* start the recording */
1845                     AudioIORecordingResume();
1846                 }
1847                 else
1848                 {
1849                     unsigned char data[4];
1850                     /* read 4 bytes to start the recording */
1851                     AudioIORead( data, 4);
1852                 }
1853
1854                 SetEvent(wwi->hEvent);
1855                 break;
1856             }
1857             case WINE_WM_HEADER:
1858                 lpWaveHdr = (LPWAVEHDR)msg.lParam;
1859                 lpWaveHdr->lpNext = 0;
1860
1861                 /* insert buffer at the end of queue */
1862                 {
1863                     LPWAVEHDR*  wh;
1864                     for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1865                     *wh = lpWaveHdr;
1866                 }
1867                 break;
1868             case WINE_WM_RESETTING:
1869                 wwi->state = WINE_WS_STOPPED;
1870                 /* return all buffers to the app */
1871                 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
1872                     TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
1873                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1874                     lpWaveHdr->dwFlags |= WHDR_DONE;
1875
1876                     if (LIBAUDIOIO_NotifyClient(uDevID, WIM_DATA,
1877                                          (DWORD)lpWaveHdr, 0) != MMSYSERR_NOERROR) {
1878                         WARN("can't notify client !\n");
1879                     }
1880                 }
1881                 wwi->lpQueuePtr = NULL;
1882                 SetEvent(wwi->hEvent);
1883                 break;
1884             case WINE_WM_CLOSING:
1885                 wwi->hThread = 0;
1886                 wwi->state = WINE_WS_CLOSED;
1887                 SetEvent(wwi->hEvent);
1888                 HeapFree(GetProcessHeap(), 0, buffer);
1889                 ExitThread(0);
1890                 /* shouldn't go here */
1891             default:
1892                 FIXME("unknown message %d\n", msg.message);
1893                 break;
1894             }
1895         }
1896   }
1897     ExitThread(0);
1898     /* just for not generating compilation warnings... should never be executed */
1899     return 0;
1900 }
1901
1902
1903 /**************************************************************************
1904  *                              widOpen                         [internal]
1905  */
1906 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1907 {
1908     int                 audio;
1909     int                 fragment_size;
1910     int                 sample_rate;
1911     int                 format;
1912     int                 dsp_stereo;
1913     WINE_WAVEIN*        wwi;
1914     int                 audio_fragment;
1915
1916     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
1917     if (lpDesc == NULL) {
1918         WARN("Invalid Parameter !\n");
1919         return MMSYSERR_INVALPARAM;
1920     }
1921     if (wDevID >= MAX_WAVEINDRV) return MMSYSERR_BADDEVICEID;
1922
1923     /* only PCM format is supported so far... */
1924     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1925         lpDesc->lpFormat->nChannels == 0 ||
1926         lpDesc->lpFormat->nSamplesPerSec == 0 ||
1927         (lpDesc->lpFormat->wBitsPerSample!=8 && lpDesc->lpFormat->wBitsPerSample!=16)) {
1928         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1929              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1930              lpDesc->lpFormat->nSamplesPerSec);
1931         return WAVERR_BADFORMAT;
1932     }
1933
1934     if (dwFlags & WAVE_FORMAT_QUERY) {
1935         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1936              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1937              lpDesc->lpFormat->nSamplesPerSec);
1938         return MMSYSERR_NOERROR;
1939     }
1940
1941     if (access(SOUND_DEV,0) != 0) return MMSYSERR_NOTENABLED;
1942     audio = AudioIOOpenX( O_RDONLY|O_NDELAY, &spec[CLIENT_RECORD],&spec[CLIENT_RECORD]);
1943     if (audio == -1) {
1944         WARN("can't open sound device %s (%s)!\n", SOUND_DEV, strerror(errno));
1945         return MMSYSERR_ALLOCATED;
1946     }
1947     fcntl(audio, F_SETFD, 1); /* set close on exec flag */
1948
1949     wwi = &WInDev[wDevID];
1950     if (wwi->lpQueuePtr) {
1951         WARN("Should have an empty queue (%p)\n", wwi->lpQueuePtr);
1952         wwi->lpQueuePtr = NULL;
1953     }
1954     wwi->unixdev = audio;
1955     wwi->dwTotalRecorded = 0;
1956     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1957
1958     memcpy(&wwi->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
1959     memcpy(&wwi->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1960
1961     if (wwi->format.wBitsPerSample == 0) {
1962         WARN("Resetting zeroed wBitsPerSample\n");
1963         wwi->format.wBitsPerSample = 8 *
1964             (wwi->format.wf.nAvgBytesPerSec /
1965              wwi->format.wf.nSamplesPerSec) /
1966             wwi->format.wf.nChannels;
1967     }
1968
1969     spec[CLIENT_RECORD].rate=sample_rate = wwi->format.wf.nSamplesPerSec;
1970     dsp_stereo = ((spec[CLIENT_RECORD].channels=wwi->format.wf.nChannels) > 1) ? TRUE : FALSE;
1971     spec[CLIENT_RECORD].precision= wwi->format.wBitsPerSample;
1972     spec[CLIENT_RECORD].type=(spec[CLIENT_RECORD].precision==16)?TYPE_SIGNED:TYPE_UNSIGNED;
1973
1974     /* This is actually hand tuned to work so that my SB Live:
1975      * - does not skip
1976      * - does not buffer too much
1977      * when sending with the Shoutcast winamp plugin
1978      */
1979     /* 7 fragments max, 2^10 = 1024 bytes per fragment */
1980     audio_fragment = 0x0007000A;
1981     fragment_size=4096;
1982     if (fragment_size == -1) {
1983         AudioIOClose();
1984         wwi->unixdev = -1;
1985         return MMSYSERR_NOTENABLED;
1986     }
1987     wwi->dwFragmentSize = fragment_size;
1988
1989     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
1990           wwi->format.wBitsPerSample, wwi->format.wf.nAvgBytesPerSec,
1991           wwi->format.wf.nSamplesPerSec, wwi->format.wf.nChannels,
1992           wwi->format.wf.nBlockAlign);
1993
1994     wwi->hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1995     wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
1996     if (wwi->hThread)
1997         SetThreadPriority(wwi->hThread, THREAD_PRIORITY_TIME_CRITICAL);
1998     WaitForSingleObject(wwi->hEvent, INFINITE);
1999
2000    if (LIBAUDIOIO_NotifyClient(wDevID, WIM_OPEN, 0L, 0L) != MMSYSERR_NOERROR) {
2001         WARN("can't notify client !\n");
2002         return MMSYSERR_INVALPARAM;
2003     }
2004     return MMSYSERR_NOERROR;
2005 }
2006
2007 /**************************************************************************
2008  *                              widClose                        [internal]
2009  */
2010 static DWORD widClose(WORD wDevID)
2011 {
2012     WINE_WAVEIN*        wwi;
2013
2014     TRACE("(%u);\n", wDevID);
2015     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2016         WARN("can't close !\n");
2017         return MMSYSERR_INVALHANDLE;
2018     }
2019
2020     wwi = &WInDev[wDevID];
2021
2022     if (wwi->lpQueuePtr != NULL) {
2023         WARN("still buffers open !\n");
2024         return WAVERR_STILLPLAYING;
2025     }
2026
2027     PostThreadMessageA(wwi->dwThreadID, WINE_WM_CLOSING, 0, 0);
2028     WaitForSingleObject(wwi->hEvent, INFINITE);
2029     CloseHandle(wwi->hEvent);
2030     AudioIOClose();
2031     wwi->unixdev = -1;
2032     wwi->dwFragmentSize = 0;
2033     if (LIBAUDIOIO_NotifyClient(wDevID, WIM_CLOSE, 0L, 0L) != MMSYSERR_NOERROR) {
2034         WARN("can't notify client !\n");
2035         return MMSYSERR_INVALPARAM;
2036     }
2037     return MMSYSERR_NOERROR;
2038 }
2039
2040 /**************************************************************************
2041  *                              widAddBuffer            [internal]
2042  */
2043 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2044 {
2045     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2046
2047     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2048         WARN("can't do it !\n");
2049         return MMSYSERR_INVALHANDLE;
2050     }
2051     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED)) {
2052         TRACE("never been prepared !\n");
2053         return WAVERR_UNPREPARED;
2054     }
2055     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) {
2056         TRACE("header already in use !\n");
2057         return WAVERR_STILLPLAYING;
2058     }
2059
2060     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2061     lpWaveHdr->dwFlags &= ~WHDR_DONE;
2062     lpWaveHdr->dwBytesRecorded = 0;
2063         lpWaveHdr->lpNext = NULL;
2064
2065     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_HEADER, 0, (DWORD)lpWaveHdr);
2066     return MMSYSERR_NOERROR;
2067 }
2068
2069 /**************************************************************************
2070  *                      widStart                                [internal]
2071  */
2072 static DWORD widStart(WORD wDevID)
2073 {
2074     TRACE("(%u);\n", wDevID);
2075     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2076         WARN("can't start recording !\n");
2077         return MMSYSERR_INVALHANDLE;
2078     }
2079
2080     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_RESTARTING, 0, 0);
2081     WaitForSingleObject(WInDev[wDevID].hEvent, INFINITE);
2082     return MMSYSERR_NOERROR;
2083 }
2084
2085 /**************************************************************************
2086  *                      widStop                                 [internal]
2087  */
2088 static DWORD widStop(WORD wDevID)
2089 {
2090     TRACE("(%u);\n", wDevID);
2091     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2092         WARN("can't stop !\n");
2093         return MMSYSERR_INVALHANDLE;
2094     }
2095     /* FIXME: reset aint stop */
2096     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_RESETTING, 0, 0);
2097     WaitForSingleObject(WInDev[wDevID].hEvent, INFINITE);
2098
2099     return MMSYSERR_NOERROR;
2100 }
2101
2102 /**************************************************************************
2103  *                      widReset                                [internal]
2104  */
2105 static DWORD widReset(WORD wDevID)
2106 {
2107     TRACE("(%u);\n", wDevID);
2108     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2109         WARN("can't reset !\n");
2110         return MMSYSERR_INVALHANDLE;
2111     }
2112     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_RESETTING, 0, 0);
2113     WaitForSingleObject(WInDev[wDevID].hEvent, INFINITE);
2114     return MMSYSERR_NOERROR;
2115 }
2116
2117 /**************************************************************************
2118  *                              widGetPosition                  [internal]
2119  */
2120 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
2121 {
2122     WINE_WAVEIN*        wwi;
2123
2124     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
2125
2126     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2127         WARN("can't get pos !\n");
2128         return MMSYSERR_INVALHANDLE;
2129     }
2130     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
2131
2132     wwi = &WInDev[wDevID];
2133
2134     return bytes_to_mmtime(lpTime, wwi->dwTotalRecorded, &wwi->format);
2135 }
2136
2137 /**************************************************************************
2138  *                              widMessage (WINEAUDIOIO.@)
2139  */
2140 DWORD WINAPI LIBAUDIOIO_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2141                             DWORD dwParam1, DWORD dwParam2)
2142 {
2143     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
2144           wDevID, wMsg, dwUser, dwParam1, dwParam2);
2145
2146     switch (wMsg) {
2147     case DRVM_INIT:
2148     case DRVM_EXIT:
2149     case DRVM_ENABLE:
2150     case DRVM_DISABLE:
2151         /* FIXME: Pretend this is supported */
2152         return 0;
2153     case WIDM_OPEN:             return widOpen       (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2154     case WIDM_CLOSE:            return widClose      (wDevID);
2155     case WIDM_ADDBUFFER:        return widAddBuffer  (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2156     case WIDM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
2157     case WIDM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
2158     case WIDM_GETDEVCAPS:       return widGetDevCaps (wDevID, (LPWAVEINCAPSW)dwParam1, dwParam2);
2159     case WIDM_GETNUMDEVS:       return wodGetNumDevs ();        /* same number of devices in output as in input */
2160     case WIDM_GETPOS:           return widGetPosition(wDevID, (LPMMTIME)dwParam1, dwParam2);
2161     case WIDM_RESET:            return widReset      (wDevID);
2162     case WIDM_START:            return widStart      (wDevID);
2163     case WIDM_STOP:             return widStop       (wDevID);
2164     case DRV_QUERYDSOUNDIFACE:  return widDsCreate   (wDevID, (PIDSCDRIVER*)dwParam1);
2165     case DRV_QUERYDSOUNDDESC:   return widDsDesc     (wDevID, (PDSDRIVERDESC)dwParam1);
2166     default:
2167         FIXME("unknown message %u!\n", wMsg);
2168     }
2169     return MMSYSERR_NOTSUPPORTED;
2170 }
2171
2172 /*======================================================================*
2173  *                  Low level DSOUND capture implementation             *
2174  *======================================================================*/
2175 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
2176 {
2177     /* we can't perform memory mapping as we don't have a file stream
2178         interface with arts like we do with oss */
2179     MESSAGE("This sound card's driver does not support direct access\n");
2180     MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
2181     return MMSYSERR_NOTSUPPORTED;
2182 }
2183
2184 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2185 {
2186     memset(desc, 0, sizeof(*desc));
2187     strcpy(desc->szDesc, "Wine LIBAUDIOIO DirectSound Driver");
2188     strcpy(desc->szDrvname, "wineaudioio.drv");
2189     return MMSYSERR_NOERROR;
2190 }
2191
2192 #else /* HAVE_LIBAUDIOIO */
2193
2194 /**************************************************************************
2195  *                              wodMessage (WINEAUDIOIO.@)
2196  */
2197 DWORD WINAPI LIBAUDIOIO_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2198                             DWORD dwParam1, DWORD dwParam2)
2199 {
2200     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2201     return MMSYSERR_NOTENABLED;
2202 }
2203
2204 /**************************************************************************
2205  *                              widMessage (WINEAUDIOIO.@)
2206  */
2207 DWORD WINAPI LIBAUDIOIO_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2208                             DWORD dwParam1, DWORD dwParam2)
2209 {
2210     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2211     return MMSYSERR_NOTENABLED;
2212 }
2213
2214 #endif /* HAVE_LIBAUDIOIO */