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