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