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