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