Fix gcc 4.0 -Wpointer-sign warnings.
[wine] / dlls / winmm / wineoss / audio.c
1 /*
2  * Sample Wine Driver for Open Sound System (featured in Linux and FreeBSD)
3  *
4  * Copyright 1994 Martin Ayotte
5  *           1999 Eric Pouech (async playing in waveOut/waveIn)
6  *           2000 Eric Pouech (loops in waveOut)
7  *           2002 Eric Pouech (full duplex)
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23 /*
24  * FIXME:
25  *      pause in waveOut does not work correctly in loop mode
26  *      Direct Sound Capture driver does not work (not complete yet)
27  */
28
29 /* an exact wodGetPosition is usually not worth the extra context switches,
30  * as we're going to have near fragment accuracy anyway */
31 #define EXACT_WODPOSITION
32 #define EXACT_WIDPOSITION
33
34 #include "config.h"
35 #include "wine/port.h"
36
37 #include <stdlib.h>
38 #include <stdarg.h>
39 #include <stdio.h>
40 #include <string.h>
41 #ifdef HAVE_UNISTD_H
42 # include <unistd.h>
43 #endif
44 #include <errno.h>
45 #include <fcntl.h>
46 #ifdef HAVE_SYS_IOCTL_H
47 # include <sys/ioctl.h>
48 #endif
49 #ifdef HAVE_SYS_MMAN_H
50 # include <sys/mman.h>
51 #endif
52 #ifdef HAVE_POLL_H
53 #include <poll.h>
54 #endif
55 #ifdef HAVE_SYS_POLL_H
56 # include <sys/poll.h>
57 #endif
58
59 #include "windef.h"
60 #include "winbase.h"
61 #include "wingdi.h"
62 #include "winuser.h"
63 #include "winnls.h"
64 #include "winerror.h"
65 #include "mmddk.h"
66 #include "mmreg.h"
67 #include "dsound.h"
68 #include "dsdriver.h"
69 #include "ks.h"
70 #include "ksguid.h"
71 #include "ksmedia.h"
72 #include "oss.h"
73 #include "wine/debug.h"
74
75 #include "audio.h"
76
77 WINE_DEFAULT_DEBUG_CHANNEL(wave);
78
79 /* Allow 1% deviation for sample rates (some ES137x cards) */
80 #define NEAR_MATCH(rate1,rate2) (((100*((int)(rate1)-(int)(rate2)))/(rate1))==0)
81
82 #ifdef HAVE_OSS
83
84 OSS_DEVICE      OSS_Devices[MAX_WAVEDRV];
85 WINE_WAVEOUT    WOutDev[MAX_WAVEDRV];
86 WINE_WAVEIN     WInDev[MAX_WAVEDRV];
87 unsigned        numOutDev;
88 unsigned        numInDev;
89
90 /* state diagram for waveOut writing:
91  *
92  * +---------+-------------+---------------+---------------------------------+
93  * |  state  |  function   |     event     |            new state            |
94  * +---------+-------------+---------------+---------------------------------+
95  * |         | open()      |               | STOPPED                         |
96  * | PAUSED  | write()     |               | PAUSED                          |
97  * | STOPPED | write()     | <thrd create> | PLAYING                         |
98  * | PLAYING | write()     | HEADER        | PLAYING                         |
99  * | (other) | write()     | <error>       |                                 |
100  * | (any)   | pause()     | PAUSING       | PAUSED                          |
101  * | PAUSED  | restart()   | RESTARTING    | PLAYING (if no thrd => STOPPED) |
102  * | (any)   | reset()     | RESETTING     | STOPPED                         |
103  * | (any)   | close()     | CLOSING       | CLOSED                          |
104  * +---------+-------------+---------------+---------------------------------+
105  */
106
107 /* These strings used only for tracing */
108 static const char * getCmdString(enum win_wm_message msg)
109 {
110     static char unknown[32];
111 #define MSG_TO_STR(x) case x: return #x
112     switch(msg) {
113     MSG_TO_STR(WINE_WM_PAUSING);
114     MSG_TO_STR(WINE_WM_RESTARTING);
115     MSG_TO_STR(WINE_WM_RESETTING);
116     MSG_TO_STR(WINE_WM_HEADER);
117     MSG_TO_STR(WINE_WM_UPDATE);
118     MSG_TO_STR(WINE_WM_BREAKLOOP);
119     MSG_TO_STR(WINE_WM_CLOSING);
120     MSG_TO_STR(WINE_WM_STARTING);
121     MSG_TO_STR(WINE_WM_STOPPING);
122     }
123 #undef MSG_TO_STR
124     sprintf(unknown, "UNKNOWN(0x%08x)", msg);
125     return unknown;
126 }
127
128 int getEnables(OSS_DEVICE *ossdev)
129 {
130     return ( (ossdev->bOutputEnabled ? PCM_ENABLE_OUTPUT : 0) |
131              (ossdev->bInputEnabled  ? PCM_ENABLE_INPUT  : 0) );
132 }
133
134 static const char * getMessage(UINT msg)
135 {
136     static char unknown[32];
137 #define MSG_TO_STR(x) case x: return #x
138     switch(msg) {
139     MSG_TO_STR(DRVM_INIT);
140     MSG_TO_STR(DRVM_EXIT);
141     MSG_TO_STR(DRVM_ENABLE);
142     MSG_TO_STR(DRVM_DISABLE);
143     MSG_TO_STR(WIDM_OPEN);
144     MSG_TO_STR(WIDM_CLOSE);
145     MSG_TO_STR(WIDM_ADDBUFFER);
146     MSG_TO_STR(WIDM_PREPARE);
147     MSG_TO_STR(WIDM_UNPREPARE);
148     MSG_TO_STR(WIDM_GETDEVCAPS);
149     MSG_TO_STR(WIDM_GETNUMDEVS);
150     MSG_TO_STR(WIDM_GETPOS);
151     MSG_TO_STR(WIDM_RESET);
152     MSG_TO_STR(WIDM_START);
153     MSG_TO_STR(WIDM_STOP);
154     MSG_TO_STR(WODM_OPEN);
155     MSG_TO_STR(WODM_CLOSE);
156     MSG_TO_STR(WODM_WRITE);
157     MSG_TO_STR(WODM_PAUSE);
158     MSG_TO_STR(WODM_GETPOS);
159     MSG_TO_STR(WODM_BREAKLOOP);
160     MSG_TO_STR(WODM_PREPARE);
161     MSG_TO_STR(WODM_UNPREPARE);
162     MSG_TO_STR(WODM_GETDEVCAPS);
163     MSG_TO_STR(WODM_GETNUMDEVS);
164     MSG_TO_STR(WODM_GETPITCH);
165     MSG_TO_STR(WODM_SETPITCH);
166     MSG_TO_STR(WODM_GETPLAYBACKRATE);
167     MSG_TO_STR(WODM_SETPLAYBACKRATE);
168     MSG_TO_STR(WODM_GETVOLUME);
169     MSG_TO_STR(WODM_SETVOLUME);
170     MSG_TO_STR(WODM_RESTART);
171     MSG_TO_STR(WODM_RESET);
172     MSG_TO_STR(DRV_QUERYDEVICEINTERFACESIZE);
173     MSG_TO_STR(DRV_QUERYDEVICEINTERFACE);
174     MSG_TO_STR(DRV_QUERYDSOUNDIFACE);
175     MSG_TO_STR(DRV_QUERYDSOUNDDESC);
176     }
177 #undef MSG_TO_STR
178     sprintf(unknown, "UNKNOWN(0x%04x)", msg);
179     return unknown;
180 }
181
182 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
183 {
184     TRACE("(%u, %p)\n", wDevID, dwParam1);
185
186     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].ossdev->interface_name, -1,
187                                     NULL, 0 ) * sizeof(WCHAR);
188     return MMSYSERR_NOERROR;
189 }
190
191 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
192 {
193     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].ossdev->interface_name, -1,
194                                         NULL, 0 ) * sizeof(WCHAR))
195     {
196         MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].ossdev->interface_name, -1,
197                             dwParam1, dwParam2 / sizeof(WCHAR));
198         return MMSYSERR_NOERROR;
199     }
200
201     return MMSYSERR_INVALPARAM;
202 }
203
204 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
205 {
206     TRACE("(%u, %p)\n", wDevID, dwParam1);
207
208     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].ossdev->interface_name, -1,
209                                     NULL, 0 ) * sizeof(WCHAR);
210     return MMSYSERR_NOERROR;
211 }
212
213 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
214 {
215     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].ossdev->interface_name, -1,
216                                         NULL, 0 ) * sizeof(WCHAR))
217     {
218         MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].ossdev->interface_name, -1,
219                             dwParam1, dwParam2 / sizeof(WCHAR));
220         return MMSYSERR_NOERROR;
221     }
222
223     return MMSYSERR_INVALPARAM;
224 }
225
226 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
227                              WAVEFORMATPCMEX* format)
228 {
229     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
230           lpTime->wType, format->Format.wBitsPerSample, format->Format.nSamplesPerSec,
231           format->Format.nChannels, format->Format.nAvgBytesPerSec);
232     TRACE("Position in bytes=%lu\n", position);
233
234     switch (lpTime->wType) {
235     case TIME_SAMPLES:
236         lpTime->u.sample = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
237         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
238         break;
239     case TIME_MS:
240         lpTime->u.ms = 1000.0 * position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels * format->Format.nSamplesPerSec);
241         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
242         break;
243     case TIME_SMPTE:
244         lpTime->u.smpte.fps = 30;
245         position = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
246         position += (format->Format.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
247         lpTime->u.smpte.sec = position / format->Format.nSamplesPerSec;
248         position -= lpTime->u.smpte.sec * format->Format.nSamplesPerSec;
249         lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
250         lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
251         lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
252         lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
253         lpTime->u.smpte.fps = 30;
254         lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->Format.nSamplesPerSec;
255         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
256               lpTime->u.smpte.hour, lpTime->u.smpte.min,
257               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
258         break;
259     default:
260         WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
261         lpTime->wType = TIME_BYTES;
262         /* fall through */
263     case TIME_BYTES:
264         lpTime->u.cb = position;
265         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
266         break;
267     }
268     return MMSYSERR_NOERROR;
269 }
270
271 static BOOL supportedFormat(LPWAVEFORMATEX wf)
272 {
273     TRACE("(%p)\n",wf);
274
275     if (wf->nSamplesPerSec<DSBFREQUENCY_MIN||wf->nSamplesPerSec>DSBFREQUENCY_MAX)
276         return FALSE;
277
278     if (wf->wFormatTag == WAVE_FORMAT_PCM) {
279         if (wf->nChannels >= 1 && wf->nChannels <= MAX_CHANNELS) {
280             if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
281                 return TRUE;
282         }
283     } else if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
284         WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE *)wf;
285
286         if (wf->cbSize == 22 && IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
287             if (wf->nChannels >=1 && wf->nChannels <= MAX_CHANNELS) {
288                 if (wf->wBitsPerSample==wfex->Samples.wValidBitsPerSample) {
289                     if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
290                         return TRUE;
291                 } else
292                     WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
293             }
294         } else
295             WARN("only KSDATAFORMAT_SUBTYPE_PCM supported\n");
296     } else
297         WARN("only WAVE_FORMAT_PCM and WAVE_FORMAT_EXTENSIBLE supported\n");
298
299     return FALSE;
300 }
301
302 void copy_format(LPWAVEFORMATEX wf1, LPWAVEFORMATPCMEX wf2)
303 {
304     ZeroMemory(wf2, sizeof(wf2));
305     if (wf1->wFormatTag == WAVE_FORMAT_PCM)
306         memcpy(wf2, wf1, sizeof(PCMWAVEFORMAT));
307     else if (wf1->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
308         memcpy(wf2, wf1, sizeof(WAVEFORMATPCMEX));
309     else
310         memcpy(wf2, wf1, sizeof(WAVEFORMATEX) + wf1->cbSize);
311 }
312
313 /*======================================================================*
314  *                  Low level WAVE implementation                       *
315  *======================================================================*/
316
317 /******************************************************************
318  *              OSS_RawOpenDevice
319  *
320  * Low level device opening (from values stored in ossdev)
321  */
322 static DWORD      OSS_RawOpenDevice(OSS_DEVICE* ossdev, int strict_format)
323 {
324     int fd, val, rc;
325     TRACE("(%p,%d)\n",ossdev,strict_format);
326
327     TRACE("open_access=%s\n",
328         ossdev->open_access == O_RDONLY ? "O_RDONLY" :
329         ossdev->open_access == O_WRONLY ? "O_WRONLY" :
330         ossdev->open_access == O_RDWR ? "O_RDWR" : "Unknown");
331
332     if ((fd = open(ossdev->dev_name, ossdev->open_access|O_NDELAY, 0)) == -1)
333     {
334         WARN("Couldn't open %s (%s)\n", ossdev->dev_name, strerror(errno));
335         return (errno == EBUSY) ? MMSYSERR_ALLOCATED : MMSYSERR_ERROR;
336     }
337     fcntl(fd, F_SETFD, 1); /* set close on exec flag */
338     /* turn full duplex on if it has been requested */
339     if (ossdev->open_access == O_RDWR && ossdev->full_duplex) {
340         rc = ioctl(fd, SNDCTL_DSP_SETDUPLEX, 0);
341         /* on *BSD, as full duplex is always enabled by default, this ioctl
342          * will fail with EINVAL
343          * so, we don't consider EINVAL an error here
344          */
345         if (rc != 0 && errno != EINVAL) {
346             WARN("ioctl(%s, SNDCTL_DSP_SETDUPLEX) failed (%s)\n", ossdev->dev_name, strerror(errno));
347             goto error2;
348         }
349     }
350
351     if (ossdev->audio_fragment) {
352         rc = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &ossdev->audio_fragment);
353         if (rc != 0) {
354             ERR("ioctl(%s, SNDCTL_DSP_SETFRAGMENT) failed (%s)\n", ossdev->dev_name, strerror(errno));
355             goto error2;
356         }
357     }
358
359     /* First size and channels then samplerate */
360     if (ossdev->format>=0)
361     {
362         val = ossdev->format;
363         rc = ioctl(fd, SNDCTL_DSP_SETFMT, &ossdev->format);
364         if (rc != 0 || val != ossdev->format) {
365             TRACE("Can't set format to %d (returned %d)\n", val, ossdev->format);
366             if (strict_format)
367                 goto error;
368         }
369     }
370     if (ossdev->channels>=0)
371     {
372         val = ossdev->channels;
373         rc = ioctl(fd, SNDCTL_DSP_CHANNELS, &ossdev->channels);
374         if (rc != 0 || val != ossdev->channels) {
375             TRACE("Can't set channels to %u (returned %d)\n", val, ossdev->channels);
376             if (strict_format)
377                 goto error;
378         }
379     }
380     if (ossdev->sample_rate>=0)
381     {
382         val = ossdev->sample_rate;
383         rc = ioctl(fd, SNDCTL_DSP_SPEED, &ossdev->sample_rate);
384         if (rc != 0 || !NEAR_MATCH(val, ossdev->sample_rate)) {
385             TRACE("Can't set sample_rate to %u (returned %d)\n", val, ossdev->sample_rate);
386             if (strict_format)
387                 goto error;
388         }
389     }
390     ossdev->fd = fd;
391
392     if (ossdev->bTriggerSupport) {
393         int trigger;
394         rc = ioctl(fd, SNDCTL_DSP_GETTRIGGER, &trigger);
395         if (rc != 0) {
396             ERR("ioctl(%s, SNDCTL_DSP_GETTRIGGER) failed (%s)\n",
397                 ossdev->dev_name, strerror(errno));
398             goto error;
399         }
400         
401         ossdev->bOutputEnabled = ((trigger & PCM_ENABLE_OUTPUT) == PCM_ENABLE_OUTPUT);
402         ossdev->bInputEnabled  = ((trigger & PCM_ENABLE_INPUT) == PCM_ENABLE_INPUT);
403
404         /* If we do not have full duplex, but they opened RDWR 
405         ** (as you have to in order for an mmap to succeed)
406         ** then we start out with input off
407         */
408         if (ossdev->open_access == O_RDWR && !ossdev->full_duplex && 
409             ossdev->bInputEnabled && ossdev->bOutputEnabled) {
410             ossdev->bInputEnabled  = FALSE;
411             trigger &= ~PCM_ENABLE_INPUT;
412             ioctl(fd, SNDCTL_DSP_SETTRIGGER, &trigger);
413         }
414     } else {
415         ossdev->bOutputEnabled = TRUE;  /* OSS enables by default */
416         ossdev->bInputEnabled  = TRUE;  /* OSS enables by default */
417     }
418
419     if (ossdev->open_access == O_RDONLY)
420         ossdev->bOutputEnabled = FALSE;
421     if (ossdev->open_access == O_WRONLY)
422         ossdev->bInputEnabled = FALSE;
423
424     return MMSYSERR_NOERROR;
425
426 error:
427     close(fd);
428     return WAVERR_BADFORMAT;
429 error2:
430     close(fd);
431     return MMSYSERR_ERROR;
432 }
433
434 /******************************************************************
435  *              OSS_OpenDevice
436  *
437  * since OSS has poor capabilities in full duplex, we try here to let a program
438  * open the device for both waveout and wavein streams...
439  * this is hackish, but it's the way OSS interface is done...
440  */
441 DWORD OSS_OpenDevice(OSS_DEVICE* ossdev, unsigned req_access,
442                             int* frag, int strict_format,
443                             int sample_rate, int channels, int fmt)
444 {
445     DWORD       ret;
446     DWORD open_access;
447     TRACE("(%p,%u,%p,%d,%d,%d,%x)\n",ossdev,req_access,frag,strict_format,sample_rate,channels,fmt);
448
449     if (ossdev->full_duplex && (req_access == O_RDONLY || req_access == O_WRONLY))
450     {
451         TRACE("Opening RDWR because full_duplex=%d and req_access=%d\n",
452               ossdev->full_duplex,req_access);
453         open_access = O_RDWR;
454     }
455     else
456     {
457         open_access=req_access;
458     }
459
460     /* FIXME: this should be protected, and it also contains a race with OSS_CloseDevice */
461     if (ossdev->open_count == 0)
462     {
463         if (access(ossdev->dev_name, 0) != 0) return MMSYSERR_NODRIVER;
464
465         ossdev->audio_fragment = (frag) ? *frag : 0;
466         ossdev->sample_rate = sample_rate;
467         ossdev->channels = channels;
468         ossdev->format = fmt;
469         ossdev->open_access = open_access;
470         ossdev->owner_tid = GetCurrentThreadId();
471
472         if ((ret = OSS_RawOpenDevice(ossdev,strict_format)) != MMSYSERR_NOERROR) return ret;
473         if (ossdev->full_duplex && ossdev->bTriggerSupport &&
474             (req_access == O_RDONLY || req_access == O_WRONLY))
475         {
476             int enable;
477             if (req_access == O_WRONLY)
478                 ossdev->bInputEnabled=0;
479             else
480                 ossdev->bOutputEnabled=0;
481             enable = getEnables(ossdev);
482             TRACE("Calling SNDCTL_DSP_SETTRIGGER with %x\n",enable);
483             if (ioctl(ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0)
484                 ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER, %d) failed (%s)\n",ossdev->dev_name, enable, strerror(errno));
485         }
486     }
487     else
488     {
489         /* check we really open with the same parameters */
490         if (ossdev->open_access != open_access)
491         {
492             ERR("FullDuplex: Mismatch in access. Your sound device is not full duplex capable.\n");
493             return WAVERR_BADFORMAT;
494         }
495
496         /* check if the audio parameters are the same */
497         if (ossdev->sample_rate != sample_rate ||
498             ossdev->channels != channels ||
499             ossdev->format != fmt)
500         {
501             /* This is not a fatal error because MSACM might do the remapping */
502             WARN("FullDuplex: mismatch in PCM parameters for input and output\n"
503                  "OSS doesn't allow us different parameters\n"
504                  "audio_frag(%x/%x) sample_rate(%d/%d) channels(%d/%d) fmt(%d/%d)\n",
505                  ossdev->audio_fragment, frag ? *frag : 0,
506                  ossdev->sample_rate, sample_rate,
507                  ossdev->channels, channels,
508                  ossdev->format, fmt);
509             return WAVERR_BADFORMAT;
510         }
511         /* check if the fragment sizes are the same */
512         if (ossdev->audio_fragment != (frag ? *frag : 0) ) {
513             ERR("FullDuplex: Playback and Capture hardware acceleration levels are different.\n"
514                 "Create string value : \"HardwareAcceleration\" = \"Emulation\" in the registry\n"
515                 "under [HKEY_CURRENT_USER\\Software\\Wine\\DirectSound].\n");
516             return WAVERR_BADFORMAT;
517         }
518         if (GetCurrentThreadId() != ossdev->owner_tid)
519         {
520             WARN("Another thread is trying to access audio...\n");
521             return MMSYSERR_ERROR;
522         }
523         if (ossdev->full_duplex && ossdev->bTriggerSupport &&
524             (req_access == O_RDONLY || req_access == O_WRONLY))
525         {
526             int enable;
527             if (req_access == O_WRONLY)
528                 ossdev->bOutputEnabled=1;
529             else
530                 ossdev->bInputEnabled=1;
531             enable = getEnables(ossdev);
532             TRACE("Calling SNDCTL_DSP_SETTRIGGER with %x\n",enable);
533             if (ioctl(ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0)
534                 ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER, %d) failed (%s)\n",ossdev->dev_name, enable, strerror(errno));
535         }
536     }
537
538     ossdev->open_count++;
539
540     return MMSYSERR_NOERROR;
541 }
542
543 /******************************************************************
544  *              OSS_CloseDevice
545  *
546  *
547  */
548 void    OSS_CloseDevice(OSS_DEVICE* ossdev)
549 {
550     TRACE("(%p)\n",ossdev);
551     if (ossdev->open_count>0) {
552         ossdev->open_count--;
553     } else {
554         WARN("OSS_CloseDevice called too many times\n");
555     }
556     if (ossdev->open_count == 0)
557     {
558         fcntl(ossdev->fd, F_SETFL, fcntl(ossdev->fd, F_GETFL) & ~O_NDELAY);
559         /* reset the device before we close it in case it is in a bad state */
560         ioctl(ossdev->fd, SNDCTL_DSP_RESET, 0);
561         if (close(ossdev->fd) != 0) FIXME("Cannot close %d: %s\n", ossdev->fd, strerror(errno));
562     }
563 }
564
565 /******************************************************************
566  *              OSS_ResetDevice
567  *
568  * Resets the device. OSS Commercial requires the device to be closed
569  * after a SNDCTL_DSP_RESET ioctl call... this function implements
570  * this behavior...
571  * FIXME: This causes problems when doing full duplex so we really
572  * only reset when not doing full duplex. We need to do this better
573  * someday.
574  */
575 static DWORD     OSS_ResetDevice(OSS_DEVICE* ossdev)
576 {
577     DWORD       ret = MMSYSERR_NOERROR;
578     int         old_fd = ossdev->fd;
579     TRACE("(%p)\n", ossdev);
580
581     if (ossdev->open_count == 1) {
582         if (ioctl(ossdev->fd, SNDCTL_DSP_RESET, NULL) == -1)
583         {
584             perror("ioctl SNDCTL_DSP_RESET");
585             return -1;
586         }
587         close(ossdev->fd);
588         ret = OSS_RawOpenDevice(ossdev, 1);
589         TRACE("Changing fd from %d to %d\n", old_fd, ossdev->fd);
590     } else
591         WARN("Not resetting device because it is in full duplex mode!\n");
592
593     return ret;
594 }
595
596 static const int win_std_oss_fmts[2]={AFMT_U8,AFMT_S16_LE};
597 static const int win_std_rates[5]={96000,48000,44100,22050,11025};
598 static const int win_std_formats[2][2][5]=
599     {{{WAVE_FORMAT_96M08, WAVE_FORMAT_48M08, WAVE_FORMAT_4M08,
600        WAVE_FORMAT_2M08,  WAVE_FORMAT_1M08},
601       {WAVE_FORMAT_96S08, WAVE_FORMAT_48S08, WAVE_FORMAT_4S08,
602        WAVE_FORMAT_2S08,  WAVE_FORMAT_1S08}},
603      {{WAVE_FORMAT_96M16, WAVE_FORMAT_48M16, WAVE_FORMAT_4M16,
604        WAVE_FORMAT_2M16,  WAVE_FORMAT_1M16},
605       {WAVE_FORMAT_96S16, WAVE_FORMAT_48S16, WAVE_FORMAT_4S16,
606        WAVE_FORMAT_2S16,  WAVE_FORMAT_1S16}},
607     };
608
609 static void OSS_Info(int fd)
610 {
611     /* Note that this only reports the formats supported by the hardware.
612      * The driver may support other formats and do the conversions in
613      * software which is why we don't use this value
614      */
615     int oss_mask, oss_caps;
616     if (ioctl(fd, SNDCTL_DSP_GETFMTS, &oss_mask) >= 0) {
617         TRACE("Formats=%08x ( ", oss_mask);
618         if (oss_mask & AFMT_MU_LAW) TRACE("AFMT_MU_LAW ");
619         if (oss_mask & AFMT_A_LAW) TRACE("AFMT_A_LAW ");
620         if (oss_mask & AFMT_IMA_ADPCM) TRACE("AFMT_IMA_ADPCM ");
621         if (oss_mask & AFMT_U8) TRACE("AFMT_U8 ");
622         if (oss_mask & AFMT_S16_LE) TRACE("AFMT_S16_LE ");
623         if (oss_mask & AFMT_S16_BE) TRACE("AFMT_S16_BE ");
624         if (oss_mask & AFMT_S8) TRACE("AFMT_S8 ");
625         if (oss_mask & AFMT_U16_LE) TRACE("AFMT_U16_LE ");
626         if (oss_mask & AFMT_U16_BE) TRACE("AFMT_U16_BE ");
627         if (oss_mask & AFMT_MPEG) TRACE("AFMT_MPEG ");
628 #ifdef AFMT_AC3
629         if (oss_mask & AFMT_AC3) TRACE("AFMT_AC3 ");
630 #endif
631 #ifdef AFMT_VORBIS
632         if (oss_mask & AFMT_VORBIS) TRACE("AFMT_VORBIS ");
633 #endif
634 #ifdef AFMT_S32_LE
635         if (oss_mask & AFMT_S32_LE) TRACE("AFMT_S32_LE ");
636 #endif
637 #ifdef AFMT_S32_BE
638         if (oss_mask & AFMT_S32_BE) TRACE("AFMT_S32_BE ");
639 #endif
640 #ifdef AFMT_FLOAT
641         if (oss_mask & AFMT_FLOAT) TRACE("AFMT_FLOAT ");
642 #endif
643 #ifdef AFMT_S24_LE
644         if (oss_mask & AFMT_S24_LE) TRACE("AFMT_S24_LE ");
645 #endif
646 #ifdef AFMT_S24_BE
647         if (oss_mask & AFMT_S24_BE) TRACE("AFMT_S24_BE ");
648 #endif
649 #ifdef AFMT_SPDIF_RAW
650         if (oss_mask & AFMT_SPDIF_RAW) TRACE("AFMT_SPDIF_RAW ");
651 #endif
652         TRACE(")\n");
653     }
654     if (ioctl(fd, SNDCTL_DSP_GETCAPS, &oss_caps) >= 0) {
655         TRACE("Caps=%08x\n",oss_caps);
656         TRACE("\tRevision: %d\n", oss_caps&DSP_CAP_REVISION);
657         TRACE("\tDuplex: %s\n", oss_caps & DSP_CAP_DUPLEX ? "true" : "false");
658         TRACE("\tRealtime: %s\n", oss_caps & DSP_CAP_REALTIME ? "true" : "false");
659         TRACE("\tBatch: %s\n", oss_caps & DSP_CAP_BATCH ? "true" : "false");
660         TRACE("\tCoproc: %s\n", oss_caps & DSP_CAP_COPROC ? "true" : "false");
661         TRACE("\tTrigger: %s\n", oss_caps & DSP_CAP_TRIGGER ? "true" : "false");
662         TRACE("\tMmap: %s\n", oss_caps & DSP_CAP_MMAP ? "true" : "false");
663 #ifdef DSP_CAP_MULTI
664         TRACE("\tMulti: %s\n", oss_caps & DSP_CAP_MULTI ? "true" : "false");
665 #endif
666 #ifdef DSP_CAP_BIND
667         TRACE("\tBind: %s\n", oss_caps & DSP_CAP_BIND ? "true" : "false");
668 #endif
669 #ifdef DSP_CAP_INPUT
670         TRACE("\tInput: %s\n", oss_caps & DSP_CAP_INPUT ? "true" : "false");
671 #endif
672 #ifdef DSP_CAP_OUTPUT
673         TRACE("\tOutput: %s\n", oss_caps & DSP_CAP_OUTPUT ? "true" : "false");
674 #endif
675 #ifdef DSP_CAP_VIRTUAL
676         TRACE("\tVirtual: %s\n", oss_caps & DSP_CAP_VIRTUAL ? "true" : "false");
677 #endif
678 #ifdef DSP_CAP_ANALOGOUT
679         TRACE("\tAnalog Out: %s\n", oss_caps & DSP_CAP_ANALOGOUT ? "true" : "false");
680 #endif
681 #ifdef DSP_CAP_ANALOGIN
682         TRACE("\tAnalog In: %s\n", oss_caps & DSP_CAP_ANALOGIN ? "true" : "false");
683 #endif
684 #ifdef DSP_CAP_DIGITALOUT
685         TRACE("\tDigital Out: %s\n", oss_caps & DSP_CAP_DIGITALOUT ? "true" : "false");
686 #endif
687 #ifdef DSP_CAP_DIGITALIN
688         TRACE("\tDigital In: %s\n", oss_caps & DSP_CAP_DIGITALIN ? "true" : "false");
689 #endif
690 #ifdef DSP_CAP_ADMASK
691         TRACE("\tA/D Mask: %s\n", oss_caps & DSP_CAP_ADMASK ? "true" : "false");
692 #endif
693 #ifdef DSP_CAP_SHADOW
694         TRACE("\tShadow: %s\n", oss_caps & DSP_CAP_SHADOW ? "true" : "false");
695 #endif
696 #ifdef DSP_CH_MASK
697         TRACE("\tChannel Mask: %x\n", oss_caps & DSP_CH_MASK);
698 #endif
699 #ifdef DSP_CAP_SLAVE
700         TRACE("\tSlave: %s\n", oss_caps & DSP_CAP_SLAVE ? "true" : "false");
701 #endif
702     }
703 }
704
705 /******************************************************************
706  *              OSS_WaveOutInit
707  *
708  *
709  */
710 static BOOL OSS_WaveOutInit(OSS_DEVICE* ossdev)
711 {
712     int rc,arg;
713     int f,c,r;
714     TRACE("(%p) %s\n", ossdev, ossdev->dev_name);
715
716     if (OSS_OpenDevice(ossdev, O_WRONLY, NULL, 0,-1,-1,-1) != 0)
717         return FALSE;
718
719     ioctl(ossdev->fd, SNDCTL_DSP_RESET, 0);
720
721 #ifdef SOUND_MIXER_INFO
722     {
723         int mixer;
724         if ((mixer = open(ossdev->mixer_name, O_RDONLY|O_NDELAY)) >= 0) {
725             mixer_info info;
726             if (ioctl(mixer, SOUND_MIXER_INFO, &info) >= 0) {
727                 lstrcpynA(ossdev->ds_desc.szDesc, info.name, sizeof(info.name));
728                 strcpy(ossdev->ds_desc.szDrvname, "wineoss.drv");
729                 MultiByteToWideChar(CP_ACP, 0, info.name, sizeof(info.name), 
730                                     ossdev->out_caps.szPname, 
731                                     sizeof(ossdev->out_caps.szPname) / sizeof(WCHAR));
732                 TRACE("%s: %s\n", ossdev->mixer_name, ossdev->ds_desc.szDesc);
733             } else {
734                 /* FreeBSD up to at least 5.2 provides this ioctl, but does not
735                  * implement it properly, and there are probably similar issues
736                  * on other platforms, so we warn but try to go ahead.
737                  */
738                 WARN("%s: cannot read SOUND_MIXER_INFO!\n", ossdev->mixer_name);
739             }
740             close(mixer);
741         } else {
742             ERR("open(%s) failed (%s)\n", ossdev->mixer_name , strerror(errno));
743             OSS_CloseDevice(ossdev);
744             return FALSE;
745         }
746     }
747 #endif /* SOUND_MIXER_INFO */
748
749     if (WINE_TRACE_ON(wave))
750         OSS_Info(ossdev->fd);
751
752     ossdev->out_caps.wMid = 0x00FF; /* Manufac ID */
753     ossdev->out_caps.wPid = 0x0001; /* Product ID */
754
755     ossdev->out_caps.vDriverVersion = 0x0100;
756     ossdev->out_caps.wChannels = 1;
757     ossdev->out_caps.dwFormats = 0x00000000;
758     ossdev->out_caps.wReserved1 = 0;
759     ossdev->out_caps.dwSupport = WAVECAPS_VOLUME;
760
761     /* direct sound caps */
762     ossdev->ds_caps.dwFlags = DSCAPS_CERTIFIED;
763     ossdev->ds_caps.dwPrimaryBuffers = 1;
764     ossdev->ds_caps.dwMinSecondarySampleRate = DSBFREQUENCY_MIN;
765     ossdev->ds_caps.dwMaxSecondarySampleRate = DSBFREQUENCY_MAX;
766
767     /* We must first set the format and the stereo mode as some sound cards
768      * may support 44kHz mono but not 44kHz stereo. Also we must
769      * systematically check the return value of these ioctls as they will
770      * always succeed (see OSS Linux) but will modify the parameter to match
771      * whatever they support. The OSS specs also say we must first set the
772      * sample size, then the stereo and then the sample rate.
773      */
774     for (f=0;f<2;f++) {
775         arg=win_std_oss_fmts[f];
776         rc=ioctl(ossdev->fd, SNDCTL_DSP_SAMPLESIZE, &arg);
777         if (rc!=0 || arg!=win_std_oss_fmts[f]) {
778             TRACE("DSP_SAMPLESIZE: rc=%d returned %d for %d\n",
779                   rc,arg,win_std_oss_fmts[f]);
780             continue;
781         }
782         if (f == 0)
783             ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARY8BIT;
784         else if (f == 1)
785             ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARY16BIT;
786
787         for (c = 1; c <= MAX_CHANNELS; c++) {
788             arg=c;
789             rc=ioctl(ossdev->fd, SNDCTL_DSP_CHANNELS, &arg);
790             if (rc!=0 || arg!=c) {
791                 TRACE("DSP_CHANNELS: rc=%d returned %d for %d\n",rc,arg,c);
792                 continue;
793             }
794             if (c == 1) {
795                 ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARYMONO;
796             } else if (c == 2) {
797                 ossdev->out_caps.wChannels = 2;
798                 ossdev->out_caps.dwSupport|=WAVECAPS_LRVOLUME;
799                 ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARYSTEREO;
800             } else
801                 ossdev->out_caps.wChannels = c;
802
803             for (r=0;r<sizeof(win_std_rates)/sizeof(*win_std_rates);r++) {
804                 arg=win_std_rates[r];
805                 rc=ioctl(ossdev->fd, SNDCTL_DSP_SPEED, &arg);
806                 TRACE("DSP_SPEED: rc=%d returned %d for %dx%dx%d\n",
807                       rc,arg,win_std_rates[r],win_std_oss_fmts[f],c);
808                 if (rc==0 && arg!=0 && NEAR_MATCH(arg,win_std_rates[r]) && c < 3)
809                     ossdev->out_caps.dwFormats|=win_std_formats[f][c-1][r];
810             }
811         }
812     }
813
814     if (ioctl(ossdev->fd, SNDCTL_DSP_GETCAPS, &arg) == 0) {
815         if (arg & DSP_CAP_TRIGGER)
816             ossdev->bTriggerSupport = TRUE;
817         if ((arg & DSP_CAP_REALTIME) && !(arg & DSP_CAP_BATCH)) {
818             ossdev->out_caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
819         }
820         /* well, might as well use the DirectSound cap flag for something */
821         if ((arg & DSP_CAP_TRIGGER) && (arg & DSP_CAP_MMAP) &&
822             !(arg & DSP_CAP_BATCH)) {
823             ossdev->out_caps.dwSupport |= WAVECAPS_DIRECTSOUND;
824         } else {
825             ossdev->ds_caps.dwFlags |= DSCAPS_EMULDRIVER;
826         }
827 #ifdef DSP_CAP_MULTI    /* not every oss has this */
828         /* check for hardware secondary buffer support (multi open) */
829         if ((arg & DSP_CAP_MULTI) &&
830             (ossdev->out_caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
831             TRACE("hardware secondary buffer support available\n");
832             if (ossdev->ds_caps.dwFlags & DSCAPS_PRIMARY8BIT)
833                 ossdev->ds_caps.dwFlags |= DSCAPS_SECONDARY8BIT;
834             if (ossdev->ds_caps.dwFlags & DSCAPS_PRIMARY16BIT)
835                 ossdev->ds_caps.dwFlags |= DSCAPS_SECONDARY16BIT;
836             if (ossdev->ds_caps.dwFlags & DSCAPS_PRIMARYMONO)
837                 ossdev->ds_caps.dwFlags |= DSCAPS_SECONDARYMONO;
838             if (ossdev->ds_caps.dwFlags & DSCAPS_PRIMARYSTEREO)
839                 ossdev->ds_caps.dwFlags |= DSCAPS_SECONDARYSTEREO;
840
841             ossdev->ds_caps.dwMaxHwMixingAllBuffers = 16;
842             ossdev->ds_caps.dwMaxHwMixingStaticBuffers = 0;
843             ossdev->ds_caps.dwMaxHwMixingStreamingBuffers = 16;
844
845             ossdev->ds_caps.dwFreeHwMixingAllBuffers = 16;
846             ossdev->ds_caps.dwFreeHwMixingStaticBuffers = 0;
847             ossdev->ds_caps.dwFreeHwMixingStreamingBuffers = 16;
848         }
849 #endif
850     }
851     OSS_CloseDevice(ossdev);
852     TRACE("out wChannels = %d, dwFormats = %08lX, dwSupport = %08lX\n",
853           ossdev->out_caps.wChannels, ossdev->out_caps.dwFormats,
854           ossdev->out_caps.dwSupport);
855     return TRUE;
856 }
857
858 /******************************************************************
859  *              OSS_WaveInInit
860  *
861  *
862  */
863 static BOOL OSS_WaveInInit(OSS_DEVICE* ossdev)
864 {
865     int rc,arg;
866     int f,c,r;
867     TRACE("(%p) %s\n", ossdev, ossdev->dev_name);
868
869     if (OSS_OpenDevice(ossdev, O_RDONLY, NULL, 0,-1,-1,-1) != 0)
870         return FALSE;
871
872     ioctl(ossdev->fd, SNDCTL_DSP_RESET, 0);
873
874 #ifdef SOUND_MIXER_INFO
875     {
876         int mixer;
877         if ((mixer = open(ossdev->mixer_name, O_RDONLY|O_NDELAY)) >= 0) {
878             mixer_info info;
879             if (ioctl(mixer, SOUND_MIXER_INFO, &info) >= 0) {
880                 MultiByteToWideChar(CP_ACP, 0, info.name, -1, 
881                                     ossdev->in_caps.szPname, 
882                                     sizeof(ossdev->in_caps.szPname) / sizeof(WCHAR));
883                 TRACE("%s: %s\n", ossdev->mixer_name, ossdev->ds_desc.szDesc);
884             } else {
885                 /* FreeBSD up to at least 5.2 provides this ioctl, but does not
886                  * implement it properly, and there are probably similar issues
887                  * on other platforms, so we warn but try to go ahead.
888                  */
889                 WARN("%s: cannot read SOUND_MIXER_INFO!\n", ossdev->mixer_name);
890             }
891             close(mixer);
892         } else {
893             ERR("open(%s) failed (%s)\n", ossdev->mixer_name, strerror(errno));
894             OSS_CloseDevice(ossdev);
895             return FALSE;
896         }
897     }
898 #endif /* SOUND_MIXER_INFO */
899
900     if (WINE_TRACE_ON(wave))
901         OSS_Info(ossdev->fd);
902
903     ossdev->in_caps.wMid = 0x00FF; /* Manufac ID */
904     ossdev->in_caps.wPid = 0x0001; /* Product ID */
905
906     ossdev->in_caps.dwFormats = 0x00000000;
907     ossdev->in_caps.wChannels = 1;
908     ossdev->in_caps.wReserved1 = 0;
909
910     /* direct sound caps */
911     ossdev->dsc_caps.dwSize = sizeof(ossdev->dsc_caps);
912     ossdev->dsc_caps.dwFlags = 0;
913     ossdev->dsc_caps.dwFormats = 0x00000000;
914     ossdev->dsc_caps.dwChannels = 1;
915
916     /* See the comment in OSS_WaveOutInit for the loop order */
917     for (f=0;f<2;f++) {
918         arg=win_std_oss_fmts[f];
919         rc=ioctl(ossdev->fd, SNDCTL_DSP_SAMPLESIZE, &arg);
920         if (rc!=0 || arg!=win_std_oss_fmts[f]) {
921             TRACE("DSP_SAMPLESIZE: rc=%d returned 0x%x for 0x%x\n",
922                   rc,arg,win_std_oss_fmts[f]);
923             continue;
924         }
925
926         for (c = 1; c <= MAX_CHANNELS; c++) {
927             arg=c;
928             rc=ioctl(ossdev->fd, SNDCTL_DSP_CHANNELS, &arg);
929             if (rc!=0 || arg!=c) {
930                 TRACE("DSP_CHANNELS: rc=%d returned %d for %d\n",rc,arg,c);
931                 continue;
932             }
933             if (c > 1) {
934                 ossdev->in_caps.wChannels = c;
935                 ossdev->dsc_caps.dwChannels = c;
936             }
937
938             for (r=0;r<sizeof(win_std_rates)/sizeof(*win_std_rates);r++) {
939                 arg=win_std_rates[r];
940                 rc=ioctl(ossdev->fd, SNDCTL_DSP_SPEED, &arg);
941                 TRACE("DSP_SPEED: rc=%d returned %d for %dx%dx%d\n",rc,arg,win_std_rates[r],win_std_oss_fmts[f],c);
942                 if (rc==0 && NEAR_MATCH(arg,win_std_rates[r]) && c < 3)
943                     ossdev->in_caps.dwFormats|=win_std_formats[f][c-1][r];
944                     ossdev->dsc_caps.dwFormats|=win_std_formats[f][c-1][r];
945             }
946         }
947     }
948
949     if (ioctl(ossdev->fd, SNDCTL_DSP_GETCAPS, &arg) == 0) {
950         if (arg & DSP_CAP_TRIGGER)
951             ossdev->bTriggerSupport = TRUE;
952         if ((arg & DSP_CAP_TRIGGER) && (arg & DSP_CAP_MMAP) &&
953             !(arg & DSP_CAP_BATCH)) {
954             /* FIXME: enable the next statement if you want to work on the driver */
955 #if 0
956             ossdev->in_caps_support |= WAVECAPS_DIRECTSOUND;
957 #endif
958         }
959         if ((arg & DSP_CAP_REALTIME) && !(arg & DSP_CAP_BATCH))
960             ossdev->in_caps_support |= WAVECAPS_SAMPLEACCURATE;
961     }
962     OSS_CloseDevice(ossdev);
963     TRACE("in wChannels = %d, dwFormats = %08lX, in_caps_support = %08lX\n",
964         ossdev->in_caps.wChannels, ossdev->in_caps.dwFormats, ossdev->in_caps_support);
965     return TRUE;
966 }
967
968 /******************************************************************
969  *              OSS_WaveFullDuplexInit
970  *
971  *
972  */
973 static void OSS_WaveFullDuplexInit(OSS_DEVICE* ossdev)
974 {
975     int rc,arg;
976     int f,c,r;
977     int caps;
978     TRACE("(%p) %s\n", ossdev, ossdev->dev_name);
979
980     /* The OSS documentation says we must call SNDCTL_SETDUPLEX
981      * *before* checking for SNDCTL_DSP_GETCAPS otherwise we may
982      * get the wrong result. This ioctl must even be done before
983      * setting the fragment size so that only OSS_RawOpenDevice is
984      * in a position to do it. So we set full_duplex speculatively
985      * and adjust right after.
986      */
987     ossdev->full_duplex=1;
988     rc=OSS_OpenDevice(ossdev, O_RDWR, NULL, 0,-1,-1,-1);
989     ossdev->full_duplex=0;
990     if (rc != 0)
991         return;
992
993     ioctl(ossdev->fd, SNDCTL_DSP_RESET, 0);
994     TRACE("%s\n", ossdev->ds_desc.szDesc);
995
996     if (ioctl(ossdev->fd, SNDCTL_DSP_GETCAPS, &caps) == 0)
997         ossdev->full_duplex = (caps & DSP_CAP_DUPLEX);
998
999     ossdev->duplex_out_caps = ossdev->out_caps;
1000
1001     ossdev->duplex_out_caps.wChannels = 1;
1002     ossdev->duplex_out_caps.dwFormats = 0x00000000;
1003     ossdev->duplex_out_caps.dwSupport = WAVECAPS_VOLUME;
1004
1005     if (WINE_TRACE_ON(wave))
1006         OSS_Info(ossdev->fd);
1007
1008     /* See the comment in OSS_WaveOutInit for the loop order */
1009     for (f=0;f<2;f++) {
1010         arg=win_std_oss_fmts[f];
1011         rc=ioctl(ossdev->fd, SNDCTL_DSP_SAMPLESIZE, &arg);
1012         if (rc!=0 || arg!=win_std_oss_fmts[f]) {
1013             TRACE("DSP_SAMPLESIZE: rc=%d returned 0x%x for 0x%x\n",
1014                   rc,arg,win_std_oss_fmts[f]);
1015             continue;
1016         }
1017
1018         for (c = 1; c <= MAX_CHANNELS; c++) {
1019             arg=c;
1020             rc=ioctl(ossdev->fd, SNDCTL_DSP_CHANNELS, &arg);
1021             if (rc!=0 || arg!=c) {
1022                 TRACE("DSP_CHANNELS: rc=%d returned %d for %d\n",rc,arg,c);
1023                 continue;
1024             }
1025             if (c == 1) {
1026                 ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARYMONO;
1027             } else if (c == 2) {
1028                 ossdev->duplex_out_caps.wChannels = 2;
1029                 ossdev->duplex_out_caps.dwSupport|=WAVECAPS_LRVOLUME;
1030                 ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARYSTEREO;
1031             } else
1032                 ossdev->duplex_out_caps.wChannels = c;
1033
1034             for (r=0;r<sizeof(win_std_rates)/sizeof(*win_std_rates);r++) {
1035                 arg=win_std_rates[r];
1036                 rc=ioctl(ossdev->fd, SNDCTL_DSP_SPEED, &arg);
1037                 TRACE("DSP_SPEED: rc=%d returned %d for %dx%dx%d\n",
1038                       rc,arg,win_std_rates[r],win_std_oss_fmts[f],c);
1039                 if (rc==0 && arg!=0 && NEAR_MATCH(arg,win_std_rates[r]) && c < 3)
1040                     ossdev->duplex_out_caps.dwFormats|=win_std_formats[f][c-1][r];
1041             }
1042         }
1043     }
1044
1045     if (ioctl(ossdev->fd, SNDCTL_DSP_GETCAPS, &arg) == 0) {
1046         if ((arg & DSP_CAP_REALTIME) && !(arg & DSP_CAP_BATCH)) {
1047             ossdev->duplex_out_caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
1048         }
1049         /* well, might as well use the DirectSound cap flag for something */
1050         if ((arg & DSP_CAP_TRIGGER) && (arg & DSP_CAP_MMAP) &&
1051             !(arg & DSP_CAP_BATCH)) {
1052             ossdev->duplex_out_caps.dwSupport |= WAVECAPS_DIRECTSOUND;
1053         }
1054     }
1055     OSS_CloseDevice(ossdev);
1056     TRACE("duplex wChannels = %d, dwFormats = %08lX, dwSupport = %08lX\n",
1057           ossdev->duplex_out_caps.wChannels,
1058           ossdev->duplex_out_caps.dwFormats,
1059           ossdev->duplex_out_caps.dwSupport);
1060 }
1061
1062 static char* StrDup(const char* str, const char* def)
1063 {
1064     char* dst;
1065     if (str==NULL)
1066         str=def;
1067     dst=HeapAlloc(GetProcessHeap(),0,strlen(str)+1);
1068     strcpy(dst, str);
1069     return dst;
1070 }
1071
1072 /******************************************************************
1073  *              OSS_WaveInit
1074  *
1075  * Initialize internal structures from OSS information
1076  */
1077 LONG OSS_WaveInit(void)
1078 {
1079     char* str;
1080     int i;
1081
1082     TRACE("()\n");
1083
1084     str=getenv("AUDIODEV");
1085     if (str!=NULL)
1086     {
1087         OSS_Devices[0].dev_name=StrDup(str,"");
1088         OSS_Devices[0].mixer_name=StrDup(getenv("MIXERDEV"),"/dev/mixer");
1089         for (i = 1; i < MAX_WAVEDRV; ++i)
1090         {
1091             OSS_Devices[i].dev_name=StrDup("",NULL);
1092             OSS_Devices[i].mixer_name=StrDup("",NULL);
1093         }
1094     }
1095     else
1096     {
1097         OSS_Devices[0].dev_name=StrDup("/dev/dsp",NULL);
1098         OSS_Devices[0].mixer_name=StrDup("/dev/mixer",NULL);
1099         for (i = 1; i < MAX_WAVEDRV; ++i)
1100         {
1101             OSS_Devices[i].dev_name=HeapAlloc(GetProcessHeap(),0,11);
1102             sprintf(OSS_Devices[i].dev_name, "/dev/dsp%d", i);
1103             OSS_Devices[i].mixer_name=HeapAlloc(GetProcessHeap(),0,13);
1104             sprintf(OSS_Devices[i].mixer_name, "/dev/mixer%d", i);
1105         }
1106     }
1107
1108     for (i = 0; i < MAX_WAVEDRV; ++i)
1109     {
1110         OSS_Devices[i].interface_name=HeapAlloc(GetProcessHeap(),0,9+strlen(OSS_Devices[i].dev_name)+1);
1111         sprintf(OSS_Devices[i].interface_name, "wineoss: %s", OSS_Devices[i].dev_name);
1112     }
1113
1114     /* start with output devices */
1115     for (i = 0; i < MAX_WAVEDRV; ++i)
1116     {
1117         if (*OSS_Devices[i].dev_name=='\0' || OSS_WaveOutInit(&OSS_Devices[i]))
1118         {
1119             WOutDev[numOutDev].state = WINE_WS_CLOSED;
1120             WOutDev[numOutDev].ossdev = &OSS_Devices[i];
1121             WOutDev[numOutDev].volume = 0xffffffff;
1122             numOutDev++;
1123         }
1124     }
1125
1126     /* then do input devices */
1127     for (i = 0; i < MAX_WAVEDRV; ++i)
1128     {
1129         if (*OSS_Devices[i].dev_name=='\0' || OSS_WaveInInit(&OSS_Devices[i]))
1130         {
1131             WInDev[numInDev].state = WINE_WS_CLOSED;
1132             WInDev[numInDev].ossdev = &OSS_Devices[i];
1133             numInDev++;
1134         }
1135     }
1136
1137     /* finish with the full duplex bits */
1138     for (i = 0; i < MAX_WAVEDRV; i++)
1139         if (*OSS_Devices[i].dev_name!='\0')
1140             OSS_WaveFullDuplexInit(&OSS_Devices[i]);
1141
1142     TRACE("%d wave out devices\n", numOutDev);
1143     for (i = 0; i < numOutDev; i++) {
1144         TRACE("%d: %s, %s, %s\n", i, WOutDev[i].ossdev->dev_name,
1145               WOutDev[i].ossdev->mixer_name, WOutDev[i].ossdev->interface_name);
1146     }
1147
1148     TRACE("%d wave in devices\n", numInDev);
1149     for (i = 0; i < numInDev; i++) {
1150         TRACE("%d: %s, %s, %s\n", i, WInDev[i].ossdev->dev_name,
1151               WInDev[i].ossdev->mixer_name, WInDev[i].ossdev->interface_name);
1152     }
1153
1154     return 0;
1155 }
1156
1157 /******************************************************************
1158  *              OSS_InitRingMessage
1159  *
1160  * Initialize the ring of messages for passing between driver's caller and playback/record
1161  * thread
1162  */
1163 static int OSS_InitRingMessage(OSS_MSG_RING* omr)
1164 {
1165     omr->msg_toget = 0;
1166     omr->msg_tosave = 0;
1167 #ifdef USE_PIPE_SYNC
1168     if (pipe(omr->msg_pipe) < 0) {
1169         omr->msg_pipe[0] = -1;
1170         omr->msg_pipe[1] = -1;
1171         ERR("could not create pipe, error=%s\n", strerror(errno));
1172     }
1173 #else
1174     omr->msg_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1175 #endif
1176     omr->ring_buffer_size = OSS_RING_BUFFER_INCREMENT;
1177     omr->messages = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,omr->ring_buffer_size * sizeof(OSS_MSG));
1178     InitializeCriticalSection(&omr->msg_crst);
1179     omr->msg_crst.DebugInfo->Spare[1] = (DWORD)"WINEOSS_msg_crst";
1180     return 0;
1181 }
1182
1183 /******************************************************************
1184  *              OSS_DestroyRingMessage
1185  *
1186  */
1187 static int OSS_DestroyRingMessage(OSS_MSG_RING* omr)
1188 {
1189 #ifdef USE_PIPE_SYNC
1190     close(omr->msg_pipe[0]);
1191     close(omr->msg_pipe[1]);
1192 #else
1193     CloseHandle(omr->msg_event);
1194 #endif
1195     HeapFree(GetProcessHeap(),0,omr->messages);
1196     DeleteCriticalSection(&omr->msg_crst);
1197     return 0;
1198 }
1199
1200 /******************************************************************
1201  *              OSS_AddRingMessage
1202  *
1203  * Inserts a new message into the ring (should be called from DriverProc derivated routines)
1204  */
1205 static int OSS_AddRingMessage(OSS_MSG_RING* omr, enum win_wm_message msg, DWORD param, BOOL wait)
1206 {
1207     HANDLE      hEvent = INVALID_HANDLE_VALUE;
1208
1209     EnterCriticalSection(&omr->msg_crst);
1210     if ((omr->msg_toget == ((omr->msg_tosave + 1) % omr->ring_buffer_size)))
1211     {
1212         int old_ring_buffer_size = omr->ring_buffer_size;
1213         omr->ring_buffer_size += OSS_RING_BUFFER_INCREMENT;
1214         TRACE("omr->ring_buffer_size=%d\n",omr->ring_buffer_size);
1215         omr->messages = HeapReAlloc(GetProcessHeap(),0,omr->messages, omr->ring_buffer_size * sizeof(OSS_MSG));
1216         /* Now we need to rearrange the ring buffer so that the new
1217            buffers just allocated are in between omr->msg_tosave and
1218            omr->msg_toget.
1219         */
1220         if (omr->msg_tosave < omr->msg_toget)
1221         {
1222             memmove(&(omr->messages[omr->msg_toget + OSS_RING_BUFFER_INCREMENT]),
1223                     &(omr->messages[omr->msg_toget]),
1224                     sizeof(OSS_MSG)*(old_ring_buffer_size - omr->msg_toget)
1225                     );
1226             omr->msg_toget += OSS_RING_BUFFER_INCREMENT;
1227         }
1228     }
1229     if (wait)
1230     {
1231         hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1232         if (hEvent == INVALID_HANDLE_VALUE)
1233         {
1234             ERR("can't create event !?\n");
1235             LeaveCriticalSection(&omr->msg_crst);
1236             return 0;
1237         }
1238         if (omr->msg_toget != omr->msg_tosave && omr->messages[omr->msg_toget].msg != WINE_WM_HEADER)
1239             FIXME("two fast messages in the queue!!!! toget = %d(%s), tosave=%d(%s)\n",
1240             omr->msg_toget,getCmdString(omr->messages[omr->msg_toget].msg),
1241             omr->msg_tosave,getCmdString(omr->messages[omr->msg_tosave].msg));
1242
1243         /* fast messages have to be added at the start of the queue */
1244         omr->msg_toget = (omr->msg_toget + omr->ring_buffer_size - 1) % omr->ring_buffer_size;
1245         omr->messages[omr->msg_toget].msg = msg;
1246         omr->messages[omr->msg_toget].param = param;
1247         omr->messages[omr->msg_toget].hEvent = hEvent;
1248     }
1249     else
1250     {
1251         omr->messages[omr->msg_tosave].msg = msg;
1252         omr->messages[omr->msg_tosave].param = param;
1253         omr->messages[omr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
1254         omr->msg_tosave = (omr->msg_tosave + 1) % omr->ring_buffer_size;
1255     }
1256     LeaveCriticalSection(&omr->msg_crst);
1257     /* signal a new message */
1258     SIGNAL_OMR(omr);
1259     if (wait)
1260     {
1261         /* wait for playback/record thread to have processed the message */
1262         WaitForSingleObject(hEvent, INFINITE);
1263         CloseHandle(hEvent);
1264     }
1265     return 1;
1266 }
1267
1268 /******************************************************************
1269  *              OSS_RetrieveRingMessage
1270  *
1271  * Get a message from the ring. Should be called by the playback/record thread.
1272  */
1273 static int OSS_RetrieveRingMessage(OSS_MSG_RING* omr,
1274                                    enum win_wm_message *msg, DWORD *param, HANDLE *hEvent)
1275 {
1276     EnterCriticalSection(&omr->msg_crst);
1277
1278     if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
1279     {
1280         LeaveCriticalSection(&omr->msg_crst);
1281         return 0;
1282     }
1283
1284     *msg = omr->messages[omr->msg_toget].msg;
1285     omr->messages[omr->msg_toget].msg = 0;
1286     *param = omr->messages[omr->msg_toget].param;
1287     *hEvent = omr->messages[omr->msg_toget].hEvent;
1288     omr->msg_toget = (omr->msg_toget + 1) % omr->ring_buffer_size;
1289     CLEAR_OMR(omr);
1290     LeaveCriticalSection(&omr->msg_crst);
1291     return 1;
1292 }
1293
1294 /******************************************************************
1295  *              OSS_PeekRingMessage
1296  *
1297  * Peek at a message from the ring but do not remove it.
1298  * Should be called by the playback/record thread.
1299  */
1300 static int OSS_PeekRingMessage(OSS_MSG_RING* omr,
1301                                enum win_wm_message *msg,
1302                                DWORD *param, HANDLE *hEvent)
1303 {
1304     EnterCriticalSection(&omr->msg_crst);
1305
1306     if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
1307     {
1308         LeaveCriticalSection(&omr->msg_crst);
1309         return 0;
1310     }
1311
1312     *msg = omr->messages[omr->msg_toget].msg;
1313     *param = omr->messages[omr->msg_toget].param;
1314     *hEvent = omr->messages[omr->msg_toget].hEvent;
1315     LeaveCriticalSection(&omr->msg_crst);
1316     return 1;
1317 }
1318
1319 /*======================================================================*
1320  *                  Low level WAVE OUT implementation                   *
1321  *======================================================================*/
1322
1323 /**************************************************************************
1324  *                      wodNotifyClient                 [internal]
1325  */
1326 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1327 {
1328     TRACE("wMsg = 0x%04x (%s) dwParm1 = %04lX dwParam2 = %04lX\n", wMsg,
1329         wMsg == WOM_OPEN ? "WOM_OPEN" : wMsg == WOM_CLOSE ? "WOM_CLOSE" :
1330         wMsg == WOM_DONE ? "WOM_DONE" : "Unknown", dwParam1, dwParam2);
1331
1332     switch (wMsg) {
1333     case WOM_OPEN:
1334     case WOM_CLOSE:
1335     case WOM_DONE:
1336         if (wwo->wFlags != DCB_NULL &&
1337             !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
1338                             (HDRVR)wwo->waveDesc.hWave, wMsg,
1339                             wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
1340             WARN("can't notify client !\n");
1341             return MMSYSERR_ERROR;
1342         }
1343         break;
1344     default:
1345         FIXME("Unknown callback message %u\n", wMsg);
1346         return MMSYSERR_INVALPARAM;
1347     }
1348     return MMSYSERR_NOERROR;
1349 }
1350
1351 /**************************************************************************
1352  *                              wodUpdatePlayedTotal    [internal]
1353  *
1354  */
1355 static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo, audio_buf_info* info)
1356 {
1357     audio_buf_info dspspace;
1358     DWORD notplayed;
1359     if (!info) info = &dspspace;
1360
1361     if (ioctl(wwo->ossdev->fd, SNDCTL_DSP_GETOSPACE, info) < 0) {
1362         ERR("ioctl(%s, SNDCTL_DSP_GETOSPACE) failed (%s)\n", wwo->ossdev->dev_name, strerror(errno));
1363         return FALSE;
1364     }
1365
1366     /* GETOSPACE is not always accurate when we're down to the last fragment or two;
1367     **   we try to accommodate that here by assuming that the dsp is empty by looking
1368     **   at the clock rather than the result of GETOSPACE */
1369     notplayed = wwo->dwBufferSize - info->bytes;
1370     if (notplayed > 0 && notplayed < (info->fragsize * 2))
1371     {
1372         if (wwo->dwProjectedFinishTime && GetTickCount() >= wwo->dwProjectedFinishTime)
1373         {
1374             TRACE("Adjusting for a presumed OSS bug and assuming all data has been played.\n");
1375             wwo->dwPlayedTotal = wwo->dwWrittenTotal;
1376             return TRUE;
1377         }
1378         else
1379             /* Some OSS drivers will clean up nicely if given a POST, so give 'em the chance... */
1380             ioctl(wwo->ossdev->fd, SNDCTL_DSP_POST, 0);
1381     }
1382
1383     wwo->dwPlayedTotal = wwo->dwWrittenTotal - notplayed;
1384     return TRUE;
1385 }
1386
1387 /**************************************************************************
1388  *                              wodPlayer_BeginWaveHdr          [internal]
1389  *
1390  * Makes the specified lpWaveHdr the currently playing wave header.
1391  * If the specified wave header is a begin loop and we're not already in
1392  * a loop, setup the loop.
1393  */
1394 static void wodPlayer_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1395 {
1396     wwo->lpPlayPtr = lpWaveHdr;
1397
1398     if (!lpWaveHdr) return;
1399
1400     if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
1401         if (wwo->lpLoopPtr) {
1402             WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1403         } else {
1404             TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1405             wwo->lpLoopPtr = lpWaveHdr;
1406             /* Windows does not touch WAVEHDR.dwLoops,
1407              * so we need to make an internal copy */
1408             wwo->dwLoops = lpWaveHdr->dwLoops;
1409         }
1410     }
1411     wwo->dwPartialOffset = 0;
1412 }
1413
1414 /**************************************************************************
1415  *                              wodPlayer_PlayPtrNext           [internal]
1416  *
1417  * Advance the play pointer to the next waveheader, looping if required.
1418  */
1419 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEOUT* wwo)
1420 {
1421     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1422
1423     wwo->dwPartialOffset = 0;
1424     if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
1425         /* We're at the end of a loop, loop if required */
1426         if (--wwo->dwLoops > 0) {
1427             wwo->lpPlayPtr = wwo->lpLoopPtr;
1428         } else {
1429             /* Handle overlapping loops correctly */
1430             if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
1431                 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
1432                 /* shall we consider the END flag for the closing loop or for
1433                  * the opening one or for both ???
1434                  * code assumes for closing loop only
1435                  */
1436             } else {
1437                 lpWaveHdr = lpWaveHdr->lpNext;
1438             }
1439             wwo->lpLoopPtr = NULL;
1440             wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
1441         }
1442     } else {
1443         /* We're not in a loop.  Advance to the next wave header */
1444         wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
1445     }
1446
1447     return lpWaveHdr;
1448 }
1449
1450 /**************************************************************************
1451  *                           wodPlayer_TicksTillEmpty           [internal]
1452  * Returns the number of ticks until we think the DSP should be empty
1453  */
1454 static DWORD wodPlayer_TicksTillEmpty(const WINE_WAVEOUT *wwo)
1455 {
1456     return ((wwo->dwWrittenTotal - wwo->dwPlayedTotal) * 1000)
1457         / wwo->waveFormat.Format.nAvgBytesPerSec;
1458 }
1459
1460 /**************************************************************************
1461  *                           wodPlayer_DSPWait                  [internal]
1462  * Returns the number of milliseconds to wait for the DSP buffer to write
1463  * one fragment.
1464  */
1465 static DWORD wodPlayer_DSPWait(const WINE_WAVEOUT *wwo)
1466 {
1467     /* time for one fragment to be played */
1468     return wwo->dwFragmentSize * 1000 / wwo->waveFormat.Format.nAvgBytesPerSec;
1469 }
1470
1471 /**************************************************************************
1472  *                           wodPlayer_NotifyWait               [internal]
1473  * Returns the number of milliseconds to wait before attempting to notify
1474  * completion of the specified wavehdr.
1475  * This is based on the number of bytes remaining to be written in the
1476  * wave.
1477  */
1478 static DWORD wodPlayer_NotifyWait(const WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1479 {
1480     DWORD dwMillis;
1481
1482     if (lpWaveHdr->reserved < wwo->dwPlayedTotal) {
1483         dwMillis = 1;
1484     } else {
1485         dwMillis = (lpWaveHdr->reserved - wwo->dwPlayedTotal) * 1000 / wwo->waveFormat.Format.nAvgBytesPerSec;
1486         if (!dwMillis) dwMillis = 1;
1487     }
1488
1489     return dwMillis;
1490 }
1491
1492
1493 /**************************************************************************
1494  *                           wodPlayer_WriteMaxFrags            [internal]
1495  * Writes the maximum number of bytes possible to the DSP and returns
1496  * TRUE iff the current playPtr has been fully played
1497  */
1498 static BOOL wodPlayer_WriteMaxFrags(WINE_WAVEOUT* wwo, DWORD* bytes)
1499 {
1500     DWORD       dwLength = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
1501     DWORD       toWrite = min(dwLength, *bytes);
1502     int         written;
1503     BOOL        ret = FALSE;
1504
1505     TRACE("Writing wavehdr %p.%lu[%lu]/%lu\n",
1506           wwo->lpPlayPtr, wwo->dwPartialOffset, wwo->lpPlayPtr->dwBufferLength, toWrite);
1507
1508     if (toWrite > 0)
1509     {
1510         written = write(wwo->ossdev->fd, wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toWrite);
1511         if (written <= 0) {
1512             TRACE("write(%s, %p, %ld) failed (%s) returned %d\n", wwo->ossdev->dev_name,
1513                 wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toWrite, strerror(errno), written);
1514             return FALSE;
1515         }
1516     }
1517     else
1518         written = 0;
1519
1520     if (written >= dwLength) {
1521         /* If we wrote all current wavehdr, skip to the next one */
1522         wodPlayer_PlayPtrNext(wwo);
1523         ret = TRUE;
1524     } else {
1525         /* Remove the amount written */
1526         wwo->dwPartialOffset += written;
1527     }
1528     *bytes -= written;
1529     wwo->dwWrittenTotal += written;
1530     TRACE("dwWrittenTotal=%lu\n", wwo->dwWrittenTotal);
1531     return ret;
1532 }
1533
1534
1535 /**************************************************************************
1536  *                              wodPlayer_NotifyCompletions     [internal]
1537  *
1538  * Notifies and remove from queue all wavehdrs which have been played to
1539  * the speaker (ie. they have cleared the OSS buffer).  If force is true,
1540  * we notify all wavehdrs and remove them all from the queue even if they
1541  * are unplayed or part of a loop.
1542  */
1543 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1544 {
1545     LPWAVEHDR           lpWaveHdr;
1546
1547     /* Start from lpQueuePtr and keep notifying until:
1548      * - we hit an unwritten wavehdr
1549      * - we hit the beginning of a running loop
1550      * - we hit a wavehdr which hasn't finished playing
1551      */
1552 #if 0
1553     while ((lpWaveHdr = wwo->lpQueuePtr) && 
1554            (force || 
1555             (lpWaveHdr != wwo->lpPlayPtr &&
1556              lpWaveHdr != wwo->lpLoopPtr &&
1557              lpWaveHdr->reserved <= wwo->dwPlayedTotal))) {
1558
1559         wwo->lpQueuePtr = lpWaveHdr->lpNext;
1560
1561         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1562         lpWaveHdr->dwFlags |= WHDR_DONE;
1563
1564         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1565     }
1566 #else
1567     for (;;)
1568     {
1569         lpWaveHdr = wwo->lpQueuePtr;
1570         if (!lpWaveHdr) {TRACE("Empty queue\n"); break;}
1571         if (!force)
1572         {
1573             if (lpWaveHdr == wwo->lpPlayPtr) {TRACE("play %p\n", lpWaveHdr); break;}
1574             if (lpWaveHdr == wwo->lpLoopPtr) {TRACE("loop %p\n", lpWaveHdr); break;}
1575             if (lpWaveHdr->reserved > wwo->dwPlayedTotal){TRACE("still playing %p (%lu/%lu)\n", lpWaveHdr, lpWaveHdr->reserved, wwo->dwPlayedTotal);break;}
1576         }
1577         wwo->lpQueuePtr = lpWaveHdr->lpNext;
1578
1579         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1580         lpWaveHdr->dwFlags |= WHDR_DONE;
1581
1582         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1583     }
1584 #endif
1585     return  (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ? 
1586         wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
1587 }
1588
1589 /**************************************************************************
1590  *                              wodPlayer_Reset                 [internal]
1591  *
1592  * wodPlayer helper. Resets current output stream.
1593  */
1594 static  void    wodPlayer_Reset(WINE_WAVEOUT* wwo, BOOL reset)
1595 {
1596     wodUpdatePlayedTotal(wwo, NULL);
1597     /* updates current notify list */
1598     wodPlayer_NotifyCompletions(wwo, FALSE);
1599
1600     /* flush all possible output */
1601     if (OSS_ResetDevice(wwo->ossdev) != MMSYSERR_NOERROR)
1602     {
1603         wwo->hThread = 0;
1604         wwo->state = WINE_WS_STOPPED;
1605         ExitThread(-1);
1606     }
1607
1608     if (reset) {
1609         enum win_wm_message     msg;
1610         DWORD                   param;
1611         HANDLE                  ev;
1612
1613         /* remove any buffer */
1614         wodPlayer_NotifyCompletions(wwo, TRUE);
1615
1616         wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1617         wwo->state = WINE_WS_STOPPED;
1618         wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1619         /* Clear partial wavehdr */
1620         wwo->dwPartialOffset = 0;
1621
1622         /* remove any existing message in the ring */
1623         EnterCriticalSection(&wwo->msgRing.msg_crst);
1624         /* return all pending headers in queue */
1625         while (OSS_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
1626         {
1627             if (msg != WINE_WM_HEADER)
1628             {
1629                 FIXME("shouldn't have headers left\n");
1630                 SetEvent(ev);
1631                 continue;
1632             }
1633             ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
1634             ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
1635
1636             wodNotifyClient(wwo, WOM_DONE, param, 0);
1637         }
1638         RESET_OMR(&wwo->msgRing);
1639         LeaveCriticalSection(&wwo->msgRing.msg_crst);
1640     } else {
1641         if (wwo->lpLoopPtr) {
1642             /* complicated case, not handled yet (could imply modifying the loop counter */
1643             FIXME("Pausing while in loop isn't correctly handled yet, except strange results\n");
1644             wwo->lpPlayPtr = wwo->lpLoopPtr;
1645             wwo->dwPartialOffset = 0;
1646             wwo->dwWrittenTotal = wwo->dwPlayedTotal; /* this is wrong !!! */
1647         } else {
1648             LPWAVEHDR   ptr;
1649             DWORD       sz = wwo->dwPartialOffset;
1650
1651             /* reset all the data as if we had written only up to lpPlayedTotal bytes */
1652             /* compute the max size playable from lpQueuePtr */
1653             for (ptr = wwo->lpQueuePtr; ptr != wwo->lpPlayPtr; ptr = ptr->lpNext) {
1654                 sz += ptr->dwBufferLength;
1655             }
1656             /* because the reset lpPlayPtr will be lpQueuePtr */
1657             if (wwo->dwWrittenTotal > wwo->dwPlayedTotal + sz) ERR("grin\n");
1658             wwo->dwPartialOffset = sz - (wwo->dwWrittenTotal - wwo->dwPlayedTotal);
1659             wwo->dwWrittenTotal = wwo->dwPlayedTotal;
1660             wwo->lpPlayPtr = wwo->lpQueuePtr;
1661         }
1662         wwo->state = WINE_WS_PAUSED;
1663     }
1664 }
1665
1666 /**************************************************************************
1667  *                    wodPlayer_ProcessMessages                 [internal]
1668  */
1669 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
1670 {
1671     LPWAVEHDR           lpWaveHdr;
1672     enum win_wm_message msg;
1673     DWORD               param;
1674     HANDLE              ev;
1675
1676     while (OSS_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
1677         TRACE("Received %s %lx\n", getCmdString(msg), param);
1678         switch (msg) {
1679         case WINE_WM_PAUSING:
1680             wodPlayer_Reset(wwo, FALSE);
1681             SetEvent(ev);
1682             break;
1683         case WINE_WM_RESTARTING:
1684             if (wwo->state == WINE_WS_PAUSED)
1685             {
1686                 wwo->state = WINE_WS_PLAYING;
1687             }
1688             SetEvent(ev);
1689             break;
1690         case WINE_WM_HEADER:
1691             lpWaveHdr = (LPWAVEHDR)param;
1692
1693             /* insert buffer at the end of queue */
1694             {
1695                 LPWAVEHDR*      wh;
1696                 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1697                 *wh = lpWaveHdr;
1698             }
1699             if (!wwo->lpPlayPtr)
1700                 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
1701             if (wwo->state == WINE_WS_STOPPED)
1702                 wwo->state = WINE_WS_PLAYING;
1703             break;
1704         case WINE_WM_RESETTING:
1705             wodPlayer_Reset(wwo, TRUE);
1706             SetEvent(ev);
1707             break;
1708         case WINE_WM_UPDATE:
1709             wodUpdatePlayedTotal(wwo, NULL);
1710             SetEvent(ev);
1711             break;
1712         case WINE_WM_BREAKLOOP:
1713             if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
1714                 /* ensure exit at end of current loop */
1715                 wwo->dwLoops = 1;
1716             }
1717             SetEvent(ev);
1718             break;
1719         case WINE_WM_CLOSING:
1720             /* sanity check: this should not happen since the device must have been reset before */
1721             if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1722             wwo->hThread = 0;
1723             wwo->state = WINE_WS_CLOSED;
1724             SetEvent(ev);
1725             ExitThread(0);
1726             /* shouldn't go here */
1727         default:
1728             FIXME("unknown message %d\n", msg);
1729             break;
1730         }
1731     }
1732 }
1733
1734 /**************************************************************************
1735  *                           wodPlayer_FeedDSP                  [internal]
1736  * Feed as much sound data as we can into the DSP and return the number of
1737  * milliseconds before it will be necessary to feed the DSP again.
1738  */
1739 static DWORD wodPlayer_FeedDSP(WINE_WAVEOUT* wwo)
1740 {
1741     audio_buf_info dspspace;
1742     DWORD       availInQ;
1743
1744     if (!wodUpdatePlayedTotal(wwo, &dspspace)) return INFINITE;
1745     availInQ = dspspace.bytes;
1746     TRACE("fragments=%d/%d, fragsize=%d, bytes=%d\n",
1747           dspspace.fragments, dspspace.fragstotal, dspspace.fragsize, dspspace.bytes);
1748
1749     /* no more room... no need to try to feed */
1750     if (dspspace.fragments != 0) {
1751         /* Feed from partial wavehdr */
1752         if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0) {
1753             wodPlayer_WriteMaxFrags(wwo, &availInQ);
1754         }
1755
1756         /* Feed wavehdrs until we run out of wavehdrs or DSP space */
1757         if (wwo->dwPartialOffset == 0 && wwo->lpPlayPtr) {
1758             do {
1759                 TRACE("Setting time to elapse for %p to %lu\n",
1760                       wwo->lpPlayPtr, wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength);
1761                 /* note the value that dwPlayedTotal will return when this wave finishes playing */
1762                 wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
1763             } while (wodPlayer_WriteMaxFrags(wwo, &availInQ) && wwo->lpPlayPtr && availInQ > 0);
1764         }
1765
1766         if (wwo->bNeedPost) {
1767             /* OSS doesn't start before it gets either 2 fragments or a SNDCTL_DSP_POST;
1768              * if it didn't get one, we give it the other */
1769             if (wwo->dwBufferSize < availInQ + 2 * wwo->dwFragmentSize)
1770                 ioctl(wwo->ossdev->fd, SNDCTL_DSP_POST, 0);
1771             wwo->bNeedPost = FALSE;
1772         }
1773     }
1774
1775     return wodPlayer_DSPWait(wwo);
1776 }
1777
1778
1779 /**************************************************************************
1780  *                              wodPlayer                       [internal]
1781  */
1782 static  DWORD   CALLBACK        wodPlayer(LPVOID pmt)
1783 {
1784     WORD          uDevID = (DWORD)pmt;
1785     WINE_WAVEOUT* wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
1786     DWORD         dwNextFeedTime = INFINITE;   /* Time before DSP needs feeding */
1787     DWORD         dwNextNotifyTime = INFINITE; /* Time before next wave completion */
1788     DWORD         dwSleepTime;
1789
1790     wwo->state = WINE_WS_STOPPED;
1791     SetEvent(wwo->hStartUpEvent);
1792
1793     for (;;) {
1794         /** Wait for the shortest time before an action is required.  If there
1795          *  are no pending actions, wait forever for a command.
1796          */
1797         dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
1798         TRACE("waiting %lums (%lu,%lu)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
1799         WAIT_OMR(&wwo->msgRing, dwSleepTime);
1800         wodPlayer_ProcessMessages(wwo);
1801         if (wwo->state == WINE_WS_PLAYING) {
1802             dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1803             if (dwNextFeedTime != INFINITE)
1804                 wwo->dwProjectedFinishTime = GetTickCount() + wodPlayer_TicksTillEmpty(wwo);
1805             else
1806                 wwo->dwProjectedFinishTime = 0;
1807
1808             dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1809             if (dwNextFeedTime == INFINITE) {
1810                 /* FeedDSP ran out of data, but before flushing, */
1811                 /* check that a notification didn't give us more */
1812                 wodPlayer_ProcessMessages(wwo);
1813                 if (!wwo->lpPlayPtr) {
1814                     TRACE("flushing\n");
1815                     ioctl(wwo->ossdev->fd, SNDCTL_DSP_SYNC, 0);
1816                     wwo->dwPlayedTotal = wwo->dwWrittenTotal;
1817                     dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1818                 } else {
1819                     TRACE("recovering\n");
1820                     dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1821                 }
1822             }
1823         } else {
1824             dwNextFeedTime = dwNextNotifyTime = INFINITE;
1825         }
1826     }
1827 }
1828
1829 /**************************************************************************
1830  *                      wodGetDevCaps                           [internal]
1831  */
1832 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
1833 {
1834     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1835
1836     if (lpCaps == NULL) {
1837         WARN("not enabled\n");
1838         return MMSYSERR_NOTENABLED;
1839     }
1840
1841     if (wDevID >= numOutDev) {
1842         WARN("numOutDev reached !\n");
1843         return MMSYSERR_BADDEVICEID;
1844     }
1845
1846     if (WOutDev[wDevID].ossdev->open_access == O_RDWR)
1847         memcpy(lpCaps, &WOutDev[wDevID].ossdev->duplex_out_caps, min(dwSize, sizeof(*lpCaps)));
1848     else
1849         memcpy(lpCaps, &WOutDev[wDevID].ossdev->out_caps, min(dwSize, sizeof(*lpCaps)));
1850
1851     return MMSYSERR_NOERROR;
1852 }
1853
1854 /**************************************************************************
1855  *                              wodOpen                         [internal]
1856  */
1857 DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1858 {
1859     int                 audio_fragment;
1860     WINE_WAVEOUT*       wwo;
1861     audio_buf_info      info;
1862     DWORD               ret;
1863
1864     TRACE("(%u, %p[cb=%08lx], %08lX);\n", wDevID, lpDesc, lpDesc->dwCallback, dwFlags);
1865     if (lpDesc == NULL) {
1866         WARN("Invalid Parameter !\n");
1867         return MMSYSERR_INVALPARAM;
1868     }
1869     if (wDevID >= numOutDev) {
1870         TRACE("MAX_WAVOUTDRV reached !\n");
1871         return MMSYSERR_BADDEVICEID;
1872     }
1873
1874     /* only PCM format is supported so far... */
1875     if (!supportedFormat(lpDesc->lpFormat)) {
1876         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1877              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1878              lpDesc->lpFormat->nSamplesPerSec);
1879         return WAVERR_BADFORMAT;
1880     }
1881
1882     if (dwFlags & WAVE_FORMAT_QUERY) {
1883         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1884              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1885              lpDesc->lpFormat->nSamplesPerSec);
1886         return MMSYSERR_NOERROR;
1887     }
1888
1889     TRACE("OSS_OpenDevice requested this format: %ldx%dx%d %s\n",
1890           lpDesc->lpFormat->nSamplesPerSec,
1891           lpDesc->lpFormat->wBitsPerSample,
1892           lpDesc->lpFormat->nChannels,
1893           lpDesc->lpFormat->wFormatTag == WAVE_FORMAT_PCM ? "WAVE_FORMAT_PCM" :
1894           lpDesc->lpFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? "WAVE_FORMAT_EXTENSIBLE" :
1895           "UNSUPPORTED");
1896
1897     wwo = &WOutDev[wDevID];
1898
1899     if ((dwFlags & WAVE_DIRECTSOUND) &&
1900         !(wwo->ossdev->duplex_out_caps.dwSupport & WAVECAPS_DIRECTSOUND))
1901         /* not supported, ignore it */
1902         dwFlags &= ~WAVE_DIRECTSOUND;
1903
1904     if (dwFlags & WAVE_DIRECTSOUND) {
1905         if (wwo->ossdev->duplex_out_caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
1906             /* we have realtime DirectSound, fragments just waste our time,
1907              * but a large buffer is good, so choose 64KB (32 * 2^11) */
1908             audio_fragment = 0x0020000B;
1909         else
1910             /* to approximate realtime, we must use small fragments,
1911              * let's try to fragment the above 64KB (256 * 2^8) */
1912             audio_fragment = 0x01000008;
1913     } else {
1914         /* A wave device must have a worst case latency of 10 ms so calculate
1915          * the largest fragment size less than 10 ms long.
1916          */
1917         int     fsize = lpDesc->lpFormat->nAvgBytesPerSec / 100;        /* 10 ms chunk */
1918         int     shift = 0;
1919         while ((1 << shift) <= fsize)
1920             shift++;
1921         shift--;
1922         audio_fragment = 0x00100000 + shift;    /* 16 fragments of 2^shift */
1923     }
1924
1925     TRACE("requesting %d %d byte fragments (%ld ms/fragment)\n",
1926         audio_fragment >> 16, 1 << (audio_fragment & 0xffff),
1927         ((1 << (audio_fragment & 0xffff)) * 1000) / lpDesc->lpFormat->nAvgBytesPerSec);
1928
1929     if (wwo->state != WINE_WS_CLOSED) {
1930         WARN("already allocated\n");
1931         return MMSYSERR_ALLOCATED;
1932     }
1933
1934     /* we want to be able to mmap() the device, which means it must be opened readable,
1935      * otherwise mmap() will fail (at least under Linux) */
1936     ret = OSS_OpenDevice(wwo->ossdev,
1937                          (dwFlags & WAVE_DIRECTSOUND) ? O_RDWR : O_WRONLY,
1938                          &audio_fragment,
1939                          (dwFlags & WAVE_DIRECTSOUND) ? 0 : 1,
1940                          lpDesc->lpFormat->nSamplesPerSec,
1941                          lpDesc->lpFormat->nChannels,
1942                          (lpDesc->lpFormat->wBitsPerSample == 16)
1943                              ? AFMT_S16_LE : AFMT_U8);
1944     if ((ret==MMSYSERR_NOERROR) && (dwFlags & WAVE_DIRECTSOUND)) {
1945         lpDesc->lpFormat->nSamplesPerSec=wwo->ossdev->sample_rate;
1946         lpDesc->lpFormat->nChannels=wwo->ossdev->channels;
1947         lpDesc->lpFormat->wBitsPerSample=(wwo->ossdev->format == AFMT_U8 ? 8 : 16);
1948         lpDesc->lpFormat->nBlockAlign=lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
1949         lpDesc->lpFormat->nAvgBytesPerSec=lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
1950         TRACE("OSS_OpenDevice returned this format: %ldx%dx%d\n",
1951               lpDesc->lpFormat->nSamplesPerSec,
1952               lpDesc->lpFormat->wBitsPerSample,
1953               lpDesc->lpFormat->nChannels);
1954     }
1955     if (ret != 0) return ret;
1956     wwo->state = WINE_WS_STOPPED;
1957
1958     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1959
1960     memcpy(&wwo->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
1961     copy_format(lpDesc->lpFormat, &wwo->waveFormat);
1962
1963     if (wwo->waveFormat.Format.wBitsPerSample == 0) {
1964         WARN("Resetting zeroed wBitsPerSample\n");
1965         wwo->waveFormat.Format.wBitsPerSample = 8 *
1966             (wwo->waveFormat.Format.nAvgBytesPerSec /
1967              wwo->waveFormat.Format.nSamplesPerSec) /
1968             wwo->waveFormat.Format.nChannels;
1969     }
1970     /* Read output space info for future reference */
1971     if (ioctl(wwo->ossdev->fd, SNDCTL_DSP_GETOSPACE, &info) < 0) {
1972         ERR("ioctl(%s, SNDCTL_DSP_GETOSPACE) failed (%s)\n", wwo->ossdev->dev_name, strerror(errno));
1973         OSS_CloseDevice(wwo->ossdev);
1974         wwo->state = WINE_WS_CLOSED;
1975         return MMSYSERR_NOTENABLED;
1976     }
1977
1978     TRACE("got %d %d byte fragments (%d ms/fragment)\n", info.fragstotal,
1979         info.fragsize, (info.fragsize * 1000) / (wwo->ossdev->sample_rate *
1980         wwo->ossdev->channels * (wwo->ossdev->format == AFMT_U8 ? 1 : 2)));
1981
1982     /* Check that fragsize is correct per our settings above */
1983     if ((info.fragsize > 1024) && (LOWORD(audio_fragment) <= 10)) {
1984         /* we've tried to set 1K fragments or less, but it didn't work */
1985         ERR("fragment size set failed, size is now %d\n", info.fragsize);
1986         MESSAGE("Your Open Sound System driver did not let us configure small enough sound fragments.\n");
1987         MESSAGE("This may cause delays and other problems in audio playback with certain applications.\n");
1988     }
1989
1990     /* Remember fragsize and total buffer size for future use */
1991     wwo->dwFragmentSize = info.fragsize;
1992     wwo->dwBufferSize = info.fragstotal * info.fragsize;
1993     wwo->dwPlayedTotal = 0;
1994     wwo->dwWrittenTotal = 0;
1995     wwo->bNeedPost = TRUE;
1996
1997     TRACE("fd=%d fragstotal=%d fragsize=%d BufferSize=%ld\n",
1998           wwo->ossdev->fd, info.fragstotal, info.fragsize, wwo->dwBufferSize);
1999     if (wwo->dwFragmentSize % wwo->waveFormat.Format.nBlockAlign) {
2000         ERR("Fragment doesn't contain an integral number of data blocks fragsize=%ld BlockAlign=%d\n",wwo->dwFragmentSize,wwo->waveFormat.Format.nBlockAlign);
2001         /* Some SoundBlaster 16 cards return an incorrect (odd) fragment
2002          * size for 16 bit sound. This will cause a system crash when we try
2003          * to write just the specified odd number of bytes. So if we
2004          * detect something is wrong we'd better fix it.
2005          */
2006         wwo->dwFragmentSize-=wwo->dwFragmentSize % wwo->waveFormat.Format.nBlockAlign;
2007     }
2008
2009     OSS_InitRingMessage(&wwo->msgRing);
2010
2011     wwo->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
2012     wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
2013     if (wwo->hThread)
2014         SetThreadPriority(wwo->hThread, THREAD_PRIORITY_TIME_CRITICAL);
2015     WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
2016     CloseHandle(wwo->hStartUpEvent);
2017     wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
2018
2019     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
2020           wwo->waveFormat.Format.wBitsPerSample, wwo->waveFormat.Format.nAvgBytesPerSec,
2021           wwo->waveFormat.Format.nSamplesPerSec, wwo->waveFormat.Format.nChannels,
2022           wwo->waveFormat.Format.nBlockAlign);
2023
2024     return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
2025 }
2026
2027 /**************************************************************************
2028  *                              wodClose                        [internal]
2029  */
2030 static DWORD wodClose(WORD wDevID)
2031 {
2032     DWORD               ret = MMSYSERR_NOERROR;
2033     WINE_WAVEOUT*       wwo;
2034
2035     TRACE("(%u);\n", wDevID);
2036
2037     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2038         WARN("bad device ID !\n");
2039         return MMSYSERR_BADDEVICEID;
2040     }
2041
2042     wwo = &WOutDev[wDevID];
2043     if (wwo->lpQueuePtr) {
2044         WARN("buffers still playing !\n");
2045         ret = WAVERR_STILLPLAYING;
2046     } else {
2047         if (wwo->hThread != INVALID_HANDLE_VALUE) {
2048             OSS_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
2049         }
2050
2051         OSS_DestroyRingMessage(&wwo->msgRing);
2052
2053         OSS_CloseDevice(wwo->ossdev);
2054         wwo->state = WINE_WS_CLOSED;
2055         wwo->dwFragmentSize = 0;
2056         ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
2057     }
2058     return ret;
2059 }
2060
2061 /**************************************************************************
2062  *                              wodWrite                        [internal]
2063  *
2064  */
2065 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2066 {
2067     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2068
2069     /* first, do the sanity checks... */
2070     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2071         WARN("bad dev ID !\n");
2072         return MMSYSERR_BADDEVICEID;
2073     }
2074
2075     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
2076         return WAVERR_UNPREPARED;
2077
2078     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2079         return WAVERR_STILLPLAYING;
2080
2081     lpWaveHdr->dwFlags &= ~WHDR_DONE;
2082     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2083     lpWaveHdr->lpNext = 0;
2084
2085     if ((lpWaveHdr->dwBufferLength & (WOutDev[wDevID].waveFormat.Format.nBlockAlign - 1)) != 0)
2086     {
2087         WARN("WaveHdr length isn't a multiple of the PCM block size: %ld %% %d\n",lpWaveHdr->dwBufferLength,WOutDev[wDevID].waveFormat.Format.nBlockAlign);
2088         lpWaveHdr->dwBufferLength &= ~(WOutDev[wDevID].waveFormat.Format.nBlockAlign - 1);
2089     }
2090
2091     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
2092
2093     return MMSYSERR_NOERROR;
2094 }
2095
2096 /**************************************************************************
2097  *                      wodPause                                [internal]
2098  */
2099 static DWORD wodPause(WORD wDevID)
2100 {
2101     TRACE("(%u);!\n", wDevID);
2102
2103     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2104         WARN("bad device ID !\n");
2105         return MMSYSERR_BADDEVICEID;
2106     }
2107
2108     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
2109
2110     return MMSYSERR_NOERROR;
2111 }
2112
2113 /**************************************************************************
2114  *                      wodRestart                              [internal]
2115  */
2116 static DWORD wodRestart(WORD wDevID)
2117 {
2118     TRACE("(%u);\n", wDevID);
2119
2120     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2121         WARN("bad device ID !\n");
2122         return MMSYSERR_BADDEVICEID;
2123     }
2124
2125     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
2126
2127     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
2128     /* FIXME: Myst crashes with this ... hmm -MM
2129        return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
2130     */
2131
2132     return MMSYSERR_NOERROR;
2133 }
2134
2135 /**************************************************************************
2136  *                      wodReset                                [internal]
2137  */
2138 static DWORD wodReset(WORD wDevID)
2139 {
2140     TRACE("(%u);\n", wDevID);
2141
2142     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2143         WARN("bad device ID !\n");
2144         return MMSYSERR_BADDEVICEID;
2145     }
2146
2147     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
2148
2149     return MMSYSERR_NOERROR;
2150 }
2151
2152 /**************************************************************************
2153  *                              wodGetPosition                  [internal]
2154  */
2155 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
2156 {
2157     WINE_WAVEOUT*       wwo;
2158
2159     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
2160
2161     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2162         WARN("bad device ID !\n");
2163         return MMSYSERR_BADDEVICEID;
2164     }
2165
2166     if (lpTime == NULL) {
2167         WARN("invalid parameter: lpTime == NULL\n");
2168         return MMSYSERR_INVALPARAM;
2169     }
2170
2171     wwo = &WOutDev[wDevID];
2172 #ifdef EXACT_WODPOSITION
2173     if (wwo->ossdev->open_access == O_RDWR) {
2174         if (wwo->ossdev->duplex_out_caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
2175             OSS_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
2176     } else {
2177         if (wwo->ossdev->out_caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
2178             OSS_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
2179     }
2180 #endif
2181
2182     return bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->waveFormat);
2183 }
2184
2185 /**************************************************************************
2186  *                              wodBreakLoop                    [internal]
2187  */
2188 static DWORD wodBreakLoop(WORD wDevID)
2189 {
2190     TRACE("(%u);\n", wDevID);
2191
2192     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2193         WARN("bad device ID !\n");
2194         return MMSYSERR_BADDEVICEID;
2195     }
2196     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
2197     return MMSYSERR_NOERROR;
2198 }
2199
2200 /**************************************************************************
2201  *                              wodGetVolume                    [internal]
2202  */
2203 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
2204 {
2205     int         mixer;
2206     int         volume;
2207     DWORD       left, right;
2208     DWORD       last_left, last_right;
2209
2210     TRACE("(%u, %p);\n", wDevID, lpdwVol);
2211
2212     if (lpdwVol == NULL) {
2213         WARN("not enabled\n");
2214         return MMSYSERR_NOTENABLED;
2215     }
2216     if (wDevID >= numOutDev) {
2217         WARN("invalid parameter\n");
2218         return MMSYSERR_INVALPARAM;
2219     }
2220
2221     if ((mixer = open(WOutDev[wDevID].ossdev->mixer_name, O_RDONLY|O_NDELAY)) < 0) {
2222         WARN("mixer device not available !\n");
2223         return MMSYSERR_NOTENABLED;
2224     }
2225     if (ioctl(mixer, SOUND_MIXER_READ_PCM, &volume) == -1) {
2226         WARN("ioctl(%s, SOUND_MIXER_READ_PCM) failed (%s)\n",
2227              WOutDev[wDevID].ossdev->mixer_name, strerror(errno));
2228         return MMSYSERR_NOTENABLED;
2229     }
2230     close(mixer);
2231
2232     left = LOBYTE(volume);
2233     right = HIBYTE(volume);
2234     TRACE("left=%ld right=%ld !\n", left, right);
2235     last_left  = (LOWORD(WOutDev[wDevID].volume) * 100) / 0xFFFFl;
2236     last_right = (HIWORD(WOutDev[wDevID].volume) * 100) / 0xFFFFl;
2237     TRACE("last_left=%ld last_right=%ld !\n", last_left, last_right);
2238     if (last_left == left && last_right == right)
2239         *lpdwVol = WOutDev[wDevID].volume;
2240     else
2241         *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) << 16);
2242     return MMSYSERR_NOERROR;
2243 }
2244
2245 /**************************************************************************
2246  *                              wodSetVolume                    [internal]
2247  */
2248 DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
2249 {
2250     int         mixer;
2251     int         volume;
2252     DWORD       left, right;
2253
2254     TRACE("(%u, %08lX);\n", wDevID, dwParam);
2255
2256     left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
2257     right = (HIWORD(dwParam) * 100) / 0xFFFFl;
2258     volume = left + (right << 8);
2259
2260     if (wDevID >= numOutDev) {
2261         WARN("invalid parameter: wDevID > %d\n", numOutDev);
2262         return MMSYSERR_INVALPARAM;
2263     }
2264     if ((mixer = open(WOutDev[wDevID].ossdev->mixer_name, O_WRONLY|O_NDELAY)) < 0) {
2265         WARN("open(%s) failed (%s)\n", WOutDev[wDevID].ossdev->mixer_name, strerror(errno));
2266         return MMSYSERR_NOTENABLED;
2267     }
2268     if (ioctl(mixer, SOUND_MIXER_WRITE_PCM, &volume) == -1) {
2269         WARN("ioctl(%s, SOUND_MIXER_WRITE_PCM) failed (%s)\n",
2270             WOutDev[wDevID].ossdev->mixer_name, strerror(errno));
2271         return MMSYSERR_NOTENABLED;
2272     } else {
2273         TRACE("volume=%04x\n", (unsigned)volume);
2274     }
2275     close(mixer);
2276
2277     /* save requested volume */
2278     WOutDev[wDevID].volume = dwParam;
2279
2280     return MMSYSERR_NOERROR;
2281 }
2282
2283 /**************************************************************************
2284  *                              wodMessage (WINEOSS.7)
2285  */
2286 DWORD WINAPI OSS_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
2287                             DWORD dwParam1, DWORD dwParam2)
2288 {
2289     TRACE("(%u, %s, %08lX, %08lX, %08lX);\n",
2290           wDevID, getMessage(wMsg), dwUser, dwParam1, dwParam2);
2291
2292     switch (wMsg) {
2293     case DRVM_INIT:
2294     case DRVM_EXIT:
2295     case DRVM_ENABLE:
2296     case DRVM_DISABLE:
2297         /* FIXME: Pretend this is supported */
2298         return 0;
2299     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
2300     case WODM_CLOSE:            return wodClose         (wDevID);
2301     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
2302     case WODM_PAUSE:            return wodPause         (wDevID);
2303     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
2304     case WODM_BREAKLOOP:        return wodBreakLoop     (wDevID);
2305     case WODM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
2306     case WODM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
2307     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSW)dwParam1,      dwParam2);
2308     case WODM_GETNUMDEVS:       return numOutDev;
2309     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
2310     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
2311     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
2312     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
2313     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
2314     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
2315     case WODM_RESTART:          return wodRestart       (wDevID);
2316     case WODM_RESET:            return wodReset         (wDevID);
2317
2318     case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize      (wDevID, (LPDWORD)dwParam1);
2319     case DRV_QUERYDEVICEINTERFACE:     return wodDevInterface          (wDevID, (PWCHAR)dwParam1, dwParam2);
2320     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate      (wDevID, (PIDSDRIVER*)dwParam1);
2321     case DRV_QUERYDSOUNDDESC:   return wodDsDesc        (wDevID, (PDSDRIVERDESC)dwParam1);
2322     default:
2323         FIXME("unknown message %d!\n", wMsg);
2324     }
2325     return MMSYSERR_NOTSUPPORTED;
2326 }
2327
2328 /*======================================================================*
2329  *                  Low level WAVE IN implementation                    *
2330  *======================================================================*/
2331
2332 /**************************************************************************
2333  *                      widNotifyClient                 [internal]
2334  */
2335 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
2336 {
2337     TRACE("wMsg = 0x%04x (%s) dwParm1 = %04lX dwParam2 = %04lX\n", wMsg,
2338         wMsg == WIM_OPEN ? "WIM_OPEN" : wMsg == WIM_CLOSE ? "WIM_CLOSE" :
2339         wMsg == WIM_DATA ? "WIM_DATA" : "Unknown", dwParam1, dwParam2);
2340
2341     switch (wMsg) {
2342     case WIM_OPEN:
2343     case WIM_CLOSE:
2344     case WIM_DATA:
2345         if (wwi->wFlags != DCB_NULL &&
2346             !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
2347                             (HDRVR)wwi->waveDesc.hWave, wMsg,
2348                             wwi->waveDesc.dwInstance, dwParam1, dwParam2)) {
2349             WARN("can't notify client !\n");
2350             return MMSYSERR_ERROR;
2351         }
2352         break;
2353     default:
2354         FIXME("Unknown callback message %u\n", wMsg);
2355         return MMSYSERR_INVALPARAM;
2356     }
2357     return MMSYSERR_NOERROR;
2358 }
2359
2360 /**************************************************************************
2361  *                      widGetDevCaps                           [internal]
2362  */
2363 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
2364 {
2365     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
2366
2367     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
2368
2369     if (wDevID >= numInDev) {
2370         TRACE("numOutDev reached !\n");
2371         return MMSYSERR_BADDEVICEID;
2372     }
2373
2374     memcpy(lpCaps, &WInDev[wDevID].ossdev->in_caps, min(dwSize, sizeof(*lpCaps)));
2375     return MMSYSERR_NOERROR;
2376 }
2377
2378 /**************************************************************************
2379  *                              widRecorder_ReadHeaders         [internal]
2380  */
2381 static void widRecorder_ReadHeaders(WINE_WAVEIN * wwi)
2382 {
2383     enum win_wm_message tmp_msg;
2384     DWORD               tmp_param;
2385     HANDLE              tmp_ev;
2386     WAVEHDR*            lpWaveHdr;
2387
2388     while (OSS_RetrieveRingMessage(&wwi->msgRing, &tmp_msg, &tmp_param, &tmp_ev)) {
2389         if (tmp_msg == WINE_WM_HEADER) {
2390             LPWAVEHDR*  wh;
2391             lpWaveHdr = (LPWAVEHDR)tmp_param;
2392             lpWaveHdr->lpNext = 0;
2393
2394             if (wwi->lpQueuePtr == 0)
2395                 wwi->lpQueuePtr = lpWaveHdr;
2396             else {
2397                 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2398                 *wh = lpWaveHdr;
2399             }
2400         } else {
2401             ERR("should only have headers left\n");
2402         }
2403     }
2404 }
2405
2406 /**************************************************************************
2407  *                              widRecorder                     [internal]
2408  */
2409 static  DWORD   CALLBACK        widRecorder(LPVOID pmt)
2410 {
2411     WORD                uDevID = (DWORD)pmt;
2412     WINE_WAVEIN*        wwi = (WINE_WAVEIN*)&WInDev[uDevID];
2413     WAVEHDR*            lpWaveHdr;
2414     DWORD               dwSleepTime;
2415     DWORD               bytesRead;
2416     LPVOID              buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, wwi->dwFragmentSize);
2417     char               *pOffset = buffer;
2418     audio_buf_info      info;
2419     int                 xs;
2420     enum win_wm_message msg;
2421     DWORD               param;
2422     HANDLE              ev;
2423     int                 enable;
2424
2425     wwi->state = WINE_WS_STOPPED;
2426     wwi->dwTotalRecorded = 0;
2427     wwi->dwTotalRead = 0;
2428     wwi->lpQueuePtr = NULL;
2429
2430     SetEvent(wwi->hStartUpEvent);
2431
2432     /* disable input so capture will begin when triggered */
2433     wwi->ossdev->bInputEnabled = FALSE;
2434     enable = getEnables(wwi->ossdev);
2435     if (ioctl(wwi->ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0)
2436         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", wwi->ossdev->dev_name, strerror(errno));
2437
2438     /* the soundblaster live needs a micro wake to get its recording started
2439      * (or GETISPACE will have 0 frags all the time)
2440      */
2441     read(wwi->ossdev->fd, &xs, 4);
2442
2443     /* make sleep time to be # of ms to output a fragment */
2444     dwSleepTime = (wwi->dwFragmentSize * 1000) / wwi->waveFormat.Format.nAvgBytesPerSec;
2445     TRACE("sleeptime=%ld ms\n", dwSleepTime);
2446
2447     for (;;) {
2448         /* wait for dwSleepTime or an event in thread's queue */
2449         /* FIXME: could improve wait time depending on queue state,
2450          * ie, number of queued fragments
2451          */
2452
2453         if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
2454         {
2455             lpWaveHdr = wwi->lpQueuePtr;
2456
2457             ioctl(wwi->ossdev->fd, SNDCTL_DSP_GETISPACE, &info);
2458             TRACE("info={frag=%d fsize=%d ftotal=%d bytes=%d}\n", info.fragments, info.fragsize, info.fragstotal, info.bytes);
2459
2460             /* read all the fragments accumulated so far */
2461             while ((info.fragments > 0) && (wwi->lpQueuePtr))
2462             {
2463                 info.fragments --;
2464
2465                 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwFragmentSize)
2466                 {
2467                     /* directly read fragment in wavehdr */
2468                     bytesRead = read(wwi->ossdev->fd,
2469                                      lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2470                                      wwi->dwFragmentSize);
2471
2472                     TRACE("bytesRead=%ld (direct)\n", bytesRead);
2473                     if (bytesRead != (DWORD) -1)
2474                     {
2475                         /* update number of bytes recorded in current buffer and by this device */
2476                         lpWaveHdr->dwBytesRecorded += bytesRead;
2477                         wwi->dwTotalRead           += bytesRead;
2478                         wwi->dwTotalRecorded = wwi->dwTotalRead;
2479
2480                         /* buffer is full. notify client */
2481                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2482                         {
2483                             /* must copy the value of next waveHdr, because we have no idea of what
2484                              * will be done with the content of lpWaveHdr in callback
2485                              */
2486                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
2487
2488                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2489                             lpWaveHdr->dwFlags |=  WHDR_DONE;
2490
2491                             wwi->lpQueuePtr = lpNext;
2492                             widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2493                             lpWaveHdr = lpNext;
2494                         }
2495                     } else {
2496                         TRACE("read(%s, %p, %ld) failed (%s)\n", wwi->ossdev->dev_name,
2497                             lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2498                             wwi->dwFragmentSize, strerror(errno));
2499                     }
2500                 }
2501                 else
2502                 {
2503                     /* read the fragment in a local buffer */
2504                     bytesRead = read(wwi->ossdev->fd, buffer, wwi->dwFragmentSize);
2505                     pOffset = buffer;
2506
2507                     TRACE("bytesRead=%ld (local)\n", bytesRead);
2508
2509                     if (bytesRead == (DWORD) -1) {
2510                         TRACE("read(%s, %p, %ld) failed (%s)\n", wwi->ossdev->dev_name,
2511                             buffer, wwi->dwFragmentSize, strerror(errno));
2512                         continue;
2513                     }
2514
2515                     /* copy data in client buffers */
2516                     while (bytesRead != (DWORD) -1 && bytesRead > 0)
2517                     {
2518                         DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
2519
2520                         memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2521                                pOffset,
2522                                dwToCopy);
2523
2524                         /* update number of bytes recorded in current buffer and by this device */
2525                         lpWaveHdr->dwBytesRecorded += dwToCopy;
2526                         wwi->dwTotalRead           += dwToCopy;
2527                         wwi->dwTotalRecorded = wwi->dwTotalRead;
2528                         bytesRead -= dwToCopy;
2529                         pOffset   += dwToCopy;
2530
2531                         /* client buffer is full. notify client */
2532                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2533                         {
2534                             /* must copy the value of next waveHdr, because we have no idea of what
2535                              * will be done with the content of lpWaveHdr in callback
2536                              */
2537                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
2538                             TRACE("lpNext=%p\n", lpNext);
2539
2540                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2541                             lpWaveHdr->dwFlags |=  WHDR_DONE;
2542
2543                             wwi->lpQueuePtr = lpNext;
2544                             widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2545
2546                             lpWaveHdr = lpNext;
2547                             if (!lpNext && bytesRead) {
2548                                 /* before we give up, check for more header messages */
2549                                 while (OSS_PeekRingMessage(&wwi->msgRing, &msg, &param, &ev))
2550                                 {
2551                                     if (msg == WINE_WM_HEADER) {
2552                                         LPWAVEHDR hdr;
2553                                         OSS_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev);
2554                                         hdr = ((LPWAVEHDR)param);
2555                                         TRACE("msg = %s, hdr = %p, ev = %p\n", getCmdString(msg), hdr, ev);
2556                                         hdr->lpNext = 0;
2557                                         if (lpWaveHdr == 0) {
2558                                             /* new head of queue */
2559                                             wwi->lpQueuePtr = lpWaveHdr = hdr;
2560                                         } else {
2561                                             /* insert buffer at the end of queue */
2562                                             LPWAVEHDR*  wh;
2563                                             for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2564                                             *wh = hdr;
2565                                         }
2566                                     } else
2567                                         break;
2568                                 }
2569
2570                                 if (lpWaveHdr == 0) {
2571                                     /* no more buffer to copy data to, but we did read more.
2572                                      * what hasn't been copied will be dropped
2573                                      */
2574                                     WARN("buffer under run! %lu bytes dropped.\n", bytesRead);
2575                                     wwi->lpQueuePtr = NULL;
2576                                     break;
2577                                 }
2578                             }
2579                         }
2580                     }
2581                 }
2582             }
2583         }
2584
2585         WAIT_OMR(&wwi->msgRing, dwSleepTime);
2586
2587         while (OSS_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev))
2588         {
2589             TRACE("msg=%s param=0x%lx\n", getCmdString(msg), param);
2590             switch (msg) {
2591             case WINE_WM_PAUSING:
2592                 wwi->state = WINE_WS_PAUSED;
2593                 /*FIXME("Device should stop recording\n");*/
2594                 SetEvent(ev);
2595                 break;
2596             case WINE_WM_STARTING:
2597                 wwi->state = WINE_WS_PLAYING;
2598
2599                 if (wwi->ossdev->bTriggerSupport)
2600                 {
2601                     /* start the recording */
2602                     wwi->ossdev->bInputEnabled = TRUE;
2603                     enable = getEnables(wwi->ossdev);
2604                     if (ioctl(wwi->ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
2605                         wwi->ossdev->bInputEnabled = FALSE;
2606                         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", wwi->ossdev->dev_name, strerror(errno));
2607                     }
2608                 }
2609                 else
2610                 {
2611                     unsigned char data[4];
2612                     /* read 4 bytes to start the recording */
2613                     read(wwi->ossdev->fd, data, 4);
2614                 }
2615
2616                 SetEvent(ev);
2617                 break;
2618             case WINE_WM_HEADER:
2619                 lpWaveHdr = (LPWAVEHDR)param;
2620                 lpWaveHdr->lpNext = 0;
2621
2622                 /* insert buffer at the end of queue */
2623                 {
2624                     LPWAVEHDR*  wh;
2625                     for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2626                     *wh = lpWaveHdr;
2627                 }
2628                 break;
2629             case WINE_WM_STOPPING:
2630                 if (wwi->state != WINE_WS_STOPPED)
2631                 {
2632                     if (wwi->ossdev->bTriggerSupport)
2633                     {
2634                         /* stop the recording */
2635                         wwi->ossdev->bInputEnabled = FALSE;
2636                         enable = getEnables(wwi->ossdev);
2637                         if (ioctl(wwi->ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
2638                             wwi->ossdev->bInputEnabled = FALSE;
2639                             ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", wwi->ossdev->dev_name, strerror(errno));
2640                         }
2641                     }
2642
2643                     /* read any headers in queue */
2644                     widRecorder_ReadHeaders(wwi);
2645
2646                     /* return current buffer to app */
2647                     lpWaveHdr = wwi->lpQueuePtr;
2648                     if (lpWaveHdr)
2649                     {
2650                         LPWAVEHDR       lpNext = lpWaveHdr->lpNext;
2651                         TRACE("stop %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
2652                         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2653                         lpWaveHdr->dwFlags |= WHDR_DONE;
2654                         wwi->lpQueuePtr = lpNext;
2655                         widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2656                     }
2657                 }
2658                 wwi->state = WINE_WS_STOPPED;
2659                 SetEvent(ev);
2660                 break;
2661             case WINE_WM_RESETTING:
2662                 if (wwi->state != WINE_WS_STOPPED)
2663                 {
2664                     if (wwi->ossdev->bTriggerSupport)
2665                     {
2666                         /* stop the recording */
2667                         wwi->ossdev->bInputEnabled = FALSE;
2668                         enable = getEnables(wwi->ossdev);
2669                         if (ioctl(wwi->ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
2670                             wwi->ossdev->bInputEnabled = FALSE;
2671                             ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", wwi->ossdev->dev_name, strerror(errno));
2672                         }
2673                     }
2674                 }
2675                 wwi->state = WINE_WS_STOPPED;
2676                 wwi->dwTotalRecorded = 0;
2677                 wwi->dwTotalRead = 0;
2678
2679                 /* read any headers in queue */
2680                 widRecorder_ReadHeaders(wwi);
2681
2682                 /* return all buffers to the app */
2683                 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
2684                     TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
2685                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2686                     lpWaveHdr->dwFlags |= WHDR_DONE;
2687                     wwi->lpQueuePtr = lpWaveHdr->lpNext;
2688                     widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2689                 }
2690
2691                 wwi->lpQueuePtr = NULL;
2692                 SetEvent(ev);
2693                 break;
2694             case WINE_WM_UPDATE:
2695                 if (wwi->state == WINE_WS_PLAYING) {
2696                     audio_buf_info tmp_info;
2697                     if (ioctl(wwi->ossdev->fd, SNDCTL_DSP_GETISPACE, &tmp_info) < 0)
2698                         ERR("ioctl(%s, SNDCTL_DSP_GETISPACE) failed (%s)\n", wwi->ossdev->dev_name, strerror(errno));
2699                     else
2700                         wwi->dwTotalRecorded = wwi->dwTotalRead + tmp_info.bytes;
2701                 }
2702                 SetEvent(ev);
2703                 break;
2704             case WINE_WM_CLOSING:
2705                 wwi->hThread = 0;
2706                 wwi->state = WINE_WS_CLOSED;
2707                 SetEvent(ev);
2708                 HeapFree(GetProcessHeap(), 0, buffer);
2709                 ExitThread(0);
2710                 /* shouldn't go here */
2711             default:
2712                 FIXME("unknown message %d\n", msg);
2713                 break;
2714             }
2715         }
2716     }
2717     ExitThread(0);
2718     /* just for not generating compilation warnings... should never be executed */
2719     return 0;
2720 }
2721
2722
2723 /**************************************************************************
2724  *                              widOpen                         [internal]
2725  */
2726 DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
2727 {
2728     WINE_WAVEIN*        wwi;
2729     audio_buf_info      info;
2730     int                 audio_fragment;
2731     DWORD               ret;
2732
2733     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
2734     if (lpDesc == NULL) {
2735         WARN("Invalid Parameter !\n");
2736         return MMSYSERR_INVALPARAM;
2737     }
2738     if (wDevID >= numInDev) {
2739         WARN("bad device id: %d >= %d\n", wDevID, numInDev);
2740         return MMSYSERR_BADDEVICEID;
2741     }
2742
2743     /* only PCM format is supported so far... */
2744     if (!supportedFormat(lpDesc->lpFormat)) {
2745         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
2746              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
2747              lpDesc->lpFormat->nSamplesPerSec);
2748         return WAVERR_BADFORMAT;
2749     }
2750
2751     if (dwFlags & WAVE_FORMAT_QUERY) {
2752         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
2753              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
2754              lpDesc->lpFormat->nSamplesPerSec);
2755         return MMSYSERR_NOERROR;
2756     }
2757
2758     TRACE("OSS_OpenDevice requested this format: %ldx%dx%d %s\n",
2759           lpDesc->lpFormat->nSamplesPerSec,
2760           lpDesc->lpFormat->wBitsPerSample,
2761           lpDesc->lpFormat->nChannels,
2762           lpDesc->lpFormat->wFormatTag == WAVE_FORMAT_PCM ? "WAVE_FORMAT_PCM" :
2763           lpDesc->lpFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? "WAVE_FORMAT_EXTENSIBLE" :
2764           "UNSUPPORTED");
2765
2766     wwi = &WInDev[wDevID];
2767
2768     if (wwi->state != WINE_WS_CLOSED) return MMSYSERR_ALLOCATED;
2769
2770     if ((dwFlags & WAVE_DIRECTSOUND) &&
2771         !(wwi->ossdev->in_caps_support & WAVECAPS_DIRECTSOUND))
2772         /* not supported, ignore it */
2773         dwFlags &= ~WAVE_DIRECTSOUND;
2774
2775     if (dwFlags & WAVE_DIRECTSOUND) {
2776         TRACE("has DirectSoundCapture driver\n");
2777         if (wwi->ossdev->in_caps_support & WAVECAPS_SAMPLEACCURATE)
2778             /* we have realtime DirectSound, fragments just waste our time,
2779              * but a large buffer is good, so choose 64KB (32 * 2^11) */
2780             audio_fragment = 0x0020000B;
2781         else
2782             /* to approximate realtime, we must use small fragments,
2783              * let's try to fragment the above 64KB (256 * 2^8) */
2784             audio_fragment = 0x01000008;
2785     } else {
2786         TRACE("doesn't have DirectSoundCapture driver\n");
2787         if (wwi->ossdev->open_count > 0) {
2788             TRACE("Using output device audio_fragment\n");
2789             /* FIXME: This may not be optimal for capture but it allows us
2790              * to do hardware playback without hardware capture. */
2791             audio_fragment = wwi->ossdev->audio_fragment;
2792         } else {
2793             /* A wave device must have a worst case latency of 10 ms so calculate
2794              * the largest fragment size less than 10 ms long.
2795              */
2796             int fsize = lpDesc->lpFormat->nAvgBytesPerSec / 100;        /* 10 ms chunk */
2797             int shift = 0;
2798             while ((1 << shift) <= fsize)
2799                 shift++;
2800             shift--;
2801             audio_fragment = 0x00100000 + shift;        /* 16 fragments of 2^shift */
2802         }
2803     }
2804
2805     TRACE("requesting %d %d byte fragments (%ld ms)\n", audio_fragment >> 16,
2806         1 << (audio_fragment & 0xffff),
2807         ((1 << (audio_fragment & 0xffff)) * 1000) / lpDesc->lpFormat->nAvgBytesPerSec);
2808
2809     ret = OSS_OpenDevice(wwi->ossdev, O_RDONLY, &audio_fragment,
2810                          1,
2811                          lpDesc->lpFormat->nSamplesPerSec,
2812                          lpDesc->lpFormat->nChannels,
2813                          (lpDesc->lpFormat->wBitsPerSample == 16)
2814                          ? AFMT_S16_LE : AFMT_U8);
2815     if (ret != 0) return ret;
2816     wwi->state = WINE_WS_STOPPED;
2817
2818     if (wwi->lpQueuePtr) {
2819         WARN("Should have an empty queue (%p)\n", wwi->lpQueuePtr);
2820         wwi->lpQueuePtr = NULL;
2821     }
2822     wwi->dwTotalRecorded = 0;
2823     wwi->dwTotalRead = 0;
2824     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
2825
2826     memcpy(&wwi->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
2827     copy_format(lpDesc->lpFormat, &wwi->waveFormat);
2828
2829     if (wwi->waveFormat.Format.wBitsPerSample == 0) {
2830         WARN("Resetting zeroed wBitsPerSample\n");
2831         wwi->waveFormat.Format.wBitsPerSample = 8 *
2832             (wwi->waveFormat.Format.nAvgBytesPerSec /
2833              wwi->waveFormat.Format.nSamplesPerSec) /
2834             wwi->waveFormat.Format.nChannels;
2835     }
2836
2837     if (ioctl(wwi->ossdev->fd, SNDCTL_DSP_GETISPACE, &info) < 0) {
2838         ERR("ioctl(%s, SNDCTL_DSP_GETISPACE) failed (%s)\n",
2839             wwi->ossdev->dev_name, strerror(errno));
2840         OSS_CloseDevice(wwi->ossdev);
2841         wwi->state = WINE_WS_CLOSED;
2842         return MMSYSERR_NOTENABLED;
2843     }
2844
2845     TRACE("got %d %d byte fragments (%d ms/fragment)\n", info.fragstotal,
2846         info.fragsize, (info.fragsize * 1000) / (wwi->ossdev->sample_rate *
2847         wwi->ossdev->channels * (wwi->ossdev->format == AFMT_U8 ? 1 : 2)));
2848
2849     wwi->dwFragmentSize = info.fragsize;
2850
2851     TRACE("dwFragmentSize=%lu\n", wwi->dwFragmentSize);
2852     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
2853           wwi->waveFormat.Format.wBitsPerSample, wwi->waveFormat.Format.nAvgBytesPerSec,
2854           wwi->waveFormat.Format.nSamplesPerSec, wwi->waveFormat.Format.nChannels,
2855           wwi->waveFormat.Format.nBlockAlign);
2856
2857     OSS_InitRingMessage(&wwi->msgRing);
2858
2859     wwi->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
2860     wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
2861     if (wwi->hThread)
2862         SetThreadPriority(wwi->hThread, THREAD_PRIORITY_TIME_CRITICAL);
2863     WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
2864     CloseHandle(wwi->hStartUpEvent);
2865     wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
2866
2867     return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
2868 }
2869
2870 /**************************************************************************
2871  *                              widClose                        [internal]
2872  */
2873 static DWORD widClose(WORD wDevID)
2874 {
2875     WINE_WAVEIN*        wwi;
2876
2877     TRACE("(%u);\n", wDevID);
2878     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2879         WARN("can't close !\n");
2880         return MMSYSERR_INVALHANDLE;
2881     }
2882
2883     wwi = &WInDev[wDevID];
2884
2885     if (wwi->lpQueuePtr != NULL) {
2886         WARN("still buffers open !\n");
2887         return WAVERR_STILLPLAYING;
2888     }
2889
2890     OSS_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
2891     OSS_CloseDevice(wwi->ossdev);
2892     wwi->state = WINE_WS_CLOSED;
2893     wwi->dwFragmentSize = 0;
2894     OSS_DestroyRingMessage(&wwi->msgRing);
2895     return widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
2896 }
2897
2898 /**************************************************************************
2899  *                              widAddBuffer            [internal]
2900  */
2901 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2902 {
2903     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2904
2905     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2906         WARN("can't do it !\n");
2907         return MMSYSERR_INVALHANDLE;
2908     }
2909     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED)) {
2910         TRACE("never been prepared !\n");
2911         return WAVERR_UNPREPARED;
2912     }
2913     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) {
2914         TRACE("header already in use !\n");
2915         return WAVERR_STILLPLAYING;
2916     }
2917
2918     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2919     lpWaveHdr->dwFlags &= ~WHDR_DONE;
2920     lpWaveHdr->dwBytesRecorded = 0;
2921     lpWaveHdr->lpNext = NULL;
2922
2923     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
2924     return MMSYSERR_NOERROR;
2925 }
2926
2927 /**************************************************************************
2928  *                      widStart                                [internal]
2929  */
2930 static DWORD widStart(WORD wDevID)
2931 {
2932     TRACE("(%u);\n", wDevID);
2933     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2934         WARN("can't start recording !\n");
2935         return MMSYSERR_INVALHANDLE;
2936     }
2937
2938     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
2939     return MMSYSERR_NOERROR;
2940 }
2941
2942 /**************************************************************************
2943  *                      widStop                                 [internal]
2944  */
2945 static DWORD widStop(WORD wDevID)
2946 {
2947     TRACE("(%u);\n", wDevID);
2948     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2949         WARN("can't stop !\n");
2950         return MMSYSERR_INVALHANDLE;
2951     }
2952
2953     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
2954
2955     return MMSYSERR_NOERROR;
2956 }
2957
2958 /**************************************************************************
2959  *                      widReset                                [internal]
2960  */
2961 static DWORD widReset(WORD wDevID)
2962 {
2963     TRACE("(%u);\n", wDevID);
2964     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2965         WARN("can't reset !\n");
2966         return MMSYSERR_INVALHANDLE;
2967     }
2968     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
2969     return MMSYSERR_NOERROR;
2970 }
2971
2972 /**************************************************************************
2973  *                              widGetPosition                  [internal]
2974  */
2975 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
2976 {
2977     WINE_WAVEIN*        wwi;
2978
2979     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
2980
2981     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2982         WARN("can't get pos !\n");
2983         return MMSYSERR_INVALHANDLE;
2984     }
2985
2986     if (lpTime == NULL) {
2987         WARN("invalid parameter: lpTime == NULL\n");
2988         return MMSYSERR_INVALPARAM;
2989     }
2990
2991     wwi = &WInDev[wDevID];
2992 #ifdef EXACT_WIDPOSITION
2993     if (wwi->ossdev->in_caps_support & WAVECAPS_SAMPLEACCURATE)
2994         OSS_AddRingMessage(&(wwi->msgRing), WINE_WM_UPDATE, 0, TRUE);
2995 #endif
2996
2997     return bytes_to_mmtime(lpTime, wwi->dwTotalRecorded, &wwi->waveFormat);
2998 }
2999
3000 /**************************************************************************
3001  *                              widMessage (WINEOSS.6)
3002  */
3003 DWORD WINAPI OSS_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3004                             DWORD dwParam1, DWORD dwParam2)
3005 {
3006     TRACE("(%u, %s, %08lX, %08lX, %08lX);\n",
3007           wDevID, getMessage(wMsg), dwUser, dwParam1, dwParam2);
3008
3009     switch (wMsg) {
3010     case DRVM_INIT:
3011     case DRVM_EXIT:
3012     case DRVM_ENABLE:
3013     case DRVM_DISABLE:
3014         /* FIXME: Pretend this is supported */
3015         return 0;
3016     case WIDM_OPEN:             return widOpen       (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
3017     case WIDM_CLOSE:            return widClose      (wDevID);
3018     case WIDM_ADDBUFFER:        return widAddBuffer  (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3019     case WIDM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
3020     case WIDM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
3021     case WIDM_GETDEVCAPS:       return widGetDevCaps (wDevID, (LPWAVEINCAPSW)dwParam1, dwParam2);
3022     case WIDM_GETNUMDEVS:       return numInDev;
3023     case WIDM_GETPOS:           return widGetPosition(wDevID, (LPMMTIME)dwParam1, dwParam2);
3024     case WIDM_RESET:            return widReset      (wDevID);
3025     case WIDM_START:            return widStart      (wDevID);
3026     case WIDM_STOP:             return widStop       (wDevID);
3027     case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize      (wDevID, (LPDWORD)dwParam1);
3028     case DRV_QUERYDEVICEINTERFACE:     return widDevInterface          (wDevID, (PWCHAR)dwParam1, dwParam2);
3029     case DRV_QUERYDSOUNDIFACE:  return widDsCreate   (wDevID, (PIDSCDRIVER*)dwParam1);
3030     case DRV_QUERYDSOUNDDESC:   return widDsDesc     (wDevID, (PDSDRIVERDESC)dwParam1);
3031     default:
3032         FIXME("unknown message %u!\n", wMsg);
3033     }
3034     return MMSYSERR_NOTSUPPORTED;
3035 }
3036
3037 #else /* !HAVE_OSS */
3038
3039 /**************************************************************************
3040  *                              wodMessage (WINEOSS.7)
3041  */
3042 DWORD WINAPI OSS_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3043                             DWORD dwParam1, DWORD dwParam2)
3044 {
3045     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3046     return MMSYSERR_NOTENABLED;
3047 }
3048
3049 /**************************************************************************
3050  *                              widMessage (WINEOSS.6)
3051  */
3052 DWORD WINAPI OSS_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3053                             DWORD dwParam1, DWORD dwParam2)
3054 {
3055     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3056     return MMSYSERR_NOTENABLED;
3057 }
3058
3059 #endif /* HAVE_OSS */