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