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