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