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