Removed some unnecessary includes.
[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                 WOutDev[0].caps.dwSupport |= WAVECAPS_DIRECTSOUND;
260         }
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         /* with DirectSound, fragments are irrelevant, but a large buffer isn't...
825          * so let's choose a full 64KB (32 * 2^11) for DirectSound */
826         audio_fragment = 0x0020000B;
827     } else {
828         /* shockwave player uses only 4 1k-fragments at a rate of 22050 bytes/sec
829          * thus leading to 46ms per fragment, and a turnaround time of 185ms
830          */
831         /* 16 fragments max, 2^10=1024 bytes per fragment */
832         audio_fragment = 0x000F000A;
833     }
834     sample_rate = wwo->format.wf.nSamplesPerSec;
835     dsp_stereo = (wwo->format.wf.nChannels > 1) ? 1 : 0;
836     format = (wwo->format.wBitsPerSample == 16) ? AFMT_S16_LE : AFMT_U8;
837
838     IOCTL(audio, SNDCTL_DSP_SETFRAGMENT, audio_fragment);
839     /* First size and stereo then samplerate */
840     IOCTL(audio, SNDCTL_DSP_SETFMT, format);
841     IOCTL(audio, SNDCTL_DSP_STEREO, dsp_stereo);
842     IOCTL(audio, SNDCTL_DSP_SPEED, sample_rate);
843
844     /* paranoid checks */
845     if (format != ((wwo->format.wBitsPerSample == 16) ? AFMT_S16_LE : AFMT_U8))
846         ERR("Can't set format to %d (%d)\n", 
847             (wwo->format.wBitsPerSample == 16) ? AFMT_S16_LE : AFMT_U8, format);
848     if (dsp_stereo != (wwo->format.wf.nChannels > 1) ? 1 : 0) 
849         ERR("Can't set stereo to %u (%d)\n", 
850             (wwo->format.wf.nChannels > 1) ? 1 : 0, dsp_stereo);
851     if (!NEAR_MATCH(sample_rate,wwo->format.wf.nSamplesPerSec))
852         ERR("Can't set sample_rate to %lu (%d)\n", 
853             wwo->format.wf.nSamplesPerSec, sample_rate);
854
855     /* even if we set fragment size above, read it again, just in case */
856     IOCTL(audio, SNDCTL_DSP_GETBLKSIZE, fragment_size);
857     if (fragment_size == -1) {
858         WARN("IOCTL can't 'SNDCTL_DSP_GETBLKSIZE' !\n");
859         close(audio);
860         wwo->unixdev = -1;
861         return MMSYSERR_NOTENABLED;
862     }
863     wwo->dwFragmentSize = fragment_size;
864
865     wwo->msg_toget = 0;
866     wwo->msg_tosave = 0;
867     wwo->msg_event = CreateEventA(NULL, FALSE, FALSE, NULL);
868     memset(wwo->messages, 0, sizeof(WWO_MSG)*WWO_RING_BUFFER_SIZE);
869     InitializeCriticalSection(&wwo->msg_crst);
870
871     if (!(dwFlags & WAVE_DIRECTSOUND)) {
872         wwo->hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
873         wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
874         WaitForSingleObject(wwo->hEvent, INFINITE);
875     } else {
876         wwo->hEvent = INVALID_HANDLE_VALUE;
877         wwo->hThread = INVALID_HANDLE_VALUE;
878         wwo->dwThreadID = 0;
879     }
880
881     TRACE("fd=%d fragmentSize=%ld\n", 
882           wwo->unixdev, wwo->dwFragmentSize);
883     if (wwo->dwFragmentSize % wwo->format.wf.nBlockAlign)
884         ERR("Fragment doesn't contain an integral number of data blocks\n");
885
886     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n", 
887           wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec, 
888           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
889           wwo->format.wf.nBlockAlign);
890     
891     if (OSS_NotifyClient(wDevID, WOM_OPEN, 0L, 0L) != MMSYSERR_NOERROR) {
892         WARN("can't notify client !\n");
893         return MMSYSERR_INVALPARAM;
894     }
895     return MMSYSERR_NOERROR;
896 }
897
898 /**************************************************************************
899  *                              wodClose                        [internal]
900  */
901 static DWORD wodClose(WORD wDevID)
902 {
903     DWORD               ret = MMSYSERR_NOERROR;
904     WINE_WAVEOUT*       wwo;
905
906     TRACE("(%u);\n", wDevID);
907     
908     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
909         WARN("bad device ID !\n");
910         return MMSYSERR_BADDEVICEID;
911     }
912     
913     wwo = &WOutDev[wDevID];
914     if (wwo->lpQueuePtr) {
915         WARN("buffers still playing !\n");
916         ret = WAVERR_STILLPLAYING;
917     } else {
918         TRACE("imhere[3-close]\n");
919         if (wwo->hEvent != INVALID_HANDLE_VALUE) {
920             wodPlayer_Message(wwo, WINE_WM_CLOSING, 0);
921             WaitForSingleObject(wwo->hEvent, INFINITE);
922             CloseHandle(wwo->hEvent);
923         }
924         if (wwo->mapping) {
925             munmap(wwo->mapping, wwo->maplen);
926             wwo->mapping = NULL;
927         }
928
929         close(wwo->unixdev);
930         wwo->unixdev = -1;
931         wwo->dwFragmentSize = 0;
932         if (OSS_NotifyClient(wDevID, WOM_CLOSE, 0L, 0L) != MMSYSERR_NOERROR) {
933             WARN("can't notify client !\n");
934             ret = MMSYSERR_INVALPARAM;
935         }
936     }
937     return ret;
938 }
939
940 /**************************************************************************
941  *                              wodWrite                        [internal]
942  * 
943  */
944 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
945 {
946     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
947     
948     /* first, do the sanity checks... */
949     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
950         WARN("bad dev ID !\n");
951         return MMSYSERR_BADDEVICEID;
952     }
953     
954     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED)) 
955         return WAVERR_UNPREPARED;
956     
957     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) 
958         return WAVERR_STILLPLAYING;
959
960     lpWaveHdr->dwFlags &= ~WHDR_DONE;
961     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
962     lpWaveHdr->lpNext = 0;
963
964     TRACE("imhere[3-HEADER]\n");
965     wodPlayer_Message(&WOutDev[wDevID], WINE_WM_HEADER, (DWORD)lpWaveHdr);
966
967     return MMSYSERR_NOERROR;
968 }
969
970 /**************************************************************************
971  *                              wodPrepare                      [internal]
972  */
973 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
974 {
975     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
976     
977     if (wDevID >= MAX_WAVEOUTDRV) {
978         WARN("bad device ID !\n");
979         return MMSYSERR_BADDEVICEID;
980     }
981     
982     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
983         return WAVERR_STILLPLAYING;
984     
985     lpWaveHdr->dwFlags |= WHDR_PREPARED;
986     lpWaveHdr->dwFlags &= ~WHDR_DONE;
987     return MMSYSERR_NOERROR;
988 }
989
990 /**************************************************************************
991  *                              wodUnprepare                    [internal]
992  */
993 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
994 {
995     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
996     
997     if (wDevID >= MAX_WAVEOUTDRV) {
998         WARN("bad device ID !\n");
999         return MMSYSERR_BADDEVICEID;
1000     }
1001     
1002     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1003         return WAVERR_STILLPLAYING;
1004     
1005     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1006     lpWaveHdr->dwFlags |= WHDR_DONE;
1007     
1008     return MMSYSERR_NOERROR;
1009 }
1010
1011 /**************************************************************************
1012  *                      wodPause                                [internal]
1013  */
1014 static DWORD wodPause(WORD wDevID)
1015 {
1016     TRACE("(%u);!\n", wDevID);
1017     
1018     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1019         WARN("bad device ID !\n");
1020         return MMSYSERR_BADDEVICEID;
1021     }
1022     
1023     TRACE("imhere[3-PAUSING]\n");
1024     wodPlayer_Message(&WOutDev[wDevID], WINE_WM_PAUSING, 0);
1025     WaitForSingleObject(WOutDev[wDevID].hEvent, INFINITE);
1026     
1027     return MMSYSERR_NOERROR;
1028 }
1029
1030 /**************************************************************************
1031  *                      wodRestart                              [internal]
1032  */
1033 static DWORD wodRestart(WORD wDevID)
1034 {
1035     TRACE("(%u);\n", wDevID);
1036     
1037     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1038         WARN("bad device ID !\n");
1039         return MMSYSERR_BADDEVICEID;
1040     }
1041     
1042     if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1043         TRACE("imhere[3-RESTARTING]\n");
1044         wodPlayer_Message(&WOutDev[wDevID], WINE_WM_RESTARTING, 0);
1045         WaitForSingleObject(WOutDev[wDevID].hEvent, INFINITE);
1046     }
1047     
1048     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1049     /* FIXME: Myst crashes with this ... hmm -MM
1050        if (OSS_NotifyClient(wDevID, WOM_DONE, 0L, 0L) != MMSYSERR_NOERROR) {
1051        WARN("can't notify client !\n");
1052        return MMSYSERR_INVALPARAM;
1053        }
1054     */
1055     
1056     return MMSYSERR_NOERROR;
1057 }
1058
1059 /**************************************************************************
1060  *                      wodReset                                [internal]
1061  */
1062 static DWORD wodReset(WORD wDevID)
1063 {
1064     TRACE("(%u);\n", wDevID);
1065     
1066     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1067         WARN("bad device ID !\n");
1068         return MMSYSERR_BADDEVICEID;
1069     }
1070     
1071     TRACE("imhere[3-RESET]\n");
1072     wodPlayer_Message(&WOutDev[wDevID], WINE_WM_RESETTING, 0);
1073     WaitForSingleObject(WOutDev[wDevID].hEvent, INFINITE);
1074     
1075     return MMSYSERR_NOERROR;
1076 }
1077
1078
1079 /**************************************************************************
1080  *                              wodGetPosition                  [internal]
1081  */
1082 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1083 {
1084     int                 time;
1085     DWORD               val;
1086     WINE_WAVEOUT*       wwo;
1087
1088     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1089     
1090     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1091         WARN("bad device ID !\n");
1092         return MMSYSERR_BADDEVICEID;
1093     }
1094     
1095     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1096
1097     wwo = &WOutDev[wDevID];
1098     val = wwo->dwPlayedTotal;
1099
1100     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n", 
1101           lpTime->wType, wwo->format.wBitsPerSample, 
1102           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels, 
1103           wwo->format.wf.nAvgBytesPerSec); 
1104     TRACE("dwTotalPlayed=%lu\n", val);
1105     
1106     switch (lpTime->wType) {
1107     case TIME_BYTES:
1108         lpTime->u.cb = val;
1109         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
1110         break;
1111     case TIME_SAMPLES:
1112         lpTime->u.sample = val * 8 / wwo->format.wBitsPerSample;
1113         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
1114         break;
1115     case TIME_SMPTE:
1116         time = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1117         lpTime->u.smpte.hour = time / 108000;
1118         time -= lpTime->u.smpte.hour * 108000;
1119         lpTime->u.smpte.min = time / 1800;
1120         time -= lpTime->u.smpte.min * 1800;
1121         lpTime->u.smpte.sec = time / 30;
1122         time -= lpTime->u.smpte.sec * 30;
1123         lpTime->u.smpte.frame = time;
1124         lpTime->u.smpte.fps = 30;
1125         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
1126               lpTime->u.smpte.hour, lpTime->u.smpte.min,
1127               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
1128         break;
1129     default:
1130         FIXME("Format %d not supported ! use TIME_MS !\n", lpTime->wType);
1131         lpTime->wType = TIME_MS;
1132     case TIME_MS:
1133         lpTime->u.ms = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1134         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
1135         break;
1136     }
1137     return MMSYSERR_NOERROR;
1138 }
1139
1140 /**************************************************************************
1141  *                              wodGetVolume                    [internal]
1142  */
1143 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1144 {
1145     int         mixer;
1146     int         volume;
1147     DWORD       left, right;
1148     
1149     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1150     
1151     if (lpdwVol == NULL) 
1152         return MMSYSERR_NOTENABLED;
1153     if ((mixer = open(MIXER_DEV, O_RDONLY|O_NDELAY)) < 0) {
1154         WARN("mixer device not available !\n");
1155         return MMSYSERR_NOTENABLED;
1156     }
1157     if (ioctl(mixer, SOUND_MIXER_READ_PCM, &volume) == -1) {
1158         WARN("unable read mixer !\n");
1159         return MMSYSERR_NOTENABLED;
1160     }
1161     close(mixer);
1162     left = LOBYTE(volume);
1163     right = HIBYTE(volume);
1164     TRACE("left=%ld right=%ld !\n", left, right);
1165     *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) << 16);
1166     return MMSYSERR_NOERROR;
1167 }
1168
1169
1170 /**************************************************************************
1171  *                              wodSetVolume                    [internal]
1172  */
1173 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1174 {
1175     int         mixer;
1176     int         volume;
1177     DWORD       left, right;
1178
1179     TRACE("(%u, %08lX);\n", wDevID, dwParam);
1180
1181     left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
1182     right = (HIWORD(dwParam) * 100) / 0xFFFFl;
1183     volume = left + (right << 8);
1184     
1185     if ((mixer = open(MIXER_DEV, O_WRONLY|O_NDELAY)) < 0) {
1186         WARN("mixer device not available !\n");
1187         return MMSYSERR_NOTENABLED;
1188     }
1189     if (ioctl(mixer, SOUND_MIXER_WRITE_PCM, &volume) == -1) {
1190         WARN("unable set mixer !\n");
1191         return MMSYSERR_NOTENABLED;
1192     } else {
1193         TRACE("volume=%04x\n", (unsigned)volume);
1194     }
1195     close(mixer);
1196     return MMSYSERR_NOERROR;
1197 }
1198
1199 /**************************************************************************
1200  *                              wodGetNumDevs                   [internal]
1201  */
1202 static  DWORD   wodGetNumDevs(void)
1203 {
1204     DWORD       ret = 1;
1205     
1206     /* FIXME: For now, only one sound device (SOUND_DEV) is allowed */
1207     int audio = open(SOUND_DEV, O_WRONLY|O_NDELAY, 0);
1208     
1209     if (audio == -1) {
1210         if (errno != EBUSY)
1211             ret = 0;
1212     } else {
1213         close(audio);
1214     }
1215     return ret;
1216 }
1217
1218 /**************************************************************************
1219  *                              OSS_wodMessage          [sample driver]
1220  */
1221 DWORD WINAPI OSS_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser, 
1222                             DWORD dwParam1, DWORD dwParam2)
1223 {
1224     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
1225           wDevID, wMsg, dwUser, dwParam1, dwParam2);
1226     
1227     switch (wMsg) {
1228     case DRVM_INIT:
1229     case DRVM_EXIT:
1230     case DRVM_ENABLE:
1231     case DRVM_DISABLE:
1232         /* FIXME: Pretend this is supported */
1233         return 0;
1234     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1235     case WODM_CLOSE:            return wodClose         (wDevID);
1236     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1237     case WODM_PAUSE:            return wodPause         (wDevID);
1238     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
1239     case WODM_BREAKLOOP:        return MMSYSERR_NOTSUPPORTED;
1240     case WODM_PREPARE:          return wodPrepare       (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1241     case WODM_UNPREPARE:        return wodUnprepare     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1242     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSA)dwParam1,      dwParam2);
1243     case WODM_GETNUMDEVS:       return wodGetNumDevs    ();
1244     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1245     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1246     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1247     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1248     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
1249     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
1250     case WODM_RESTART:          return wodRestart       (wDevID);
1251     case WODM_RESET:            return wodReset         (wDevID);
1252     case 0x810:                 return wodDsCreate(wDevID, (PIDSDRIVER*)dwParam1);
1253     default:
1254         FIXME("unknown message %d!\n", wMsg);
1255     }
1256     return MMSYSERR_NOTSUPPORTED;
1257 }
1258
1259 /*======================================================================*
1260  *                  Low level DSOUND implementation                     *
1261  *======================================================================*/
1262
1263 typedef struct IDsDriverImpl IDsDriverImpl;
1264 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1265
1266 struct IDsDriverImpl
1267 {
1268     /* IUnknown fields */
1269     ICOM_VFIELD(IDsDriver);
1270     DWORD               ref;
1271     /* IDsDriverImpl fields */
1272     UINT                wDevID;
1273     IDsDriverBufferImpl*primary;
1274 };
1275
1276 struct IDsDriverBufferImpl
1277 {
1278     /* IUnknown fields */
1279     ICOM_VFIELD(IDsDriverBuffer);
1280     DWORD               ref;
1281     /* IDsDriverBufferImpl fields */
1282     IDsDriverImpl*      drv;
1283     DWORD               buflen;
1284 };
1285
1286 static HRESULT DSDB_MapPrimary(IDsDriverBufferImpl *dsdb)
1287 {
1288     WINE_WAVEOUT *wwo = &(WOutDev[dsdb->drv->wDevID]);
1289     if (!wwo->mapping) {
1290         wwo->mapping = mmap(NULL, wwo->maplen, PROT_WRITE, MAP_SHARED,
1291                             wwo->unixdev, 0);
1292         if (wwo->mapping == (LPBYTE)-1) {
1293             ERR("(%p): Could not map sound device for direct access (errno=%d)\n", dsdb, errno);
1294             return DSERR_GENERIC;
1295         }
1296         TRACE("(%p): sound device has been mapped for direct access at %p, size=%ld\n", dsdb, wwo->mapping, wwo->maplen);
1297
1298         /* for some reason, es1371 and sblive! sometimes have junk in here. */
1299         memset(wwo->mapping,0,wwo->maplen); /* clear it, or we get junk noise */
1300     }
1301     return DS_OK;
1302 }
1303
1304 static HRESULT DSDB_UnmapPrimary(IDsDriverBufferImpl *dsdb)
1305 {
1306     WINE_WAVEOUT *wwo = &(WOutDev[dsdb->drv->wDevID]);
1307     if (wwo->mapping) {
1308         if (munmap(wwo->mapping, wwo->maplen) < 0) {
1309             ERR("(%p): Could not unmap sound device (errno=%d)\n", dsdb, errno);
1310             return DSERR_GENERIC;
1311         }
1312         wwo->mapping = NULL;
1313         TRACE("(%p): sound device unmapped\n", dsdb);
1314     }
1315     return DS_OK;
1316 }
1317
1318 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
1319 {
1320     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1321     FIXME("(): stub!\n");
1322     return DSERR_UNSUPPORTED;
1323 }
1324
1325 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
1326 {
1327     ICOM_THIS(IDsDriverBufferImpl,iface);
1328     This->ref++;
1329     return This->ref;
1330 }
1331
1332 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
1333 {
1334     ICOM_THIS(IDsDriverBufferImpl,iface);
1335     if (--This->ref)
1336         return This->ref;
1337     if (This == This->drv->primary)
1338         This->drv->primary = NULL;
1339     DSDB_UnmapPrimary(This);
1340     HeapFree(GetProcessHeap(),0,This);
1341     return 0;
1342 }
1343
1344 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
1345                                                LPVOID*ppvAudio1,LPDWORD pdwLen1,
1346                                                LPVOID*ppvAudio2,LPDWORD pdwLen2,
1347                                                DWORD dwWritePosition,DWORD dwWriteLen,
1348                                                DWORD dwFlags)
1349 {
1350     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1351     /* since we (GetDriverDesc flags) have specified DSDDESC_DONTNEEDPRIMARYLOCK,
1352      * and that we don't support secondary buffers, this method will never be called */
1353     TRACE("(%p): stub\n",iface);
1354     return DSERR_UNSUPPORTED;
1355 }
1356
1357 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
1358                                                  LPVOID pvAudio1,DWORD dwLen1,
1359                                                  LPVOID pvAudio2,DWORD dwLen2)
1360 {
1361     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1362     TRACE("(%p): stub\n",iface);
1363     return DSERR_UNSUPPORTED;
1364 }
1365
1366 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
1367                                                     LPWAVEFORMATEX pwfx)
1368 {
1369     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1370
1371     TRACE("(%p,%p)\n",iface,pwfx);
1372     /* On our request (GetDriverDesc flags), DirectSound has by now used
1373      * waveOutClose/waveOutOpen to set the format...
1374      * unfortunately, this means our mmap() is now gone...
1375      * so we need to somehow signal to our DirectSound implementation
1376      * that it should completely recreate this HW buffer...
1377      * this unexpected error code should do the trick... */
1378     return DSERR_BUFFERLOST;
1379 }
1380
1381 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
1382 {
1383     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1384     TRACE("(%p,%ld): stub\n",iface,dwFreq);
1385     return DSERR_UNSUPPORTED;
1386 }
1387
1388 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
1389 {
1390     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1391     FIXME("(%p,%p): stub!\n",iface,pVolPan);
1392     return DSERR_UNSUPPORTED;
1393 }
1394
1395 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
1396 {
1397     /* ICOM_THIS(IDsDriverImpl,iface); */
1398     TRACE("(%p,%ld): stub\n",iface,dwNewPos);
1399     return DSERR_UNSUPPORTED;
1400 }
1401
1402 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
1403                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
1404 {
1405     ICOM_THIS(IDsDriverBufferImpl,iface);
1406     count_info info;
1407     DWORD ptr;
1408
1409     TRACE("(%p)\n",iface);
1410     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_GETOPTR, &info) < 0) {
1411         ERR("ioctl failed (%d)\n", errno);
1412         return DSERR_GENERIC;
1413     }
1414     ptr = info.ptr & ~3; /* align the pointer, just in case */
1415     if (lpdwPlay) *lpdwPlay = ptr;
1416     if (lpdwWrite) {
1417         /* add some safety margin (not strictly necessary, but...) */
1418         *lpdwWrite = ptr + 32;
1419         while (*lpdwWrite > This->buflen)
1420             *lpdwWrite -= This->buflen;
1421     }
1422     TRACE("playpos=%ld, writepos=%ld\n", lpdwPlay?*lpdwPlay:0, lpdwWrite?*lpdwWrite:0);
1423     return DSERR_UNSUPPORTED;
1424 }
1425
1426 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
1427 {
1428     ICOM_THIS(IDsDriverBufferImpl,iface);
1429     int enable = PCM_ENABLE_OUTPUT;
1430     TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
1431     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1432         ERR("ioctl failed (%d)\n", errno);
1433         return DSERR_GENERIC;
1434     }
1435     return DS_OK;
1436 }
1437
1438 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
1439 {
1440     ICOM_THIS(IDsDriverBufferImpl,iface);
1441     int enable = 0;
1442     TRACE("(%p)\n",iface);
1443     /* no more playing */
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 #if 0
1449     /* the play position must be reset to the beginning of the buffer */
1450     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_RESET, 0) < 0) {
1451         ERR("ioctl failed (%d)\n", errno);
1452         return DSERR_GENERIC;
1453     }
1454 #endif
1455     return DS_OK;
1456 }
1457
1458 static ICOM_VTABLE(IDsDriverBuffer) dsdbvt =
1459 {
1460     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1461     IDsDriverBufferImpl_QueryInterface,
1462     IDsDriverBufferImpl_AddRef,
1463     IDsDriverBufferImpl_Release,
1464     IDsDriverBufferImpl_Lock,
1465     IDsDriverBufferImpl_Unlock,
1466     IDsDriverBufferImpl_SetFormat,
1467     IDsDriverBufferImpl_SetFrequency,
1468     IDsDriverBufferImpl_SetVolumePan,
1469     IDsDriverBufferImpl_SetPosition,
1470     IDsDriverBufferImpl_GetPosition,
1471     IDsDriverBufferImpl_Play,
1472     IDsDriverBufferImpl_Stop
1473 };
1474
1475 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
1476 {
1477     /* ICOM_THIS(IDsDriverImpl,iface); */
1478     FIXME("(%p): stub!\n",iface);
1479     return DSERR_UNSUPPORTED;
1480 }
1481
1482 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
1483 {
1484     ICOM_THIS(IDsDriverImpl,iface);
1485     This->ref++;
1486     return This->ref;
1487 }
1488
1489 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
1490 {
1491     ICOM_THIS(IDsDriverImpl,iface);
1492     if (--This->ref)
1493         return This->ref;
1494     HeapFree(GetProcessHeap(),0,This);
1495     return 0;
1496 }
1497
1498 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
1499 {
1500     ICOM_THIS(IDsDriverImpl,iface);
1501     TRACE("(%p,%p)\n",iface,pDesc);
1502     pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
1503         DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK;
1504     strcpy(pDesc->szDesc,"WineOSS DirectSound Driver");
1505     strcpy(pDesc->szDrvName,"wineoss.drv");
1506     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
1507     pDesc->wVxdId               = 0; 
1508     pDesc->wReserved            = 0;
1509     pDesc->ulDeviceNum          = This->wDevID;
1510     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
1511     pDesc->pvDirectDrawHeap     = NULL;
1512     pDesc->dwMemStartAddress    = 0;
1513     pDesc->dwMemEndAddress      = 0;
1514     pDesc->dwMemAllocExtra      = 0;
1515     pDesc->pvReserved1          = NULL;
1516     pDesc->pvReserved2          = NULL;
1517     return DS_OK;
1518 }
1519
1520 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
1521 {
1522     ICOM_THIS(IDsDriverImpl,iface);
1523     int enable = 0;
1524
1525     TRACE("(%p)\n",iface);
1526     /* make sure the card doesn't start playing before we want it to */
1527     if (ioctl(WOutDev[This->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1528         ERR("ioctl failed (%d)\n", errno);
1529         return DSERR_GENERIC;
1530     }
1531     return DS_OK;
1532 }
1533
1534 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
1535 {
1536     ICOM_THIS(IDsDriverImpl,iface);
1537     TRACE("(%p)\n",iface);
1538     if (This->primary) {
1539         ERR("problem with DirectSound: primary not released\n");
1540         return DSERR_GENERIC;
1541     }
1542     return DS_OK;
1543 }
1544
1545 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
1546 {
1547     /* ICOM_THIS(IDsDriverImpl,iface); */
1548     TRACE("(%p,%p)\n",iface,pCaps);
1549     memset(pCaps, 0, sizeof(*pCaps));
1550     /* FIXME: need to check actual capabilities */
1551     pCaps->dwFlags = DSCAPS_PRIMARYMONO | DSCAPS_PRIMARYSTEREO |
1552         DSCAPS_PRIMARY8BIT | DSCAPS_PRIMARY16BIT;
1553     pCaps->dwPrimaryBuffers = 1;
1554     /* the other fields only apply to secondary buffers, which we don't support
1555      * (unless we want to mess with wavetable synthesizers and MIDI) */
1556     return DS_OK;
1557 }
1558
1559 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
1560                                                       LPWAVEFORMATEX pwfx,
1561                                                       DWORD dwFlags, DWORD dwCardAddress,
1562                                                       LPDWORD pdwcbBufferSize,
1563                                                       LPBYTE *ppbBuffer,
1564                                                       LPVOID *ppvObj)
1565 {
1566     ICOM_THIS(IDsDriverImpl,iface);
1567     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
1568     HRESULT err;
1569     audio_buf_info info;
1570
1571     TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
1572     /* we only support primary buffers */
1573     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
1574         return DSERR_UNSUPPORTED;
1575     if (This->primary)
1576         return DSERR_ALLOCATED;
1577     if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
1578         return DSERR_CONTROLUNAVAIL;
1579
1580     *ippdsdb = (IDsDriverBufferImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
1581     if (*ippdsdb == NULL)
1582         return DSERR_OUTOFMEMORY;
1583     ICOM_VTBL(*ippdsdb) = &dsdbvt;
1584     (*ippdsdb)->ref     = 1;
1585     (*ippdsdb)->drv     = This;
1586
1587     /* check how big the DMA buffer is now */
1588     if (ioctl(WOutDev[This->wDevID].unixdev, SNDCTL_DSP_GETOSPACE, &info) < 0) {
1589         ERR("ioctl failed (%d)\n", errno);
1590         HeapFree(GetProcessHeap(),0,*ippdsdb);
1591         *ippdsdb = NULL;
1592         return DSERR_GENERIC;
1593     }
1594     WOutDev[This->wDevID].maplen = (*ippdsdb)->buflen = info.fragstotal * info.fragsize;
1595
1596     /* map the DMA buffer */
1597     err = DSDB_MapPrimary(*ippdsdb);
1598     if (err != DS_OK) {
1599         HeapFree(GetProcessHeap(),0,*ippdsdb);
1600         *ippdsdb = NULL;
1601         return err;
1602     }
1603
1604     /* primary buffer is ready to go */
1605     *pdwcbBufferSize    = WOutDev[This->wDevID].maplen;
1606     *ppbBuffer          = WOutDev[This->wDevID].mapping;
1607
1608     This->primary = *ippdsdb;
1609
1610     return DS_OK;
1611 }
1612
1613 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
1614                                                          PIDSDRIVERBUFFER pBuffer,
1615                                                          LPVOID *ppvObj)
1616 {
1617     /* ICOM_THIS(IDsDriverImpl,iface); */
1618     TRACE("(%p,%p): stub\n",iface,pBuffer);
1619     return DSERR_INVALIDCALL;
1620 }
1621
1622 static ICOM_VTABLE(IDsDriver) dsdvt =
1623 {
1624     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1625     IDsDriverImpl_QueryInterface,
1626     IDsDriverImpl_AddRef,
1627     IDsDriverImpl_Release,
1628     IDsDriverImpl_GetDriverDesc,
1629     IDsDriverImpl_Open,
1630     IDsDriverImpl_Close,
1631     IDsDriverImpl_GetCaps,
1632     IDsDriverImpl_CreateSoundBuffer,
1633     IDsDriverImpl_DuplicateSoundBuffer
1634 };
1635
1636 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1637 {
1638     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
1639
1640     /* the HAL isn't much better than the HEL if we can't do mmap() */
1641     if (!(WOutDev[wDevID].caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
1642         ERR("DirectSound flag not set\n");
1643         MESSAGE("This sound card's driver does not support direct access\n");
1644         MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
1645         return MMSYSERR_NOTSUPPORTED;
1646     }
1647
1648     *idrv = (IDsDriverImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
1649     if (!*idrv)
1650         return MMSYSERR_NOMEM;
1651     ICOM_VTBL(*idrv)    = &dsdvt;
1652     (*idrv)->ref        = 1;
1653
1654     (*idrv)->wDevID     = wDevID;
1655     (*idrv)->primary    = NULL;
1656     return MMSYSERR_NOERROR;
1657 }
1658
1659 /*======================================================================*
1660  *                  Low level WAVE IN implementation                    *
1661  *======================================================================*/
1662
1663 /**************************************************************************
1664  *                      widGetDevCaps                           [internal]
1665  */
1666 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSA lpCaps, DWORD dwSize)
1667 {
1668     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1669     
1670     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1671     
1672     if (wDevID >= MAX_WAVEINDRV) {
1673         TRACE("MAX_WAVINDRV reached !\n");
1674         return MMSYSERR_BADDEVICEID;
1675     }
1676
1677     memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1678     return MMSYSERR_NOERROR;
1679 }
1680
1681 /**************************************************************************
1682  *                              widRecorder                     [internal]
1683  */
1684 static  DWORD   CALLBACK        widRecorder(LPVOID pmt)
1685 {
1686     WORD                uDevID = (DWORD)pmt;
1687     WINE_WAVEIN*        wwi = (WINE_WAVEIN*)&WInDev[uDevID];
1688     WAVEHDR*            lpWaveHdr;
1689     DWORD               dwSleepTime;
1690     MSG                 msg;
1691     DWORD               bytesRead;
1692
1693     audio_buf_info info;
1694         
1695         LPVOID          buffer = HeapAlloc(GetProcessHeap(), 
1696                                            HEAP_ZERO_MEMORY, 
1697                                        wwi->dwFragmentSize);
1698
1699     LPVOID              pOffset = buffer;
1700
1701     PeekMessageA(&msg, 0, 0, 0, 0);
1702     wwi->state = WINE_WS_STOPPED;
1703     wwi->dwTotalRecorded = 0;
1704
1705     SetEvent(wwi->hEvent);
1706     
1707         /* make sleep time to be # of ms to output a fragment */
1708     dwSleepTime = (wwi->dwFragmentSize * 1000) / wwi->format.wf.nAvgBytesPerSec;
1709     TRACE("sleeptime=%ld ms\n", dwSleepTime);
1710
1711     for (; ; ) {
1712         /* wait for dwSleepTime or an event in thread's queue */
1713         /* FIXME: could improve wait time depending on queue state,
1714          * ie, number of queued fragments
1715          */
1716
1717         if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING) 
1718         {
1719             lpWaveHdr = wwi->lpQueuePtr;
1720
1721
1722             ioctl(wwi->unixdev, SNDCTL_DSP_GETISPACE, &info);
1723             TRACE("info={frag=%d fsize=%d ftotal=%d bytes=%d}\n", info.fragments, info.fragsize, info.fragstotal, info.bytes);
1724
1725
1726             /* read all the fragments accumulated so far */
1727             while ((info.fragments > 0) && (wwi->lpQueuePtr))
1728             {
1729                 info.fragments --;
1730
1731                 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded > wwi->dwFragmentSize)
1732                 {
1733                     /* directly read fragment in wavehdr */
1734                     bytesRead = read(wwi->unixdev, 
1735                                      lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded, 
1736                                      wwi->dwFragmentSize);
1737
1738                     TRACE("bytesRead=%ld (direct)\n", bytesRead);
1739                     if (bytesRead != (DWORD) -1)
1740                     {
1741                         /* update number of bytes recorded in current buffer and by this device */
1742                         lpWaveHdr->dwBytesRecorded += bytesRead;
1743                         wwi->dwTotalRecorded       += bytesRead;
1744                                 
1745                         /* buffer is full. notify client */
1746                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength) 
1747                         {
1748                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1749                             lpWaveHdr->dwFlags |=  WHDR_DONE;
1750
1751                             if (OSS_NotifyClient(uDevID, 
1752                                                  WIM_DATA, 
1753                                                  (DWORD)lpWaveHdr, 
1754                                                  lpWaveHdr->dwBytesRecorded) != MMSYSERR_NOERROR) 
1755                             {
1756                                 WARN("can't notify client !\n");
1757                             }
1758                             lpWaveHdr = wwi->lpQueuePtr = lpWaveHdr->lpNext;
1759                         }
1760                     }
1761                 }
1762                 else
1763                 {
1764                     /* read the fragment in a local buffer */
1765                     bytesRead = read(wwi->unixdev, buffer, wwi->dwFragmentSize);
1766                     pOffset = buffer;
1767
1768                     TRACE("bytesRead=%ld (local)\n", bytesRead);
1769
1770                     /* copy data in client buffers */   
1771                     while (bytesRead != (DWORD) -1 && bytesRead > 0)
1772                     {
1773                         DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
1774
1775                         memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
1776                                pOffset,
1777                                dwToCopy);
1778
1779                         /* update number of bytes recorded in current buffer and by this device */
1780                         lpWaveHdr->dwBytesRecorded += dwToCopy;
1781                         wwi->dwTotalRecorded += dwToCopy;
1782                         bytesRead -= dwToCopy;
1783                         pOffset   += dwToCopy;
1784                                 
1785                         /* client buffer is full. notify client */
1786                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength) 
1787                         {
1788                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1789                             lpWaveHdr->dwFlags |=  WHDR_DONE;
1790
1791                             if (OSS_NotifyClient(uDevID, 
1792                                                  WIM_DATA, 
1793                                                  (DWORD)lpWaveHdr, 
1794                                                  lpWaveHdr->dwBytesRecorded) != MMSYSERR_NOERROR) 
1795                             {
1796                                 WARN("can't notify client !\n");
1797                             }
1798                                    
1799                             if (lpWaveHdr->lpNext)
1800                             {   
1801                                 lpWaveHdr = lpWaveHdr->lpNext;
1802                                 wwi->lpQueuePtr = lpWaveHdr;
1803                             }
1804                             else
1805                             {
1806                                 /* no more buffer to copy data to, but we did read more. 
1807                                  * what hasn't been copied will be dropped
1808                                  */ 
1809                                 if (bytesRead) WARN("buffer over run! %lu bytes dropped.\n", bytesRead);
1810                                 wwi->lpQueuePtr = NULL;
1811                                 break;
1812                             }
1813                         }
1814                     }
1815                 }
1816             }
1817         }
1818         
1819         MsgWaitForMultipleObjects(0, NULL, FALSE, dwSleepTime, QS_POSTMESSAGE);
1820
1821         while (PeekMessageA(&msg, 0, WINE_WM_FIRST, WINE_WM_LAST, PM_REMOVE)) {
1822
1823             TRACE("msg=0x%x wParam=0x%x lParam=0x%lx\n", msg.message, msg.wParam, msg.lParam);
1824             switch (msg.message) {
1825             case WINE_WM_PAUSING:
1826                 wwi->state = WINE_WS_PAUSED;
1827                 /*FIXME("Device should stop recording");*/
1828                 SetEvent(wwi->hEvent);
1829                 break;
1830             case WINE_WM_RESTARTING:
1831             {
1832                 int enable = PCM_ENABLE_INPUT;
1833                 wwi->state = WINE_WS_PLAYING;
1834
1835                 if (wwi->bTriggerSupport)
1836                 {
1837                     /* start the recording */
1838                     if (ioctl(wwi->unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) 
1839                     {
1840                         ERR("ioctl(SNDCTL_DSP_SETTRIGGER) failed (%d)\n", errno);
1841                     }
1842                 }
1843                 else
1844                 {
1845                     unsigned char data[4];
1846                     /* read 4 bytes to start the recording */
1847                     read(wwi->unixdev, data, 4);
1848                 }
1849                 
1850                 SetEvent(wwi->hEvent);
1851                 break;
1852             }
1853             case WINE_WM_HEADER:
1854                 lpWaveHdr = (LPWAVEHDR)msg.lParam;
1855                 lpWaveHdr->lpNext = 0;
1856
1857                 /* insert buffer at the end of queue */
1858                 {
1859                     LPWAVEHDR*  wh;
1860                     for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1861                     *wh = lpWaveHdr;
1862                 }
1863                 break;
1864             case WINE_WM_RESETTING:
1865                 wwi->state = WINE_WS_STOPPED;
1866                 /* return all buffers to the app */
1867                 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
1868                     TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
1869                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1870                     lpWaveHdr->dwFlags |= WHDR_DONE;
1871         
1872                     if (OSS_NotifyClient(uDevID, WIM_DATA, (DWORD)lpWaveHdr, 
1873                                          lpWaveHdr->dwBytesRecorded) != MMSYSERR_NOERROR) {
1874                         WARN("can't notify client !\n");
1875                     }
1876                 }
1877                 wwi->lpQueuePtr = NULL;
1878                 SetEvent(wwi->hEvent);
1879                 break;
1880             case WINE_WM_CLOSING:
1881                 wwi->hThread = 0;
1882                 wwi->state = WINE_WS_CLOSED;
1883                 SetEvent(wwi->hEvent);
1884                 HeapFree(GetProcessHeap(), 0, buffer); 
1885                 ExitThread(0);
1886                 /* shouldn't go here */
1887             default:
1888                 FIXME("unknown message %d\n", msg.message);
1889                 break;
1890             }
1891         }
1892     }
1893     ExitThread(0);
1894     /* just for not generating compilation warnings... should never be executed */
1895     return 0; 
1896 }
1897
1898
1899 /**************************************************************************
1900  *                              widOpen                         [internal]
1901  */
1902 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1903 {
1904     int                 audio;
1905     int                 fragment_size;
1906     int                 sample_rate;
1907     int                 format;
1908     int                 dsp_stereo;
1909     WINE_WAVEIN*        wwi;
1910
1911     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
1912     if (lpDesc == NULL) {
1913         WARN("Invalid Parameter !\n");
1914         return MMSYSERR_INVALPARAM;
1915     }
1916     if (wDevID >= MAX_WAVEINDRV) return MMSYSERR_BADDEVICEID;
1917
1918     /* only PCM format is supported so far... */
1919     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1920         lpDesc->lpFormat->nChannels == 0 ||
1921         lpDesc->lpFormat->nSamplesPerSec == 0) {
1922         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n", 
1923              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1924              lpDesc->lpFormat->nSamplesPerSec);
1925         return WAVERR_BADFORMAT;
1926     }
1927
1928     if (dwFlags & WAVE_FORMAT_QUERY) {
1929         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n", 
1930              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1931              lpDesc->lpFormat->nSamplesPerSec);
1932         return MMSYSERR_NOERROR;
1933     }
1934
1935     if (access(SOUND_DEV,0) != 0) return MMSYSERR_NOTENABLED;
1936     audio = open(SOUND_DEV, O_RDONLY|O_NDELAY, 0);
1937     if (audio == -1) {
1938         WARN("can't open sound device %s (%s)!\n", SOUND_DEV, strerror(errno));
1939         return MMSYSERR_ALLOCATED;
1940     }
1941     fcntl(audio, F_SETFD, 1); /* set close on exec flag */
1942
1943     wwi = &WInDev[wDevID];
1944     if (wwi->lpQueuePtr) {
1945         WARN("Should have an empty queue (%p)\n", wwi->lpQueuePtr);
1946         wwi->lpQueuePtr = NULL;
1947     }
1948     wwi->unixdev = audio;
1949     wwi->dwTotalRecorded = 0;
1950     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1951
1952     memcpy(&wwi->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
1953     memcpy(&wwi->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1954
1955     if (wwi->format.wBitsPerSample == 0) {
1956         WARN("Resetting zeroed wBitsPerSample\n");
1957         wwi->format.wBitsPerSample = 8 *
1958             (wwi->format.wf.nAvgBytesPerSec /
1959              wwi->format.wf.nSamplesPerSec) /
1960             wwi->format.wf.nChannels;
1961     }
1962
1963     sample_rate = wwi->format.wf.nSamplesPerSec;
1964     dsp_stereo = (wwi->format.wf.nChannels > 1) ? TRUE : FALSE;
1965     format = (wwi->format.wBitsPerSample == 16) ? AFMT_S16_LE : AFMT_U8;
1966
1967     IOCTL(audio, SNDCTL_DSP_SETFMT, format);
1968     IOCTL(audio, SNDCTL_DSP_STEREO, dsp_stereo);
1969     IOCTL(audio, SNDCTL_DSP_SPEED,  sample_rate);
1970
1971     /* paranoid checks */
1972     if (format != ((wwi->format.wBitsPerSample == 16) ? AFMT_S16_LE : AFMT_U8))
1973         ERR("Can't set format to %d (%d)\n", 
1974             (wwi->format.wBitsPerSample == 16) ? AFMT_S16_LE : AFMT_U8, format);
1975     if (dsp_stereo != (wwi->format.wf.nChannels > 1) ? 1 : 0) 
1976         ERR("Can't set stereo to %u (%d)\n", 
1977             (wwi->format.wf.nChannels > 1) ? 1 : 0, dsp_stereo);
1978     if (!NEAR_MATCH(sample_rate, wwi->format.wf.nSamplesPerSec))
1979         ERR("Can't set sample_rate to %lu (%d)\n", 
1980             wwi->format.wf.nSamplesPerSec, sample_rate);
1981
1982     IOCTL(audio, SNDCTL_DSP_GETBLKSIZE, fragment_size);
1983     if (fragment_size == -1) {
1984         WARN("IOCTL can't 'SNDCTL_DSP_GETBLKSIZE' !\n");
1985         close(audio);
1986         wwi->unixdev = -1;
1987         return MMSYSERR_NOTENABLED;
1988     }
1989     wwi->dwFragmentSize = fragment_size;
1990
1991     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n", 
1992           wwi->format.wBitsPerSample, wwi->format.wf.nAvgBytesPerSec, 
1993           wwi->format.wf.nSamplesPerSec, wwi->format.wf.nChannels,
1994           wwi->format.wf.nBlockAlign);
1995
1996     wwi->hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
1997     wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
1998     WaitForSingleObject(wwi->hEvent, INFINITE);
1999
2000    if (OSS_NotifyClient(wDevID, WIM_OPEN, 0L, 0L) != MMSYSERR_NOERROR) {
2001         WARN("can't notify client !\n");
2002         return MMSYSERR_INVALPARAM;
2003     }
2004     return MMSYSERR_NOERROR;
2005 }
2006
2007 /**************************************************************************
2008  *                              widClose                        [internal]
2009  */
2010 static DWORD widClose(WORD wDevID)
2011 {
2012     WINE_WAVEIN*        wwi;
2013
2014     TRACE("(%u);\n", wDevID);
2015     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2016         WARN("can't close !\n");
2017         return MMSYSERR_INVALHANDLE;
2018     }
2019
2020     wwi = &WInDev[wDevID];
2021
2022     if (wwi->lpQueuePtr != NULL) {
2023         WARN("still buffers open !\n");
2024         return WAVERR_STILLPLAYING;
2025     }
2026
2027     PostThreadMessageA(wwi->dwThreadID, WINE_WM_CLOSING, 0, 0);
2028     WaitForSingleObject(wwi->hEvent, INFINITE);
2029     CloseHandle(wwi->hEvent);
2030     close(wwi->unixdev);
2031     wwi->unixdev = -1;
2032     wwi->dwFragmentSize = 0;
2033     if (OSS_NotifyClient(wDevID, WIM_CLOSE, 0L, 0L) != MMSYSERR_NOERROR) {
2034         WARN("can't notify client !\n");
2035         return MMSYSERR_INVALPARAM;
2036     }
2037     return MMSYSERR_NOERROR;
2038 }
2039
2040 /**************************************************************************
2041  *                              widAddBuffer            [internal]
2042  */
2043 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2044 {
2045     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2046
2047     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2048         WARN("can't do it !\n");
2049         return MMSYSERR_INVALHANDLE;
2050     }
2051     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED)) {
2052         TRACE("never been prepared !\n");
2053         return WAVERR_UNPREPARED;
2054     }
2055     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) {
2056         TRACE("header already in use !\n");
2057         return WAVERR_STILLPLAYING;
2058     }
2059
2060     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2061     lpWaveHdr->dwFlags &= ~WHDR_DONE;
2062     lpWaveHdr->dwBytesRecorded = 0;
2063         lpWaveHdr->lpNext = NULL;
2064         
2065     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_HEADER, 0, (DWORD)lpWaveHdr);
2066     return MMSYSERR_NOERROR;
2067 }
2068
2069 /**************************************************************************
2070  *                              widPrepare                      [internal]
2071  */
2072 static DWORD widPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2073 {
2074     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2075
2076     if (wDevID >= MAX_WAVEINDRV) return MMSYSERR_INVALHANDLE;
2077
2078     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2079         return WAVERR_STILLPLAYING;
2080
2081     lpWaveHdr->dwFlags |= WHDR_PREPARED;
2082     lpWaveHdr->dwFlags &= ~(WHDR_INQUEUE|WHDR_DONE);
2083     lpWaveHdr->dwBytesRecorded = 0;
2084     TRACE("header prepared !\n");
2085     return MMSYSERR_NOERROR;
2086 }
2087
2088 /**************************************************************************
2089  *                              widUnprepare                    [internal]
2090  */
2091 static DWORD widUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2092 {
2093     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2094     if (wDevID >= MAX_WAVEINDRV) return MMSYSERR_INVALHANDLE;
2095
2096     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2097         return WAVERR_STILLPLAYING;
2098
2099     lpWaveHdr->dwFlags &= ~(WHDR_PREPARED|WHDR_INQUEUE);
2100     lpWaveHdr->dwFlags |= WHDR_DONE;
2101     
2102     return MMSYSERR_NOERROR;
2103 }
2104
2105 /**************************************************************************
2106  *                      widStart                                [internal]
2107  */
2108 static DWORD widStart(WORD wDevID)
2109 {
2110     TRACE("(%u);\n", wDevID);
2111     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2112         WARN("can't start recording !\n");
2113         return MMSYSERR_INVALHANDLE;
2114     }
2115
2116     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_RESTARTING, 0, 0);
2117     WaitForSingleObject(WInDev[wDevID].hEvent, INFINITE);
2118     return MMSYSERR_NOERROR;
2119 }
2120
2121 /**************************************************************************
2122  *                      widStop                                 [internal]
2123  */
2124 static DWORD widStop(WORD wDevID)
2125 {
2126     TRACE("(%u);\n", wDevID);
2127     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2128         WARN("can't stop !\n");
2129         return MMSYSERR_INVALHANDLE;
2130     }
2131     /* FIXME: reset aint stop */
2132     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_RESETTING, 0, 0);
2133     WaitForSingleObject(WInDev[wDevID].hEvent, INFINITE);
2134     
2135     return MMSYSERR_NOERROR;
2136 }
2137
2138 /**************************************************************************
2139  *                      widReset                                [internal]
2140  */
2141 static DWORD widReset(WORD wDevID)
2142 {
2143     TRACE("(%u);\n", wDevID);
2144     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2145         WARN("can't reset !\n");
2146         return MMSYSERR_INVALHANDLE;
2147     }
2148     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_RESETTING, 0, 0);
2149     WaitForSingleObject(WInDev[wDevID].hEvent, INFINITE);
2150     return MMSYSERR_NOERROR;
2151 }
2152
2153 /**************************************************************************
2154  *                              widGetPosition                  [internal]
2155  */
2156 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
2157 {
2158     int                 time;
2159     WINE_WAVEIN*        wwi;
2160     
2161     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
2162
2163     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2164         WARN("can't get pos !\n");
2165         return MMSYSERR_INVALHANDLE;
2166     }
2167     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
2168
2169     wwi = &WInDev[wDevID];
2170
2171     TRACE("wType=%04X !\n", lpTime->wType);
2172     TRACE("wBitsPerSample=%u\n", wwi->format.wBitsPerSample); 
2173     TRACE("nSamplesPerSec=%lu\n", wwi->format.wf.nSamplesPerSec); 
2174     TRACE("nChannels=%u\n", wwi->format.wf.nChannels); 
2175     TRACE("nAvgBytesPerSec=%lu\n", wwi->format.wf.nAvgBytesPerSec); 
2176     switch (lpTime->wType) {
2177     case TIME_BYTES:
2178         lpTime->u.cb = wwi->dwTotalRecorded;
2179         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
2180         break;
2181     case TIME_SAMPLES:
2182         lpTime->u.sample = wwi->dwTotalRecorded * 8 /
2183             wwi->format.wBitsPerSample;
2184         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
2185         break;
2186     case TIME_SMPTE:
2187         time = wwi->dwTotalRecorded /
2188             (wwi->format.wf.nAvgBytesPerSec / 1000);
2189         lpTime->u.smpte.hour = time / 108000;
2190         time -= lpTime->u.smpte.hour * 108000;
2191         lpTime->u.smpte.min = time / 1800;
2192         time -= lpTime->u.smpte.min * 1800;
2193         lpTime->u.smpte.sec = time / 30;
2194         time -= lpTime->u.smpte.sec * 30;
2195         lpTime->u.smpte.frame = time;
2196         lpTime->u.smpte.fps = 30;
2197         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
2198               lpTime->u.smpte.hour, lpTime->u.smpte.min,
2199               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
2200         break;
2201     case TIME_MS:
2202         lpTime->u.ms = wwi->dwTotalRecorded /
2203             (wwi->format.wf.nAvgBytesPerSec / 1000);
2204         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
2205         break;
2206     default:
2207         FIXME("format not supported (%u) ! use TIME_MS !\n", lpTime->wType);
2208         lpTime->wType = TIME_MS;
2209     }
2210     return MMSYSERR_NOERROR;
2211 }
2212
2213 /**************************************************************************
2214  *                              OSS_widMessage                  [sample driver]
2215  */
2216 DWORD WINAPI OSS_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser, 
2217                             DWORD dwParam1, DWORD dwParam2)
2218 {
2219     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
2220           wDevID, wMsg, dwUser, dwParam1, dwParam2);
2221
2222     switch (wMsg) {
2223     case DRVM_INIT:
2224     case DRVM_EXIT:
2225     case DRVM_ENABLE:
2226     case DRVM_DISABLE:
2227         /* FIXME: Pretend this is supported */
2228         return 0;
2229     case WIDM_OPEN:             return widOpen       (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2230     case WIDM_CLOSE:            return widClose      (wDevID);
2231     case WIDM_ADDBUFFER:        return widAddBuffer  (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2232     case WIDM_PREPARE:          return widPrepare    (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2233     case WIDM_UNPREPARE:        return widUnprepare  (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2234     case WIDM_GETDEVCAPS:       return widGetDevCaps (wDevID, (LPWAVEINCAPSA)dwParam1, dwParam2);
2235     case WIDM_GETNUMDEVS:       return wodGetNumDevs ();        /* same number of devices in output as in input */
2236     case WIDM_GETPOS:           return widGetPosition(wDevID, (LPMMTIME)dwParam1, dwParam2);
2237     case WIDM_RESET:            return widReset      (wDevID);
2238     case WIDM_START:            return widStart      (wDevID);
2239     case WIDM_STOP:             return widStop       (wDevID);
2240     default:
2241         FIXME("unknown message %u!\n", wMsg);
2242     }
2243     return MMSYSERR_NOTSUPPORTED;
2244 }
2245
2246 #else /* !HAVE_OSS */
2247
2248 /**************************************************************************
2249  *                              OSS_wodMessage                  [sample driver]
2250  */
2251 DWORD WINAPI OSS_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser, 
2252                             DWORD dwParam1, DWORD dwParam2)
2253 {
2254     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2255     return MMSYSERR_NOTENABLED;
2256 }
2257
2258 /**************************************************************************
2259  *                              OSS_widMessage                  [sample driver]
2260  */
2261 DWORD WINAPI OSS_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser, 
2262                             DWORD dwParam1, DWORD dwParam2)
2263 {
2264     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2265     return MMSYSERR_NOTENABLED;
2266 }
2267
2268 #endif /* HAVE_OSS */