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