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