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