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