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