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