Add '\n' at the end of traces.
[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, DWORD dwParam2)
358 {
359     TRACE("wDevID = %04X wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n",wDevID, wMsg, dwParam1, dwParam2);
360     
361     switch (wMsg) {
362     case WOM_OPEN:
363     case WOM_CLOSE:
364     case WOM_DONE:
365         if (wDevID >= MAX_WAVEOUTDRV) return MCIERR_INTERNAL;
366         
367         if (WOutDev[wDevID].wFlags != DCB_NULL && 
368             !DriverCallback(WOutDev[wDevID].waveDesc.dwCallback, 
369                             WOutDev[wDevID].wFlags, 
370                             WOutDev[wDevID].waveDesc.hWave, 
371                             wMsg, 
372                             WOutDev[wDevID].waveDesc.dwInstance, 
373                             dwParam1, 
374                             dwParam2)) {
375             WARN("can't notify client !\n");
376             return MMSYSERR_NOERROR;
377         }
378         break;
379         
380     case WIM_OPEN:
381     case WIM_CLOSE:
382     case WIM_DATA:
383         if (wDevID >= MAX_WAVEINDRV) return MCIERR_INTERNAL;
384         
385         if (WInDev[wDevID].wFlags != DCB_NULL && 
386             !DriverCallback(WInDev[wDevID].waveDesc.dwCallback, 
387                             WInDev[wDevID].wFlags, 
388                             WInDev[wDevID].waveDesc.hWave, 
389                             wMsg, 
390                             WInDev[wDevID].waveDesc.dwInstance, 
391                             dwParam1, 
392                             dwParam2)) {
393             WARN("can't notify client !\n");
394             return MMSYSERR_NOERROR;
395         }
396         break;
397     default:
398         FIXME("Unknown CB message %u\n", wMsg);
399         break;
400     }
401     return 0;
402 }
403
404 /*======================================================================*
405  *                  Low level WAVE OUT implementation                   *
406  *======================================================================*/
407
408 /**************************************************************************
409  *                              wodPlayer_WriteFragments        [internal]
410  *
411  * wodPlayer helper. Writes as many fragments as it can to unixdev.
412  * Returns TRUE in case of buffer underrun.
413  */
414 static  BOOL    wodPlayer_WriteFragments(WINE_WAVEOUT* wwo)
415 {
416     LPWAVEHDR           lpWaveHdr;
417     LPBYTE              lpData;
418     int                 count;
419     audio_buf_info      info;
420
421     for (;;) {
422         if (ioctl(wwo->unixdev, SNDCTL_DSP_GETOSPACE, &info) < 0) {
423             ERR("ioctl failed (%s)\n", strerror(errno));
424             return FALSE;
425         }
426         
427         TRACE("info={frag=%d fsize=%d ftotal=%d bytes=%d}\n", info.fragments, info.fragsize, info.fragstotal, info.bytes);
428
429         if (!info.fragments)    /* output queue is full, wait a bit */
430             return FALSE;
431
432         lpWaveHdr = wwo->lpPlayPtr;
433         if (!lpWaveHdr) {
434             if (wwo->dwRemain > 0 &&            /* still data to send to complete current fragment */
435                 wwo->dwLastFragDone &&          /* first fragment has been played */
436                 info.fragments + 2 > info.fragstotal) {   /* done with all waveOutWrite()' fragments */
437                 /* FIXME: should do better handling here */
438                 WARN("Oooch, buffer underrun !\n");
439                 return TRUE; /* force resetting of waveOut device */
440             }
441             return FALSE;       /* wait a bit */
442         }
443         
444         if (wwo->dwOffCurrHdr == 0) {
445             TRACE("Starting a new wavehdr %p of %ld bytes\n", lpWaveHdr, lpWaveHdr->dwBufferLength);
446             if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
447                 if (wwo->lpLoopPtr) {
448                     WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
449                 } else {
450                     TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
451                     wwo->lpLoopPtr = lpWaveHdr;
452                     /* Windows does not touch WAVEHDR.dwLoops,
453                      * so we need to make an internal copy */
454                     wwo->dwLoops = lpWaveHdr->dwLoops;
455                 }
456             }
457         }
458         
459         lpData = lpWaveHdr->lpData;
460
461         /* finish current wave hdr ? */
462         if (wwo->dwOffCurrHdr + wwo->dwRemain >= lpWaveHdr->dwBufferLength) { 
463             DWORD       toWrite = lpWaveHdr->dwBufferLength - wwo->dwOffCurrHdr;
464             
465             /* write end of current wave hdr */
466             count = write(wwo->unixdev, lpData + wwo->dwOffCurrHdr, toWrite);
467             TRACE("write(%p[%5lu], %5lu) => %d\n", lpData, wwo->dwOffCurrHdr, toWrite, count);
468             
469             if (count > 0 || toWrite == 0) {
470                 DWORD   tc = GetTickCount();
471
472                 if (wwo->dwLastFragDone /* + guard time ?? */ < tc) 
473                     wwo->dwLastFragDone = tc;
474                 wwo->dwLastFragDone += (toWrite * 1000) / wwo->format.wf.nAvgBytesPerSec;
475
476                 lpWaveHdr->reserved = wwo->dwLastFragDone;
477                 TRACE("Tagging hdr %p with %08lx\n", lpWaveHdr, wwo->dwLastFragDone);
478
479                 /* WAVEHDR written, go to next one */
480                 if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
481                     if (--wwo->dwLoops > 0) {
482                         wwo->lpPlayPtr = wwo->lpLoopPtr;
483                     } else {
484                         /* last one played */
485                         if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
486                             FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
487                             /* shall we consider the END flag for the closing loop or for
488                              * the opening one or for both ???
489                              * code assumes for closing loop only
490                              */
491                             wwo->lpLoopPtr = lpWaveHdr;
492                         } else {
493                             wwo->lpLoopPtr = NULL;
494                         }
495                         wwo->lpPlayPtr = lpWaveHdr->lpNext;
496                     }
497                 } else {
498                     wwo->lpPlayPtr = lpWaveHdr->lpNext;
499                 }
500                 wwo->dwOffCurrHdr = 0;
501                 if ((wwo->dwRemain -= count) == 0) {
502                     wwo->dwRemain = wwo->dwFragmentSize;
503                 }
504             }
505             continue; /* try to go to use next wavehdr */
506         }  else {
507             count = write(wwo->unixdev, lpData + wwo->dwOffCurrHdr, wwo->dwRemain);
508             TRACE("write(%p[%5lu], %5lu) => %d\n", lpData, wwo->dwOffCurrHdr, wwo->dwRemain, count);
509             if (count > 0) {
510                 DWORD   tc = GetTickCount();
511
512                 if (wwo->dwLastFragDone /* + guard time ?? */ < tc) 
513                     wwo->dwLastFragDone = tc;
514                 wwo->dwLastFragDone += (wwo->dwRemain * 1000) / wwo->format.wf.nAvgBytesPerSec;
515
516                 TRACE("Tagging frag with %08lx\n", wwo->dwLastFragDone);
517
518                 wwo->dwOffCurrHdr += count;
519                 wwo->dwRemain = wwo->dwFragmentSize;
520             }
521         }
522     }
523 }
524
525
526 int wodPlayer_Message(WINE_WAVEOUT *wwo, int msg, DWORD param)
527 {
528     EnterCriticalSection(&wwo->msg_crst);
529     if ((wwo->msg_tosave == wwo->msg_toget) /* buffer overflow ? */
530     &&  (wwo->messages[wwo->msg_toget].msg))
531     {
532         ERR("buffer overflow !?\n");
533         LeaveCriticalSection(&wwo->msg_crst);
534         return 0;
535     }
536
537     wwo->messages[wwo->msg_tosave].msg = msg;
538     wwo->messages[wwo->msg_tosave].param = param;
539     wwo->msg_tosave++;
540     if (wwo->msg_tosave > WWO_RING_BUFFER_SIZE-1)
541         wwo->msg_tosave = 0;
542     LeaveCriticalSection(&wwo->msg_crst);
543     /* signal a new message */
544     SetEvent(wwo->msg_event);
545     return 1;
546 }
547
548 int wodPlayer_RetrieveMessage(WINE_WAVEOUT *wwo, int *msg, DWORD *param)
549 {
550     EnterCriticalSection(&wwo->msg_crst);
551
552     if (wwo->msg_toget == wwo->msg_tosave) /* buffer empty ? */
553     {
554         LeaveCriticalSection(&wwo->msg_crst);
555         return 0;
556     }
557         
558     *msg = wwo->messages[wwo->msg_toget].msg;
559     wwo->messages[wwo->msg_toget].msg = 0;
560     *param = wwo->messages[wwo->msg_toget].param;
561     wwo->msg_toget++;
562     if (wwo->msg_toget > WWO_RING_BUFFER_SIZE-1)
563         wwo->msg_toget = 0;
564     LeaveCriticalSection(&wwo->msg_crst);
565     return 1;
566 }
567
568 /**************************************************************************
569  *                              wodPlayer_Notify                [internal]
570  *
571  * wodPlayer helper. Notifies (and remove from queue) all the wavehdr which content
572  * have been played (actually to speaker, not to unixdev fd).
573  */
574 static  void    wodPlayer_Notify(WINE_WAVEOUT* wwo, WORD uDevID, BOOL force)
575 {
576     LPWAVEHDR           lpWaveHdr;
577     DWORD               tc = GetTickCount();
578
579     while (wwo->lpQueuePtr && 
580            (force || 
581             (wwo->lpQueuePtr != wwo->lpPlayPtr && wwo->lpQueuePtr != wwo->lpLoopPtr))) {
582         lpWaveHdr = wwo->lpQueuePtr;
583             
584         if (lpWaveHdr->reserved > tc && !force) break;
585
586         wwo->dwPlayedTotal += lpWaveHdr->dwBufferLength;
587         wwo->lpQueuePtr = lpWaveHdr->lpNext;
588
589         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
590         lpWaveHdr->dwFlags |= WHDR_DONE;
591
592         TRACE("Notifying client with %p\n", lpWaveHdr);
593         if (OSS_NotifyClient(uDevID, WOM_DONE, (DWORD)lpWaveHdr, 0) != MMSYSERR_NOERROR) {
594             WARN("can't notify client !\n");
595         }
596     }
597 }
598
599 /**************************************************************************
600  *                              wodPlayer_Reset                 [internal]
601  *
602  * wodPlayer helper. Resets current output stream.
603  */
604 static  void    wodPlayer_Reset(WINE_WAVEOUT* wwo, WORD uDevID, BOOL reset)
605 {
606     /* updates current notify list */
607     wodPlayer_Notify(wwo, uDevID, FALSE);
608
609     /* flush all possible output */
610     if (ioctl(wwo->unixdev, SNDCTL_DSP_RESET, 0) == -1) {
611         perror("ioctl SNDCTL_DSP_RESET");
612         wwo->hThread = 0;
613         wwo->state = WINE_WS_STOPPED;
614         ExitThread(-1);
615     }
616
617     wwo->dwOffCurrHdr = 0;
618     wwo->dwRemain = wwo->dwFragmentSize;
619     if (reset) {
620         /* empty notify list */
621         wodPlayer_Notify(wwo, uDevID, TRUE);
622
623         wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
624         wwo->state = WINE_WS_STOPPED;
625         wwo->dwPlayedTotal = 0;
626     } else {
627         /* FIXME: this is not accurate when looping, but can be do better ? */
628         wwo->lpPlayPtr = (wwo->lpLoopPtr) ? wwo->lpLoopPtr : wwo->lpQueuePtr;
629         wwo->state = WINE_WS_PAUSED;
630     }
631 }
632
633 /**************************************************************************
634  *                              wodPlayer                       [internal]
635  */
636 static  DWORD   CALLBACK        wodPlayer(LPVOID pmt)
637 {
638     WORD                uDevID = (DWORD)pmt;
639     WINE_WAVEOUT*       wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
640     WAVEHDR*            lpWaveHdr;
641     DWORD               dwSleepTime;
642     int                 msg;
643     DWORD               param;
644     DWORD               tc;
645
646     wwo->state = WINE_WS_STOPPED;
647
648     wwo->dwLastFragDone = 0;
649     wwo->dwOffCurrHdr = 0;
650     wwo->dwRemain = wwo->dwFragmentSize;
651     wwo->lpQueuePtr = wwo->lpPlayPtr = wwo->lpLoopPtr = NULL;
652     wwo->dwPlayedTotal = 0;
653
654     TRACE("imhere[0]\n");
655     SetEvent(wwo->hEvent);
656
657     for (;;) {
658         /* wait for dwSleepTime or an event in thread's queue
659          * FIXME:
660          * - is wait time calculation optimal ?
661          * - these 100 ms parts should be changed, but Eric reports
662          *   that the wodPlayer thread might lock up if we use INFINITE
663          *   (strange !), so I better don't change that now... */
664         if (wwo->state != WINE_WS_PLAYING)
665             dwSleepTime = 100;
666         else
667         {
668             tc = GetTickCount();
669             if (tc < wwo->dwLastFragDone)
670             {
671                 /* calculate sleep time depending on when the last fragment
672                    will be played */
673                 dwSleepTime = (wwo->dwLastFragDone - tc)*7/10;
674                 if (dwSleepTime > 100)
675                     dwSleepTime = 100;
676             }
677             else
678                 dwSleepTime = 0;
679         }
680
681         TRACE("imhere[1]\n");
682         if (dwSleepTime)
683         WaitForSingleObject(wwo->msg_event, dwSleepTime);
684         TRACE("imhere[2] (q=%p p=%p)\n", wwo->lpQueuePtr, wwo->lpPlayPtr);
685         while (wodPlayer_RetrieveMessage(wwo, &msg, &param)) {
686             switch (msg) {
687             case WINE_WM_PAUSING:
688                 wodPlayer_Reset(wwo, uDevID, FALSE);
689                 wwo->state = WINE_WS_PAUSED;
690                 SetEvent(wwo->hEvent);
691                 break;
692             case WINE_WM_RESTARTING:
693                 wwo->state = WINE_WS_PLAYING;
694                 SetEvent(wwo->hEvent);
695                 break;
696             case WINE_WM_HEADER:
697                 lpWaveHdr = (LPWAVEHDR)param;
698                 
699                 /* insert buffer at the end of queue */
700                 {
701                     LPWAVEHDR*  wh;
702                     for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
703                     *wh = lpWaveHdr;
704                 }
705                 if (!wwo->lpPlayPtr) wwo->lpPlayPtr = lpWaveHdr;
706                 if (wwo->state == WINE_WS_STOPPED)
707                     wwo->state = WINE_WS_PLAYING;
708                 break;
709             case WINE_WM_RESETTING:
710                 wodPlayer_Reset(wwo, uDevID, TRUE);
711                 SetEvent(wwo->hEvent);
712                 break;
713             case WINE_WM_CLOSING:
714                 /* sanity check: this should not happen since the device must have been reset before */
715                 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
716                 wwo->hThread = 0;
717                 wwo->state = WINE_WS_CLOSED;
718                 SetEvent(wwo->hEvent);
719                 ExitThread(0);
720                 /* shouldn't go here */
721             default:
722                 FIXME("unknown message %d\n", msg);
723                 break;
724             }
725         }
726         if (wwo->state == WINE_WS_PLAYING) {
727             wodPlayer_WriteFragments(wwo);
728         }
729         wodPlayer_Notify(wwo, uDevID, FALSE);
730     }
731     ExitThread(0);
732     /* just for not generating compilation warnings... should never be executed */
733     return 0; 
734 }
735
736 /**************************************************************************
737  *                      wodGetDevCaps                           [internal]
738  */
739 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSA lpCaps, DWORD dwSize)
740 {
741     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
742     
743     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
744     
745     if (wDevID >= MAX_WAVEOUTDRV) {
746         TRACE("MAX_WAVOUTDRV reached !\n");
747         return MMSYSERR_BADDEVICEID;
748     }
749
750     memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
751     return MMSYSERR_NOERROR;
752 }
753
754 /**************************************************************************
755  *                              wodOpen                         [internal]
756  */
757 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
758 {
759     int                 audio;
760     int                 format;
761     int                 sample_rate;
762     int                 dsp_stereo;
763     int                 fragment_size;
764     int                 audio_fragment;
765     WINE_WAVEOUT*       wwo;
766
767     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
768     if (lpDesc == NULL) {
769         WARN("Invalid Parameter !\n");
770         return MMSYSERR_INVALPARAM;
771     }
772     if (wDevID >= MAX_WAVEOUTDRV) {
773         TRACE("MAX_WAVOUTDRV reached !\n");
774         return MMSYSERR_BADDEVICEID;
775     }
776
777     /* only PCM format is supported so far... */
778     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
779         lpDesc->lpFormat->nChannels == 0 ||
780         lpDesc->lpFormat->nSamplesPerSec == 0) {
781         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n", 
782              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
783              lpDesc->lpFormat->nSamplesPerSec);
784         return WAVERR_BADFORMAT;
785     }
786
787     if (dwFlags & WAVE_FORMAT_QUERY) {
788         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n", 
789              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
790              lpDesc->lpFormat->nSamplesPerSec);
791         return MMSYSERR_NOERROR;
792     }
793
794     wwo = &WOutDev[wDevID];
795
796     if ((dwFlags & WAVE_DIRECTSOUND) && !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
797         /* not supported, ignore it */
798         dwFlags &= ~WAVE_DIRECTSOUND;
799
800     if (access(SOUND_DEV, 0) != 0)
801         return MMSYSERR_NOTENABLED;
802     if (dwFlags & WAVE_DIRECTSOUND)
803         /* we want to be able to mmap() the device, which means it must be opened readable,
804          * otherwise mmap() will fail (at least under Linux) */
805         audio = open(SOUND_DEV, O_RDWR|O_NDELAY, 0);
806     else
807         audio = open(SOUND_DEV, O_WRONLY|O_NDELAY, 0);
808     if (audio == -1) {
809         WARN("can't open sound device %s (%s)!\n", SOUND_DEV, strerror(errno));
810         return MMSYSERR_ALLOCATED;
811     }
812     fcntl(audio, F_SETFD, 1); /* set close on exec flag */
813     wwo->unixdev = audio;
814     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
815     
816     memcpy(&wwo->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
817     memcpy(&wwo->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
818     
819     if (wwo->format.wBitsPerSample == 0) {
820         WARN("Resetting zeroed wBitsPerSample\n");
821         wwo->format.wBitsPerSample = 8 *
822             (wwo->format.wf.nAvgBytesPerSec /
823              wwo->format.wf.nSamplesPerSec) /
824             wwo->format.wf.nChannels;
825     }
826     
827     if (dwFlags & WAVE_DIRECTSOUND) {
828         if (wwo->caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
829             /* we have realtime DirectSound, fragments just waste our time,
830              * but a large buffer is good, so choose 64KB (32 * 2^11) */
831             audio_fragment = 0x0020000B;
832         else
833             /* to approximate realtime, we must use small fragments,
834              * let's try to fragment the above 64KB (256 * 2^8) */
835             audio_fragment = 0x01000008;
836     } else {
837         /* shockwave player uses only 4 1k-fragments at a rate of 22050 bytes/sec
838          * thus leading to 46ms per fragment, and a turnaround time of 185ms
839          */
840         /* 16 fragments max, 2^10=1024 bytes per fragment */
841         audio_fragment = 0x000F000A;
842     }
843     sample_rate = wwo->format.wf.nSamplesPerSec;
844     dsp_stereo = (wwo->format.wf.nChannels > 1) ? 1 : 0;
845     format = (wwo->format.wBitsPerSample == 16) ? AFMT_S16_LE : AFMT_U8;
846
847     IOCTL(audio, SNDCTL_DSP_SETFRAGMENT, audio_fragment);
848     /* First size and stereo then samplerate */
849     IOCTL(audio, SNDCTL_DSP_SETFMT, format);
850     IOCTL(audio, SNDCTL_DSP_STEREO, dsp_stereo);
851     IOCTL(audio, SNDCTL_DSP_SPEED, sample_rate);
852
853     /* paranoid checks */
854     if (format != ((wwo->format.wBitsPerSample == 16) ? AFMT_S16_LE : AFMT_U8))
855         ERR("Can't set format to %d (%d)\n", 
856             (wwo->format.wBitsPerSample == 16) ? AFMT_S16_LE : AFMT_U8, format);
857     if (dsp_stereo != (wwo->format.wf.nChannels > 1) ? 1 : 0) 
858         ERR("Can't set stereo to %u (%d)\n", 
859             (wwo->format.wf.nChannels > 1) ? 1 : 0, dsp_stereo);
860     if (!NEAR_MATCH(sample_rate,wwo->format.wf.nSamplesPerSec))
861         ERR("Can't set sample_rate to %lu (%d)\n", 
862             wwo->format.wf.nSamplesPerSec, sample_rate);
863
864     /* even if we set fragment size above, read it again, just in case */
865     IOCTL(audio, SNDCTL_DSP_GETBLKSIZE, fragment_size);
866     if (fragment_size == -1) {
867         ERR("IOCTL can't 'SNDCTL_DSP_GETBLKSIZE' !\n");
868         close(audio);
869         wwo->unixdev = -1;
870         return MMSYSERR_NOTENABLED;
871     }
872     if ((fragment_size > 1024) && (LOWORD(audio_fragment) <= 10)) {
873         /* we've tried to set 1K fragments or less, but it didn't work */
874         ERR("fragment size set failed, size is now %d\n", fragment_size);
875         MESSAGE("Your Open Sound System driver did not let us configure small enough sound fragments.\n");
876         MESSAGE("This may cause delays and other problems in audio playback with certain applications.\n");
877     }
878     wwo->dwFragmentSize = fragment_size;
879
880     wwo->msg_toget = 0;
881     wwo->msg_tosave = 0;
882     wwo->msg_event = CreateEventA(NULL, FALSE, FALSE, NULL);
883     memset(wwo->messages, 0, sizeof(WWO_MSG)*WWO_RING_BUFFER_SIZE);
884     InitializeCriticalSection(&wwo->msg_crst);
885
886     if (!(dwFlags & WAVE_DIRECTSOUND)) {
887         wwo->hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
888         wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
889         WaitForSingleObject(wwo->hEvent, INFINITE);
890     } else {
891         wwo->hEvent = INVALID_HANDLE_VALUE;
892         wwo->hThread = INVALID_HANDLE_VALUE;
893         wwo->dwThreadID = 0;
894     }
895
896     TRACE("fd=%d fragmentSize=%ld\n", 
897           wwo->unixdev, wwo->dwFragmentSize);
898     if (wwo->dwFragmentSize % wwo->format.wf.nBlockAlign)
899         ERR("Fragment doesn't contain an integral number of data blocks\n");
900
901     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n", 
902           wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec, 
903           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
904           wwo->format.wf.nBlockAlign);
905     
906     if (OSS_NotifyClient(wDevID, WOM_OPEN, 0L, 0L) != MMSYSERR_NOERROR) {
907         WARN("can't notify client !\n");
908         return MMSYSERR_INVALPARAM;
909     }
910     return MMSYSERR_NOERROR;
911 }
912
913 /**************************************************************************
914  *                              wodClose                        [internal]
915  */
916 static DWORD wodClose(WORD wDevID)
917 {
918     DWORD               ret = MMSYSERR_NOERROR;
919     WINE_WAVEOUT*       wwo;
920
921     TRACE("(%u);\n", wDevID);
922     
923     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
924         WARN("bad device ID !\n");
925         return MMSYSERR_BADDEVICEID;
926     }
927     
928     wwo = &WOutDev[wDevID];
929     if (wwo->lpQueuePtr) {
930         WARN("buffers still playing !\n");
931         ret = WAVERR_STILLPLAYING;
932     } else {
933         TRACE("imhere[3-close]\n");
934         if (wwo->hEvent != INVALID_HANDLE_VALUE) {
935             wodPlayer_Message(wwo, WINE_WM_CLOSING, 0);
936             WaitForSingleObject(wwo->hEvent, INFINITE);
937             CloseHandle(wwo->hEvent);
938         }
939         if (wwo->mapping) {
940             munmap(wwo->mapping, wwo->maplen);
941             wwo->mapping = NULL;
942         }
943
944         close(wwo->unixdev);
945         wwo->unixdev = -1;
946         wwo->dwFragmentSize = 0;
947         if (OSS_NotifyClient(wDevID, WOM_CLOSE, 0L, 0L) != MMSYSERR_NOERROR) {
948             WARN("can't notify client !\n");
949             ret = MMSYSERR_INVALPARAM;
950         }
951     }
952     return ret;
953 }
954
955 /**************************************************************************
956  *                              wodWrite                        [internal]
957  * 
958  */
959 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
960 {
961     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
962     
963     /* first, do the sanity checks... */
964     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
965         WARN("bad dev ID !\n");
966         return MMSYSERR_BADDEVICEID;
967     }
968     
969     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED)) 
970         return WAVERR_UNPREPARED;
971     
972     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) 
973         return WAVERR_STILLPLAYING;
974
975     lpWaveHdr->dwFlags &= ~WHDR_DONE;
976     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
977     lpWaveHdr->lpNext = 0;
978
979     TRACE("imhere[3-HEADER]\n");
980     wodPlayer_Message(&WOutDev[wDevID], WINE_WM_HEADER, (DWORD)lpWaveHdr);
981
982     return MMSYSERR_NOERROR;
983 }
984
985 /**************************************************************************
986  *                              wodPrepare                      [internal]
987  */
988 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
989 {
990     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
991     
992     if (wDevID >= MAX_WAVEOUTDRV) {
993         WARN("bad device ID !\n");
994         return MMSYSERR_BADDEVICEID;
995     }
996     
997     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
998         return WAVERR_STILLPLAYING;
999     
1000     lpWaveHdr->dwFlags |= WHDR_PREPARED;
1001     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1002     return MMSYSERR_NOERROR;
1003 }
1004
1005 /**************************************************************************
1006  *                              wodUnprepare                    [internal]
1007  */
1008 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1009 {
1010     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1011     
1012     if (wDevID >= MAX_WAVEOUTDRV) {
1013         WARN("bad device ID !\n");
1014         return MMSYSERR_BADDEVICEID;
1015     }
1016     
1017     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1018         return WAVERR_STILLPLAYING;
1019     
1020     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1021     lpWaveHdr->dwFlags |= WHDR_DONE;
1022     
1023     return MMSYSERR_NOERROR;
1024 }
1025
1026 /**************************************************************************
1027  *                      wodPause                                [internal]
1028  */
1029 static DWORD wodPause(WORD wDevID)
1030 {
1031     TRACE("(%u);!\n", wDevID);
1032     
1033     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1034         WARN("bad device ID !\n");
1035         return MMSYSERR_BADDEVICEID;
1036     }
1037     
1038     TRACE("imhere[3-PAUSING]\n");
1039     wodPlayer_Message(&WOutDev[wDevID], WINE_WM_PAUSING, 0);
1040     WaitForSingleObject(WOutDev[wDevID].hEvent, INFINITE);
1041     
1042     return MMSYSERR_NOERROR;
1043 }
1044
1045 /**************************************************************************
1046  *                      wodRestart                              [internal]
1047  */
1048 static DWORD wodRestart(WORD wDevID)
1049 {
1050     TRACE("(%u);\n", wDevID);
1051     
1052     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1053         WARN("bad device ID !\n");
1054         return MMSYSERR_BADDEVICEID;
1055     }
1056     
1057     if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1058         TRACE("imhere[3-RESTARTING]\n");
1059         wodPlayer_Message(&WOutDev[wDevID], WINE_WM_RESTARTING, 0);
1060         WaitForSingleObject(WOutDev[wDevID].hEvent, INFINITE);
1061     }
1062     
1063     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1064     /* FIXME: Myst crashes with this ... hmm -MM
1065        if (OSS_NotifyClient(wDevID, WOM_DONE, 0L, 0L) != MMSYSERR_NOERROR) {
1066        WARN("can't notify client !\n");
1067        return MMSYSERR_INVALPARAM;
1068        }
1069     */
1070     
1071     return MMSYSERR_NOERROR;
1072 }
1073
1074 /**************************************************************************
1075  *                      wodReset                                [internal]
1076  */
1077 static DWORD wodReset(WORD wDevID)
1078 {
1079     TRACE("(%u);\n", wDevID);
1080     
1081     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1082         WARN("bad device ID !\n");
1083         return MMSYSERR_BADDEVICEID;
1084     }
1085     
1086     TRACE("imhere[3-RESET]\n");
1087     wodPlayer_Message(&WOutDev[wDevID], WINE_WM_RESETTING, 0);
1088     WaitForSingleObject(WOutDev[wDevID].hEvent, INFINITE);
1089     
1090     return MMSYSERR_NOERROR;
1091 }
1092
1093
1094 /**************************************************************************
1095  *                              wodGetPosition                  [internal]
1096  */
1097 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1098 {
1099     int                 time;
1100     DWORD               val;
1101     WINE_WAVEOUT*       wwo;
1102
1103     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1104     
1105     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1106         WARN("bad device ID !\n");
1107         return MMSYSERR_BADDEVICEID;
1108     }
1109     
1110     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1111
1112     wwo = &WOutDev[wDevID];
1113     val = wwo->dwPlayedTotal;
1114
1115     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n", 
1116           lpTime->wType, wwo->format.wBitsPerSample, 
1117           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels, 
1118           wwo->format.wf.nAvgBytesPerSec); 
1119     TRACE("dwTotalPlayed=%lu\n", val);
1120     
1121     switch (lpTime->wType) {
1122     case TIME_BYTES:
1123         lpTime->u.cb = val;
1124         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
1125         break;
1126     case TIME_SAMPLES:
1127         lpTime->u.sample = val * 8 / wwo->format.wBitsPerSample;
1128         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
1129         break;
1130     case TIME_SMPTE:
1131         time = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1132         lpTime->u.smpte.hour = time / 108000;
1133         time -= lpTime->u.smpte.hour * 108000;
1134         lpTime->u.smpte.min = time / 1800;
1135         time -= lpTime->u.smpte.min * 1800;
1136         lpTime->u.smpte.sec = time / 30;
1137         time -= lpTime->u.smpte.sec * 30;
1138         lpTime->u.smpte.frame = time;
1139         lpTime->u.smpte.fps = 30;
1140         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
1141               lpTime->u.smpte.hour, lpTime->u.smpte.min,
1142               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
1143         break;
1144     default:
1145         FIXME("Format %d not supported ! use TIME_MS !\n", lpTime->wType);
1146         lpTime->wType = TIME_MS;
1147     case TIME_MS:
1148         lpTime->u.ms = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1149         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
1150         break;
1151     }
1152     return MMSYSERR_NOERROR;
1153 }
1154
1155 /**************************************************************************
1156  *                              wodGetVolume                    [internal]
1157  */
1158 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1159 {
1160     int         mixer;
1161     int         volume;
1162     DWORD       left, right;
1163     
1164     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1165     
1166     if (lpdwVol == NULL) 
1167         return MMSYSERR_NOTENABLED;
1168     if ((mixer = open(MIXER_DEV, O_RDONLY|O_NDELAY)) < 0) {
1169         WARN("mixer device not available !\n");
1170         return MMSYSERR_NOTENABLED;
1171     }
1172     if (ioctl(mixer, SOUND_MIXER_READ_PCM, &volume) == -1) {
1173         WARN("unable read mixer !\n");
1174         return MMSYSERR_NOTENABLED;
1175     }
1176     close(mixer);
1177     left = LOBYTE(volume);
1178     right = HIBYTE(volume);
1179     TRACE("left=%ld right=%ld !\n", left, right);
1180     *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) << 16);
1181     return MMSYSERR_NOERROR;
1182 }
1183
1184
1185 /**************************************************************************
1186  *                              wodSetVolume                    [internal]
1187  */
1188 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1189 {
1190     int         mixer;
1191     int         volume;
1192     DWORD       left, right;
1193
1194     TRACE("(%u, %08lX);\n", wDevID, dwParam);
1195
1196     left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
1197     right = (HIWORD(dwParam) * 100) / 0xFFFFl;
1198     volume = left + (right << 8);
1199     
1200     if ((mixer = open(MIXER_DEV, O_WRONLY|O_NDELAY)) < 0) {
1201         WARN("mixer device not available !\n");
1202         return MMSYSERR_NOTENABLED;
1203     }
1204     if (ioctl(mixer, SOUND_MIXER_WRITE_PCM, &volume) == -1) {
1205         WARN("unable set mixer !\n");
1206         return MMSYSERR_NOTENABLED;
1207     } else {
1208         TRACE("volume=%04x\n", (unsigned)volume);
1209     }
1210     close(mixer);
1211     return MMSYSERR_NOERROR;
1212 }
1213
1214 /**************************************************************************
1215  *                              wodGetNumDevs                   [internal]
1216  */
1217 static  DWORD   wodGetNumDevs(void)
1218 {
1219     DWORD       ret = 1;
1220     
1221     /* FIXME: For now, only one sound device (SOUND_DEV) is allowed */
1222     int audio = open(SOUND_DEV, O_WRONLY|O_NDELAY, 0);
1223     
1224     if (audio == -1) {
1225         if (errno != EBUSY)
1226             ret = 0;
1227     } else {
1228         close(audio);
1229     }
1230     return ret;
1231 }
1232
1233 /**************************************************************************
1234  *                              OSS_wodMessage          [sample driver]
1235  */
1236 DWORD WINAPI OSS_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser, 
1237                             DWORD dwParam1, DWORD dwParam2)
1238 {
1239     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
1240           wDevID, wMsg, dwUser, dwParam1, dwParam2);
1241     
1242     switch (wMsg) {
1243     case DRVM_INIT:
1244     case DRVM_EXIT:
1245     case DRVM_ENABLE:
1246     case DRVM_DISABLE:
1247         /* FIXME: Pretend this is supported */
1248         return 0;
1249     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1250     case WODM_CLOSE:            return wodClose         (wDevID);
1251     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1252     case WODM_PAUSE:            return wodPause         (wDevID);
1253     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
1254     case WODM_BREAKLOOP:        return MMSYSERR_NOTSUPPORTED;
1255     case WODM_PREPARE:          return wodPrepare       (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1256     case WODM_UNPREPARE:        return wodUnprepare     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1257     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSA)dwParam1,      dwParam2);
1258     case WODM_GETNUMDEVS:       return wodGetNumDevs    ();
1259     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1260     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1261     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1262     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1263     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
1264     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
1265     case WODM_RESTART:          return wodRestart       (wDevID);
1266     case WODM_RESET:            return wodReset         (wDevID);
1267
1268     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate(wDevID, (PIDSDRIVER*)dwParam1);
1269     default:
1270         FIXME("unknown message %d!\n", wMsg);
1271     }
1272     return MMSYSERR_NOTSUPPORTED;
1273 }
1274
1275 /*======================================================================*
1276  *                  Low level DSOUND implementation                     *
1277  *======================================================================*/
1278
1279 typedef struct IDsDriverImpl IDsDriverImpl;
1280 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1281
1282 struct IDsDriverImpl
1283 {
1284     /* IUnknown fields */
1285     ICOM_VFIELD(IDsDriver);
1286     DWORD               ref;
1287     /* IDsDriverImpl fields */
1288     UINT                wDevID;
1289     IDsDriverBufferImpl*primary;
1290 };
1291
1292 struct IDsDriverBufferImpl
1293 {
1294     /* IUnknown fields */
1295     ICOM_VFIELD(IDsDriverBuffer);
1296     DWORD               ref;
1297     /* IDsDriverBufferImpl fields */
1298     IDsDriverImpl*      drv;
1299     DWORD               buflen;
1300 };
1301
1302 static HRESULT DSDB_MapPrimary(IDsDriverBufferImpl *dsdb)
1303 {
1304     WINE_WAVEOUT *wwo = &(WOutDev[dsdb->drv->wDevID]);
1305     if (!wwo->mapping) {
1306         wwo->mapping = mmap(NULL, wwo->maplen, PROT_WRITE, MAP_SHARED,
1307                             wwo->unixdev, 0);
1308         if (wwo->mapping == (LPBYTE)-1) {
1309             ERR("(%p): Could not map sound device for direct access (errno=%d)\n", dsdb, errno);
1310             return DSERR_GENERIC;
1311         }
1312         TRACE("(%p): sound device has been mapped for direct access at %p, size=%ld\n", dsdb, wwo->mapping, wwo->maplen);
1313
1314         /* for some reason, es1371 and sblive! sometimes have junk in here. */
1315         memset(wwo->mapping,0,wwo->maplen); /* clear it, or we get junk noise */
1316     }
1317     return DS_OK;
1318 }
1319
1320 static HRESULT DSDB_UnmapPrimary(IDsDriverBufferImpl *dsdb)
1321 {
1322     WINE_WAVEOUT *wwo = &(WOutDev[dsdb->drv->wDevID]);
1323     if (wwo->mapping) {
1324         if (munmap(wwo->mapping, wwo->maplen) < 0) {
1325             ERR("(%p): Could not unmap sound device (errno=%d)\n", dsdb, errno);
1326             return DSERR_GENERIC;
1327         }
1328         wwo->mapping = NULL;
1329         TRACE("(%p): sound device unmapped\n", dsdb);
1330     }
1331     return DS_OK;
1332 }
1333
1334 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
1335 {
1336     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1337     FIXME("(): stub!\n");
1338     return DSERR_UNSUPPORTED;
1339 }
1340
1341 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
1342 {
1343     ICOM_THIS(IDsDriverBufferImpl,iface);
1344     This->ref++;
1345     return This->ref;
1346 }
1347
1348 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
1349 {
1350     ICOM_THIS(IDsDriverBufferImpl,iface);
1351     if (--This->ref)
1352         return This->ref;
1353     if (This == This->drv->primary)
1354         This->drv->primary = NULL;
1355     DSDB_UnmapPrimary(This);
1356     HeapFree(GetProcessHeap(),0,This);
1357     return 0;
1358 }
1359
1360 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
1361                                                LPVOID*ppvAudio1,LPDWORD pdwLen1,
1362                                                LPVOID*ppvAudio2,LPDWORD pdwLen2,
1363                                                DWORD dwWritePosition,DWORD dwWriteLen,
1364                                                DWORD dwFlags)
1365 {
1366     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1367     /* since we (GetDriverDesc flags) have specified DSDDESC_DONTNEEDPRIMARYLOCK,
1368      * and that we don't support secondary buffers, this method will never be called */
1369     TRACE("(%p): stub\n",iface);
1370     return DSERR_UNSUPPORTED;
1371 }
1372
1373 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
1374                                                  LPVOID pvAudio1,DWORD dwLen1,
1375                                                  LPVOID pvAudio2,DWORD dwLen2)
1376 {
1377     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1378     TRACE("(%p): stub\n",iface);
1379     return DSERR_UNSUPPORTED;
1380 }
1381
1382 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
1383                                                     LPWAVEFORMATEX pwfx)
1384 {
1385     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1386
1387     TRACE("(%p,%p)\n",iface,pwfx);
1388     /* On our request (GetDriverDesc flags), DirectSound has by now used
1389      * waveOutClose/waveOutOpen to set the format...
1390      * unfortunately, this means our mmap() is now gone...
1391      * so we need to somehow signal to our DirectSound implementation
1392      * that it should completely recreate this HW buffer...
1393      * this unexpected error code should do the trick... */
1394     return DSERR_BUFFERLOST;
1395 }
1396
1397 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
1398 {
1399     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1400     TRACE("(%p,%ld): stub\n",iface,dwFreq);
1401     return DSERR_UNSUPPORTED;
1402 }
1403
1404 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
1405 {
1406     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1407     FIXME("(%p,%p): stub!\n",iface,pVolPan);
1408     return DSERR_UNSUPPORTED;
1409 }
1410
1411 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
1412 {
1413     /* ICOM_THIS(IDsDriverImpl,iface); */
1414     TRACE("(%p,%ld): stub\n",iface,dwNewPos);
1415     return DSERR_UNSUPPORTED;
1416 }
1417
1418 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
1419                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
1420 {
1421     ICOM_THIS(IDsDriverBufferImpl,iface);
1422     count_info info;
1423     DWORD ptr;
1424
1425     TRACE("(%p)\n",iface);
1426     if (WOutDev[This->drv->wDevID].unixdev == -1) {
1427         ERR("device not open, but accessing?\n");
1428         return DSERR_UNINITIALIZED;
1429     }
1430     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_GETOPTR, &info) < 0) {
1431         ERR("ioctl failed (%d)\n", errno);
1432         return DSERR_GENERIC;
1433     }
1434     ptr = info.ptr & ~3; /* align the pointer, just in case */
1435     if (lpdwPlay) *lpdwPlay = ptr;
1436     if (lpdwWrite) {
1437         /* add some safety margin (not strictly necessary, but...) */
1438         if (WOutDev[This->drv->wDevID].caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
1439             *lpdwWrite = ptr + 32;
1440         else
1441             *lpdwWrite = ptr + WOutDev[This->drv->wDevID].dwFragmentSize;
1442         while (*lpdwWrite > This->buflen)
1443             *lpdwWrite -= This->buflen;
1444     }
1445     TRACE("playpos=%ld, writepos=%ld\n", lpdwPlay?*lpdwPlay:0, lpdwWrite?*lpdwWrite:0);
1446     return DS_OK;
1447 }
1448
1449 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
1450 {
1451     ICOM_THIS(IDsDriverBufferImpl,iface);
1452     int enable = PCM_ENABLE_OUTPUT;
1453     TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
1454     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1455         ERR("ioctl failed (%d)\n", errno);
1456         return DSERR_GENERIC;
1457     }
1458     return DS_OK;
1459 }
1460
1461 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
1462 {
1463     ICOM_THIS(IDsDriverBufferImpl,iface);
1464     int enable = 0;
1465     TRACE("(%p)\n",iface);
1466     /* no more playing */
1467     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1468         ERR("ioctl failed (%d)\n", errno);
1469         return DSERR_GENERIC;
1470     }
1471 #if 0
1472     /* the play position must be reset to the beginning of the buffer */
1473     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_RESET, 0) < 0) {
1474         ERR("ioctl failed (%d)\n", errno);
1475         return DSERR_GENERIC;
1476     }
1477 #endif
1478     /* Most OSS drivers just can't stop the playback without closing the device...
1479      * so we need to somehow signal to our DirectSound implementation
1480      * that it should completely recreate this HW buffer...
1481      * this unexpected error code should do the trick... */
1482     return DSERR_BUFFERLOST;
1483 }
1484
1485 static ICOM_VTABLE(IDsDriverBuffer) dsdbvt =
1486 {
1487     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1488     IDsDriverBufferImpl_QueryInterface,
1489     IDsDriverBufferImpl_AddRef,
1490     IDsDriverBufferImpl_Release,
1491     IDsDriverBufferImpl_Lock,
1492     IDsDriverBufferImpl_Unlock,
1493     IDsDriverBufferImpl_SetFormat,
1494     IDsDriverBufferImpl_SetFrequency,
1495     IDsDriverBufferImpl_SetVolumePan,
1496     IDsDriverBufferImpl_SetPosition,
1497     IDsDriverBufferImpl_GetPosition,
1498     IDsDriverBufferImpl_Play,
1499     IDsDriverBufferImpl_Stop
1500 };
1501
1502 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
1503 {
1504     /* ICOM_THIS(IDsDriverImpl,iface); */
1505     FIXME("(%p): stub!\n",iface);
1506     return DSERR_UNSUPPORTED;
1507 }
1508
1509 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
1510 {
1511     ICOM_THIS(IDsDriverImpl,iface);
1512     This->ref++;
1513     return This->ref;
1514 }
1515
1516 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
1517 {
1518     ICOM_THIS(IDsDriverImpl,iface);
1519     if (--This->ref)
1520         return This->ref;
1521     HeapFree(GetProcessHeap(),0,This);
1522     return 0;
1523 }
1524
1525 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
1526 {
1527     ICOM_THIS(IDsDriverImpl,iface);
1528     TRACE("(%p,%p)\n",iface,pDesc);
1529     pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
1530         DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK;
1531     strcpy(pDesc->szDesc,"WineOSS DirectSound Driver");
1532     strcpy(pDesc->szDrvName,"wineoss.drv");
1533     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
1534     pDesc->wVxdId               = 0; 
1535     pDesc->wReserved            = 0;
1536     pDesc->ulDeviceNum          = This->wDevID;
1537     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
1538     pDesc->pvDirectDrawHeap     = NULL;
1539     pDesc->dwMemStartAddress    = 0;
1540     pDesc->dwMemEndAddress      = 0;
1541     pDesc->dwMemAllocExtra      = 0;
1542     pDesc->pvReserved1          = NULL;
1543     pDesc->pvReserved2          = NULL;
1544     return DS_OK;
1545 }
1546
1547 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
1548 {
1549     ICOM_THIS(IDsDriverImpl,iface);
1550     int enable = 0;
1551
1552     TRACE("(%p)\n",iface);
1553     /* make sure the card doesn't start playing before we want it to */
1554     if (ioctl(WOutDev[This->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1555         ERR("ioctl failed (%d)\n", errno);
1556         return DSERR_GENERIC;
1557     }
1558     return DS_OK;
1559 }
1560
1561 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
1562 {
1563     ICOM_THIS(IDsDriverImpl,iface);
1564     TRACE("(%p)\n",iface);
1565     if (This->primary) {
1566         ERR("problem with DirectSound: primary not released\n");
1567         return DSERR_GENERIC;
1568     }
1569     return DS_OK;
1570 }
1571
1572 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
1573 {
1574     /* ICOM_THIS(IDsDriverImpl,iface); */
1575     TRACE("(%p,%p)\n",iface,pCaps);
1576     memset(pCaps, 0, sizeof(*pCaps));
1577     /* FIXME: need to check actual capabilities */
1578     pCaps->dwFlags = DSCAPS_PRIMARYMONO | DSCAPS_PRIMARYSTEREO |
1579         DSCAPS_PRIMARY8BIT | DSCAPS_PRIMARY16BIT;
1580     pCaps->dwPrimaryBuffers = 1;
1581     /* the other fields only apply to secondary buffers, which we don't support
1582      * (unless we want to mess with wavetable synthesizers and MIDI) */
1583     return DS_OK;
1584 }
1585
1586 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
1587                                                       LPWAVEFORMATEX pwfx,
1588                                                       DWORD dwFlags, DWORD dwCardAddress,
1589                                                       LPDWORD pdwcbBufferSize,
1590                                                       LPBYTE *ppbBuffer,
1591                                                       LPVOID *ppvObj)
1592 {
1593     ICOM_THIS(IDsDriverImpl,iface);
1594     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
1595     HRESULT err;
1596     audio_buf_info info;
1597     int enable = 0;
1598
1599     TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
1600     /* we only support primary buffers */
1601     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
1602         return DSERR_UNSUPPORTED;
1603     if (This->primary)
1604         return DSERR_ALLOCATED;
1605     if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
1606         return DSERR_CONTROLUNAVAIL;
1607
1608     *ippdsdb = (IDsDriverBufferImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
1609     if (*ippdsdb == NULL)
1610         return DSERR_OUTOFMEMORY;
1611     ICOM_VTBL(*ippdsdb) = &dsdbvt;
1612     (*ippdsdb)->ref     = 1;
1613     (*ippdsdb)->drv     = This;
1614
1615     /* check how big the DMA buffer is now */
1616     if (ioctl(WOutDev[This->wDevID].unixdev, SNDCTL_DSP_GETOSPACE, &info) < 0) {
1617         ERR("ioctl failed (%d)\n", errno);
1618         HeapFree(GetProcessHeap(),0,*ippdsdb);
1619         *ippdsdb = NULL;
1620         return DSERR_GENERIC;
1621     }
1622     WOutDev[This->wDevID].maplen = (*ippdsdb)->buflen = info.fragstotal * info.fragsize;
1623
1624     /* map the DMA buffer */
1625     err = DSDB_MapPrimary(*ippdsdb);
1626     if (err != DS_OK) {
1627         HeapFree(GetProcessHeap(),0,*ippdsdb);
1628         *ippdsdb = NULL;
1629         return err;
1630     }
1631
1632     /* primary buffer is ready to go */
1633     *pdwcbBufferSize    = WOutDev[This->wDevID].maplen;
1634     *ppbBuffer          = WOutDev[This->wDevID].mapping;
1635
1636     /* some drivers need some extra nudging after mapping */
1637     if (ioctl(WOutDev[This->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1638         ERR("ioctl failed (%d)\n", errno);
1639         return DSERR_GENERIC;
1640     }
1641
1642     This->primary = *ippdsdb;
1643
1644     return DS_OK;
1645 }
1646
1647 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
1648                                                          PIDSDRIVERBUFFER pBuffer,
1649                                                          LPVOID *ppvObj)
1650 {
1651     /* ICOM_THIS(IDsDriverImpl,iface); */
1652     TRACE("(%p,%p): stub\n",iface,pBuffer);
1653     return DSERR_INVALIDCALL;
1654 }
1655
1656 static ICOM_VTABLE(IDsDriver) dsdvt =
1657 {
1658     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1659     IDsDriverImpl_QueryInterface,
1660     IDsDriverImpl_AddRef,
1661     IDsDriverImpl_Release,
1662     IDsDriverImpl_GetDriverDesc,
1663     IDsDriverImpl_Open,
1664     IDsDriverImpl_Close,
1665     IDsDriverImpl_GetCaps,
1666     IDsDriverImpl_CreateSoundBuffer,
1667     IDsDriverImpl_DuplicateSoundBuffer
1668 };
1669
1670 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1671 {
1672     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
1673
1674     /* the HAL isn't much better than the HEL if we can't do mmap() */
1675     if (!(WOutDev[wDevID].caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
1676         ERR("DirectSound flag not set\n");
1677         MESSAGE("This sound card's driver does not support direct access\n");
1678         MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
1679         return MMSYSERR_NOTSUPPORTED;
1680     }
1681
1682     *idrv = (IDsDriverImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
1683     if (!*idrv)
1684         return MMSYSERR_NOMEM;
1685     ICOM_VTBL(*idrv)    = &dsdvt;
1686     (*idrv)->ref        = 1;
1687
1688     (*idrv)->wDevID     = wDevID;
1689     (*idrv)->primary    = NULL;
1690     return MMSYSERR_NOERROR;
1691 }
1692
1693 /*======================================================================*
1694  *                  Low level WAVE IN implementation                    *
1695  *======================================================================*/
1696
1697 /**************************************************************************
1698  *                      widGetDevCaps                           [internal]
1699  */
1700 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSA lpCaps, DWORD dwSize)
1701 {
1702     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1703     
1704     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1705     
1706     if (wDevID >= MAX_WAVEINDRV) {
1707         TRACE("MAX_WAVINDRV reached !\n");
1708         return MMSYSERR_BADDEVICEID;
1709     }
1710
1711     memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1712     return MMSYSERR_NOERROR;
1713 }
1714
1715 /**************************************************************************
1716  *                              widRecorder                     [internal]
1717  */
1718 static  DWORD   CALLBACK        widRecorder(LPVOID pmt)
1719 {
1720     WORD                uDevID = (DWORD)pmt;
1721     WINE_WAVEIN*        wwi = (WINE_WAVEIN*)&WInDev[uDevID];
1722     WAVEHDR*            lpWaveHdr;
1723     DWORD               dwSleepTime;
1724     MSG                 msg;
1725     DWORD               bytesRead;
1726
1727     audio_buf_info info;
1728     int xs;
1729         
1730         LPVOID          buffer = HeapAlloc(GetProcessHeap(), 
1731                                            HEAP_ZERO_MEMORY, 
1732                                        wwi->dwFragmentSize);
1733
1734     LPVOID              pOffset = buffer;
1735
1736     PeekMessageA(&msg, 0, 0, 0, 0);
1737     wwi->state = WINE_WS_STOPPED;
1738     wwi->dwTotalRecorded = 0;
1739
1740     SetEvent(wwi->hEvent);
1741
1742     /* the soundblaster live needs a micro wake to get its recording started
1743      * (or GETISPACE will have 0 frags all the time)
1744      */
1745     read(wwi->unixdev,&xs,4);
1746     
1747         /* make sleep time to be # of ms to output a fragment */
1748     dwSleepTime = (wwi->dwFragmentSize * 1000) / wwi->format.wf.nAvgBytesPerSec;
1749     TRACE("sleeptime=%ld ms\n", dwSleepTime);
1750
1751     for (; ; ) {
1752         /* wait for dwSleepTime or an event in thread's queue */
1753         /* FIXME: could improve wait time depending on queue state,
1754          * ie, number of queued fragments
1755          */
1756
1757         if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING) 
1758         {
1759             lpWaveHdr = wwi->lpQueuePtr;
1760
1761             ioctl(wwi->unixdev, SNDCTL_DSP_GETISPACE, &info);
1762             TRACE("info={frag=%d fsize=%d ftotal=%d bytes=%d}\n", info.fragments, info.fragsize, info.fragstotal, info.bytes);
1763
1764             /* read all the fragments accumulated so far */
1765             while ((info.fragments > 0) && (wwi->lpQueuePtr))
1766             {
1767                 info.fragments --;
1768
1769                 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwFragmentSize)
1770                 {
1771                     /* directly read fragment in wavehdr */
1772                     bytesRead = read(wwi->unixdev, 
1773                                      lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded, 
1774                                      wwi->dwFragmentSize);
1775
1776                     TRACE("bytesRead=%ld (direct)\n", bytesRead);
1777                     if (bytesRead != (DWORD) -1)
1778                     {
1779                         /* update number of bytes recorded in current buffer and by this device */
1780                         lpWaveHdr->dwBytesRecorded += bytesRead;
1781                         wwi->dwTotalRecorded       += bytesRead;
1782                                 
1783                         /* buffer is full. notify client */
1784                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength) 
1785                         {
1786                             /* must copy the value of next waveHdr, because we have no idea of what
1787                              * will be done with the content of lpWaveHdr in callback
1788                              */
1789                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
1790
1791                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1792                             lpWaveHdr->dwFlags |=  WHDR_DONE;
1793
1794                             if (OSS_NotifyClient(uDevID, WIM_DATA, 
1795                                                  (DWORD)lpWaveHdr, 0) != MMSYSERR_NOERROR) 
1796                             {
1797                                 WARN("can't notify client !\n");
1798                             }
1799                             lpWaveHdr = wwi->lpQueuePtr = lpNext;
1800                         }
1801                     }
1802                 }
1803                 else
1804                 {
1805                     /* read the fragment in a local buffer */
1806                     bytesRead = read(wwi->unixdev, buffer, wwi->dwFragmentSize);
1807                     pOffset = buffer;
1808
1809                     TRACE("bytesRead=%ld (local)\n", bytesRead);
1810
1811                     /* copy data in client buffers */   
1812                     while (bytesRead != (DWORD) -1 && bytesRead > 0)
1813                     {
1814                         DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
1815
1816                         memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
1817                                pOffset,
1818                                dwToCopy);
1819
1820                         /* update number of bytes recorded in current buffer and by this device */
1821                         lpWaveHdr->dwBytesRecorded += dwToCopy;
1822                         wwi->dwTotalRecorded += dwToCopy;
1823                         bytesRead -= dwToCopy;
1824                         pOffset   += dwToCopy;
1825                                 
1826                         /* client buffer is full. notify client */
1827                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength) 
1828                         {
1829                             /* must copy the value of next waveHdr, because we have no idea of what
1830                              * will be done with the content of lpWaveHdr in callback
1831                              */
1832                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
1833                             TRACE("lpNext=%p\n", lpNext);
1834
1835                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1836                             lpWaveHdr->dwFlags |=  WHDR_DONE;
1837
1838                             if (OSS_NotifyClient(uDevID, WIM_DATA, 
1839                                                  (DWORD)lpWaveHdr, 0) != MMSYSERR_NOERROR) 
1840                             {
1841                                 WARN("can't notify client !\n");
1842                             }
1843                                    
1844                             wwi->lpQueuePtr = lpWaveHdr = lpNext;
1845                             if (!lpNext && bytesRead) {
1846                                 /* no more buffer to copy data to, but we did read more. 
1847                                  * what hasn't been copied will be dropped
1848                                  */ 
1849                                 WARN("buffer under run! %lu bytes dropped.\n", bytesRead);
1850                                 wwi->lpQueuePtr = NULL;
1851                                 break;
1852                             }
1853                         }
1854                     }
1855                 }
1856             }
1857         }
1858         
1859         MsgWaitForMultipleObjects(0, NULL, FALSE, dwSleepTime, QS_POSTMESSAGE);
1860
1861         while (PeekMessageA(&msg, 0, WINE_WM_FIRST, WINE_WM_LAST, PM_REMOVE)) {
1862
1863             TRACE("msg=0x%x wParam=0x%x lParam=0x%lx\n", msg.message, msg.wParam, msg.lParam);
1864             switch (msg.message) {
1865             case WINE_WM_PAUSING:
1866                 wwi->state = WINE_WS_PAUSED;
1867                 /*FIXME("Device should stop recording\n");*/
1868                 SetEvent(wwi->hEvent);
1869                 break;
1870             case WINE_WM_RESTARTING:
1871             {
1872                 int enable = PCM_ENABLE_INPUT;
1873                 wwi->state = WINE_WS_PLAYING;
1874
1875                 if (wwi->bTriggerSupport)
1876                 {
1877                     /* start the recording */
1878                     if (ioctl(wwi->unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) 
1879                     {
1880                         ERR("ioctl(SNDCTL_DSP_SETTRIGGER) failed (%d)\n", errno);
1881                     }
1882                 }
1883                 else
1884                 {
1885                     unsigned char data[4];
1886                     /* read 4 bytes to start the recording */
1887                     read(wwi->unixdev, data, 4);
1888                 }
1889                 
1890                 SetEvent(wwi->hEvent);
1891                 break;
1892             }
1893             case WINE_WM_HEADER:
1894                 lpWaveHdr = (LPWAVEHDR)msg.lParam;
1895                 lpWaveHdr->lpNext = 0;
1896
1897                 /* insert buffer at the end of queue */
1898                 {
1899                     LPWAVEHDR*  wh;
1900                     for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1901                     *wh = lpWaveHdr;
1902                 }
1903                 break;
1904             case WINE_WM_RESETTING:
1905                 wwi->state = WINE_WS_STOPPED;
1906                 /* return all buffers to the app */
1907                 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
1908                     TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
1909                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1910                     lpWaveHdr->dwFlags |= WHDR_DONE;
1911         
1912                     if (OSS_NotifyClient(uDevID, WIM_DATA, 
1913                                          (DWORD)lpWaveHdr, 0) != MMSYSERR_NOERROR) {
1914                         WARN("can't notify client !\n");
1915                     }
1916                 }
1917                 wwi->lpQueuePtr = NULL;
1918                 SetEvent(wwi->hEvent);
1919                 break;
1920             case WINE_WM_CLOSING:
1921                 wwi->hThread = 0;
1922                 wwi->state = WINE_WS_CLOSED;
1923                 SetEvent(wwi->hEvent);
1924                 HeapFree(GetProcessHeap(), 0, buffer); 
1925                 ExitThread(0);
1926                 /* shouldn't go here */
1927             default:
1928                 FIXME("unknown message %d\n", msg.message);
1929                 break;
1930             }
1931         }
1932     }
1933     ExitThread(0);
1934     /* just for not generating compilation warnings... should never be executed */
1935     return 0; 
1936 }
1937
1938
1939 /**************************************************************************
1940  *                              widOpen                         [internal]
1941  */
1942 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1943 {
1944     int                 audio;
1945     int                 fragment_size;
1946     int                 sample_rate;
1947     int                 format;
1948     int                 dsp_stereo;
1949     WINE_WAVEIN*        wwi;
1950     int                 audio_fragment;
1951
1952     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
1953     if (lpDesc == NULL) {
1954         WARN("Invalid Parameter !\n");
1955         return MMSYSERR_INVALPARAM;
1956     }
1957     if (wDevID >= MAX_WAVEINDRV) return MMSYSERR_BADDEVICEID;
1958
1959     /* only PCM format is supported so far... */
1960     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1961         lpDesc->lpFormat->nChannels == 0 ||
1962         lpDesc->lpFormat->nSamplesPerSec == 0) {
1963         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n", 
1964              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1965              lpDesc->lpFormat->nSamplesPerSec);
1966         return WAVERR_BADFORMAT;
1967     }
1968
1969     if (dwFlags & WAVE_FORMAT_QUERY) {
1970         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n", 
1971              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1972              lpDesc->lpFormat->nSamplesPerSec);
1973         return MMSYSERR_NOERROR;
1974     }
1975
1976     if (access(SOUND_DEV,0) != 0) return MMSYSERR_NOTENABLED;
1977     audio = open(SOUND_DEV, O_RDONLY|O_NDELAY, 0);
1978     if (audio == -1) {
1979         WARN("can't open sound device %s (%s)!\n", SOUND_DEV, strerror(errno));
1980         return MMSYSERR_ALLOCATED;
1981     }
1982     fcntl(audio, F_SETFD, 1); /* set close on exec flag */
1983
1984     wwi = &WInDev[wDevID];
1985     if (wwi->lpQueuePtr) {
1986         WARN("Should have an empty queue (%p)\n", wwi->lpQueuePtr);
1987         wwi->lpQueuePtr = NULL;
1988     }
1989     wwi->unixdev = audio;
1990     wwi->dwTotalRecorded = 0;
1991     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1992
1993     memcpy(&wwi->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
1994     memcpy(&wwi->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1995
1996     if (wwi->format.wBitsPerSample == 0) {
1997         WARN("Resetting zeroed wBitsPerSample\n");
1998         wwi->format.wBitsPerSample = 8 *
1999             (wwi->format.wf.nAvgBytesPerSec /
2000              wwi->format.wf.nSamplesPerSec) /
2001             wwi->format.wf.nChannels;
2002     }
2003
2004     sample_rate = wwi->format.wf.nSamplesPerSec;
2005     dsp_stereo = (wwi->format.wf.nChannels > 1) ? TRUE : FALSE;
2006     format = (wwi->format.wBitsPerSample == 16) ? AFMT_S16_LE : AFMT_U8;
2007
2008
2009     IOCTL(audio, SNDCTL_DSP_SETFMT, format);
2010     IOCTL(audio, SNDCTL_DSP_STEREO, dsp_stereo);
2011     IOCTL(audio, SNDCTL_DSP_SPEED,  sample_rate);
2012
2013
2014     /* This is actually hand tuned to work so that my SB Live:
2015      * - does not skip
2016      * - does not buffer too much
2017      * when sending with the Shoutcast winamp plugin
2018      */
2019     /* 7 fragments max, 2^10 = 1024 bytes per fragment */
2020     audio_fragment = 0x0007000A;
2021     IOCTL(audio, SNDCTL_DSP_SETFRAGMENT, audio_fragment);
2022
2023     /* paranoid checks */
2024     if (format != ((wwi->format.wBitsPerSample == 16) ? AFMT_S16_LE : AFMT_U8))
2025         ERR("Can't set format to %d (%d)\n", 
2026             (wwi->format.wBitsPerSample == 16) ? AFMT_S16_LE : AFMT_U8, format);
2027     if (dsp_stereo != (wwi->format.wf.nChannels > 1) ? 1 : 0) 
2028         ERR("Can't set stereo to %u (%d)\n", 
2029             (wwi->format.wf.nChannels > 1) ? 1 : 0, dsp_stereo);
2030     if (!NEAR_MATCH(sample_rate, wwi->format.wf.nSamplesPerSec))
2031         ERR("Can't set sample_rate to %lu (%d)\n", 
2032             wwi->format.wf.nSamplesPerSec, sample_rate);
2033
2034     IOCTL(audio, SNDCTL_DSP_GETBLKSIZE, fragment_size);
2035     if (fragment_size == -1) {
2036         WARN("IOCTL can't 'SNDCTL_DSP_GETBLKSIZE' !\n");
2037         close(audio);
2038         wwi->unixdev = -1;
2039         return MMSYSERR_NOTENABLED;
2040     }
2041     wwi->dwFragmentSize = fragment_size;
2042
2043     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n", 
2044           wwi->format.wBitsPerSample, wwi->format.wf.nAvgBytesPerSec, 
2045           wwi->format.wf.nSamplesPerSec, wwi->format.wf.nChannels,
2046           wwi->format.wf.nBlockAlign);
2047
2048     wwi->hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
2049     wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
2050     WaitForSingleObject(wwi->hEvent, INFINITE);
2051
2052    if (OSS_NotifyClient(wDevID, WIM_OPEN, 0L, 0L) != MMSYSERR_NOERROR) {
2053         WARN("can't notify client !\n");
2054         return MMSYSERR_INVALPARAM;
2055     }
2056     return MMSYSERR_NOERROR;
2057 }
2058
2059 /**************************************************************************
2060  *                              widClose                        [internal]
2061  */
2062 static DWORD widClose(WORD wDevID)
2063 {
2064     WINE_WAVEIN*        wwi;
2065
2066     TRACE("(%u);\n", wDevID);
2067     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2068         WARN("can't close !\n");
2069         return MMSYSERR_INVALHANDLE;
2070     }
2071
2072     wwi = &WInDev[wDevID];
2073
2074     if (wwi->lpQueuePtr != NULL) {
2075         WARN("still buffers open !\n");
2076         return WAVERR_STILLPLAYING;
2077     }
2078
2079     PostThreadMessageA(wwi->dwThreadID, WINE_WM_CLOSING, 0, 0);
2080     WaitForSingleObject(wwi->hEvent, INFINITE);
2081     CloseHandle(wwi->hEvent);
2082     close(wwi->unixdev);
2083     wwi->unixdev = -1;
2084     wwi->dwFragmentSize = 0;
2085     if (OSS_NotifyClient(wDevID, WIM_CLOSE, 0L, 0L) != MMSYSERR_NOERROR) {
2086         WARN("can't notify client !\n");
2087         return MMSYSERR_INVALPARAM;
2088     }
2089     return MMSYSERR_NOERROR;
2090 }
2091
2092 /**************************************************************************
2093  *                              widAddBuffer            [internal]
2094  */
2095 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2096 {
2097     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2098
2099     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2100         WARN("can't do it !\n");
2101         return MMSYSERR_INVALHANDLE;
2102     }
2103     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED)) {
2104         TRACE("never been prepared !\n");
2105         return WAVERR_UNPREPARED;
2106     }
2107     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) {
2108         TRACE("header already in use !\n");
2109         return WAVERR_STILLPLAYING;
2110     }
2111
2112     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2113     lpWaveHdr->dwFlags &= ~WHDR_DONE;
2114     lpWaveHdr->dwBytesRecorded = 0;
2115         lpWaveHdr->lpNext = NULL;
2116         
2117     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_HEADER, 0, (DWORD)lpWaveHdr);
2118     return MMSYSERR_NOERROR;
2119 }
2120
2121 /**************************************************************************
2122  *                              widPrepare                      [internal]
2123  */
2124 static DWORD widPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2125 {
2126     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2127
2128     if (wDevID >= MAX_WAVEINDRV) return MMSYSERR_INVALHANDLE;
2129
2130     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2131         return WAVERR_STILLPLAYING;
2132
2133     lpWaveHdr->dwFlags |= WHDR_PREPARED;
2134     lpWaveHdr->dwFlags &= ~(WHDR_INQUEUE|WHDR_DONE);
2135     lpWaveHdr->dwBytesRecorded = 0;
2136     TRACE("header prepared !\n");
2137     return MMSYSERR_NOERROR;
2138 }
2139
2140 /**************************************************************************
2141  *                              widUnprepare                    [internal]
2142  */
2143 static DWORD widUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2144 {
2145     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2146     if (wDevID >= MAX_WAVEINDRV) return MMSYSERR_INVALHANDLE;
2147
2148     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2149         return WAVERR_STILLPLAYING;
2150
2151     lpWaveHdr->dwFlags &= ~(WHDR_PREPARED|WHDR_INQUEUE);
2152     lpWaveHdr->dwFlags |= WHDR_DONE;
2153     
2154     return MMSYSERR_NOERROR;
2155 }
2156
2157 /**************************************************************************
2158  *                      widStart                                [internal]
2159  */
2160 static DWORD widStart(WORD wDevID)
2161 {
2162     TRACE("(%u);\n", wDevID);
2163     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2164         WARN("can't start recording !\n");
2165         return MMSYSERR_INVALHANDLE;
2166     }
2167
2168     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_RESTARTING, 0, 0);
2169     WaitForSingleObject(WInDev[wDevID].hEvent, INFINITE);
2170     return MMSYSERR_NOERROR;
2171 }
2172
2173 /**************************************************************************
2174  *                      widStop                                 [internal]
2175  */
2176 static DWORD widStop(WORD wDevID)
2177 {
2178     TRACE("(%u);\n", wDevID);
2179     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2180         WARN("can't stop !\n");
2181         return MMSYSERR_INVALHANDLE;
2182     }
2183     /* FIXME: reset aint stop */
2184     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_RESETTING, 0, 0);
2185     WaitForSingleObject(WInDev[wDevID].hEvent, INFINITE);
2186     
2187     return MMSYSERR_NOERROR;
2188 }
2189
2190 /**************************************************************************
2191  *                      widReset                                [internal]
2192  */
2193 static DWORD widReset(WORD wDevID)
2194 {
2195     TRACE("(%u);\n", wDevID);
2196     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2197         WARN("can't reset !\n");
2198         return MMSYSERR_INVALHANDLE;
2199     }
2200     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_RESETTING, 0, 0);
2201     WaitForSingleObject(WInDev[wDevID].hEvent, INFINITE);
2202     return MMSYSERR_NOERROR;
2203 }
2204
2205 /**************************************************************************
2206  *                              widGetPosition                  [internal]
2207  */
2208 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
2209 {
2210     int                 time;
2211     WINE_WAVEIN*        wwi;
2212     
2213     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
2214
2215     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2216         WARN("can't get pos !\n");
2217         return MMSYSERR_INVALHANDLE;
2218     }
2219     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
2220
2221     wwi = &WInDev[wDevID];
2222
2223     TRACE("wType=%04X !\n", lpTime->wType);
2224     TRACE("wBitsPerSample=%u\n", wwi->format.wBitsPerSample); 
2225     TRACE("nSamplesPerSec=%lu\n", wwi->format.wf.nSamplesPerSec); 
2226     TRACE("nChannels=%u\n", wwi->format.wf.nChannels); 
2227     TRACE("nAvgBytesPerSec=%lu\n", wwi->format.wf.nAvgBytesPerSec); 
2228     switch (lpTime->wType) {
2229     case TIME_BYTES:
2230         lpTime->u.cb = wwi->dwTotalRecorded;
2231         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
2232         break;
2233     case TIME_SAMPLES:
2234         lpTime->u.sample = wwi->dwTotalRecorded * 8 /
2235             wwi->format.wBitsPerSample;
2236         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
2237         break;
2238     case TIME_SMPTE:
2239         time = wwi->dwTotalRecorded /
2240             (wwi->format.wf.nAvgBytesPerSec / 1000);
2241         lpTime->u.smpte.hour = time / 108000;
2242         time -= lpTime->u.smpte.hour * 108000;
2243         lpTime->u.smpte.min = time / 1800;
2244         time -= lpTime->u.smpte.min * 1800;
2245         lpTime->u.smpte.sec = time / 30;
2246         time -= lpTime->u.smpte.sec * 30;
2247         lpTime->u.smpte.frame = time;
2248         lpTime->u.smpte.fps = 30;
2249         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
2250               lpTime->u.smpte.hour, lpTime->u.smpte.min,
2251               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
2252         break;
2253     case TIME_MS:
2254         lpTime->u.ms = wwi->dwTotalRecorded /
2255             (wwi->format.wf.nAvgBytesPerSec / 1000);
2256         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
2257         break;
2258     default:
2259         FIXME("format not supported (%u) ! use TIME_MS !\n", lpTime->wType);
2260         lpTime->wType = TIME_MS;
2261     }
2262     return MMSYSERR_NOERROR;
2263 }
2264
2265 /**************************************************************************
2266  *                              OSS_widMessage                  [sample driver]
2267  */
2268 DWORD WINAPI OSS_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser, 
2269                             DWORD dwParam1, DWORD dwParam2)
2270 {
2271     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
2272           wDevID, wMsg, dwUser, dwParam1, dwParam2);
2273
2274     switch (wMsg) {
2275     case DRVM_INIT:
2276     case DRVM_EXIT:
2277     case DRVM_ENABLE:
2278     case DRVM_DISABLE:
2279         /* FIXME: Pretend this is supported */
2280         return 0;
2281     case WIDM_OPEN:             return widOpen       (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2282     case WIDM_CLOSE:            return widClose      (wDevID);
2283     case WIDM_ADDBUFFER:        return widAddBuffer  (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2284     case WIDM_PREPARE:          return widPrepare    (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2285     case WIDM_UNPREPARE:        return widUnprepare  (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2286     case WIDM_GETDEVCAPS:       return widGetDevCaps (wDevID, (LPWAVEINCAPSA)dwParam1, dwParam2);
2287     case WIDM_GETNUMDEVS:       return wodGetNumDevs ();        /* same number of devices in output as in input */
2288     case WIDM_GETPOS:           return widGetPosition(wDevID, (LPMMTIME)dwParam1, dwParam2);
2289     case WIDM_RESET:            return widReset      (wDevID);
2290     case WIDM_START:            return widStart      (wDevID);
2291     case WIDM_STOP:             return widStop       (wDevID);
2292     default:
2293         FIXME("unknown message %u!\n", wMsg);
2294     }
2295     return MMSYSERR_NOTSUPPORTED;
2296 }
2297
2298 #else /* !HAVE_OSS */
2299
2300 /**************************************************************************
2301  *                              OSS_wodMessage                  [sample driver]
2302  */
2303 DWORD WINAPI OSS_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser, 
2304                             DWORD dwParam1, DWORD dwParam2)
2305 {
2306     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2307     return MMSYSERR_NOTENABLED;
2308 }
2309
2310 /**************************************************************************
2311  *                              OSS_widMessage                  [sample driver]
2312  */
2313 DWORD WINAPI OSS_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser, 
2314                             DWORD dwParam1, DWORD dwParam2)
2315 {
2316     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2317     return MMSYSERR_NOTENABLED;
2318 }
2319
2320 #endif /* HAVE_OSS */