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