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