Spelling fixes.
[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
1928 /**************************************************************************
1929  *                      wodGetDevCaps                           [internal]
1930  */
1931 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
1932 {
1933     TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1934
1935     if (lpCaps == NULL) {
1936         WARN("not enabled\n");
1937         return MMSYSERR_NOTENABLED;
1938     }
1939
1940     if (wDevID >= numOutDev) {
1941         WARN("numOutDev reached !\n");
1942         return MMSYSERR_BADDEVICEID;
1943     }
1944
1945     if (WOutDev[wDevID].ossdev.open_access == O_RDWR)
1946         memcpy(lpCaps, &WOutDev[wDevID].ossdev.duplex_out_caps, min(dwSize, sizeof(*lpCaps)));
1947     else
1948         memcpy(lpCaps, &WOutDev[wDevID].ossdev.out_caps, min(dwSize, sizeof(*lpCaps)));
1949
1950     return MMSYSERR_NOERROR;
1951 }
1952
1953 /**************************************************************************
1954  *                              wodOpen                         [internal]
1955  */
1956 DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1957 {
1958     int                 audio_fragment;
1959     WINE_WAVEOUT*       wwo;
1960     audio_buf_info      info;
1961     DWORD               ret;
1962
1963     TRACE("(%u, %p[cb=%08x], %08X);\n", wDevID, lpDesc, lpDesc->dwCallback, dwFlags);
1964     if (lpDesc == NULL) {
1965         WARN("Invalid Parameter !\n");
1966         return MMSYSERR_INVALPARAM;
1967     }
1968     if (wDevID >= numOutDev) {
1969         TRACE("MAX_WAVOUTDRV reached !\n");
1970         return MMSYSERR_BADDEVICEID;
1971     }
1972
1973     /* only PCM format is supported so far... */
1974     if (!supportedFormat(lpDesc->lpFormat)) {
1975         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1976              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1977              lpDesc->lpFormat->nSamplesPerSec);
1978         return WAVERR_BADFORMAT;
1979     }
1980
1981     if (dwFlags & WAVE_FORMAT_QUERY) {
1982         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1983              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1984              lpDesc->lpFormat->nSamplesPerSec);
1985         return MMSYSERR_NOERROR;
1986     }
1987
1988     TRACE("OSS_OpenDevice requested this format: %dx%dx%d %s\n",
1989           lpDesc->lpFormat->nSamplesPerSec,
1990           lpDesc->lpFormat->wBitsPerSample,
1991           lpDesc->lpFormat->nChannels,
1992           lpDesc->lpFormat->wFormatTag == WAVE_FORMAT_PCM ? "WAVE_FORMAT_PCM" :
1993           lpDesc->lpFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? "WAVE_FORMAT_EXTENSIBLE" :
1994           "UNSUPPORTED");
1995
1996     wwo = &WOutDev[wDevID];
1997
1998     if ((dwFlags & WAVE_DIRECTSOUND) &&
1999         !(wwo->ossdev.duplex_out_caps.dwSupport & WAVECAPS_DIRECTSOUND))
2000         /* not supported, ignore it */
2001         dwFlags &= ~WAVE_DIRECTSOUND;
2002
2003     if (dwFlags & WAVE_DIRECTSOUND) {
2004         if (wwo->ossdev.duplex_out_caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
2005             /* we have realtime DirectSound, fragments just waste our time,
2006              * but a large buffer is good, so choose 64KB (32 * 2^11) */
2007             audio_fragment = 0x0020000B;
2008         else
2009             /* to approximate realtime, we must use small fragments,
2010              * let's try to fragment the above 64KB (256 * 2^8) */
2011             audio_fragment = 0x01000008;
2012     } else {
2013         /* A wave device must have a worst case latency of 10 ms so calculate
2014          * the largest fragment size less than 10 ms long.
2015          */
2016         int     fsize = lpDesc->lpFormat->nAvgBytesPerSec / 100;        /* 10 ms chunk */
2017         int     shift = 0;
2018         while ((1 << shift) <= fsize)
2019             shift++;
2020         shift--;
2021         audio_fragment = 0x00100000 + shift;    /* 16 fragments of 2^shift */
2022     }
2023
2024     TRACE("requesting %d %d byte fragments (%d ms/fragment)\n",
2025         audio_fragment >> 16, 1 << (audio_fragment & 0xffff),
2026         ((1 << (audio_fragment & 0xffff)) * 1000) / lpDesc->lpFormat->nAvgBytesPerSec);
2027
2028     if (wwo->state != WINE_WS_CLOSED) {
2029         WARN("already allocated\n");
2030         return MMSYSERR_ALLOCATED;
2031     }
2032
2033     /* we want to be able to mmap() the device, which means it must be opened readable,
2034      * otherwise mmap() will fail (at least under Linux) */
2035     ret = OSS_OpenDevice(&wwo->ossdev,
2036                          (dwFlags & WAVE_DIRECTSOUND) ? O_RDWR : O_WRONLY,
2037                          &audio_fragment,
2038                          (dwFlags & WAVE_DIRECTSOUND) ? 0 : 1,
2039                          lpDesc->lpFormat->nSamplesPerSec,
2040                          lpDesc->lpFormat->nChannels,
2041                          (lpDesc->lpFormat->wBitsPerSample == 16)
2042                              ? AFMT_S16_LE : AFMT_U8);
2043     if ((ret==MMSYSERR_NOERROR) && (dwFlags & WAVE_DIRECTSOUND)) {
2044         lpDesc->lpFormat->nSamplesPerSec=wwo->ossdev.sample_rate;
2045         lpDesc->lpFormat->nChannels=wwo->ossdev.channels;
2046         lpDesc->lpFormat->wBitsPerSample=(wwo->ossdev.format == AFMT_U8 ? 8 : 16);
2047         lpDesc->lpFormat->nBlockAlign=lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
2048         lpDesc->lpFormat->nAvgBytesPerSec=lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
2049         TRACE("OSS_OpenDevice returned this format: %dx%dx%d\n",
2050               lpDesc->lpFormat->nSamplesPerSec,
2051               lpDesc->lpFormat->wBitsPerSample,
2052               lpDesc->lpFormat->nChannels);
2053     }
2054     if (ret != 0) return ret;
2055     wwo->state = WINE_WS_STOPPED;
2056
2057     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
2058
2059     wwo->waveDesc = *lpDesc;
2060     copy_format(lpDesc->lpFormat, &wwo->waveFormat);
2061
2062     if (wwo->waveFormat.Format.wBitsPerSample == 0) {
2063         WARN("Resetting zeroed wBitsPerSample\n");
2064         wwo->waveFormat.Format.wBitsPerSample = 8 *
2065             (wwo->waveFormat.Format.nAvgBytesPerSec /
2066              wwo->waveFormat.Format.nSamplesPerSec) /
2067             wwo->waveFormat.Format.nChannels;
2068     }
2069     /* Read output space info for future reference */
2070     if (ioctl(wwo->ossdev.fd, SNDCTL_DSP_GETOSPACE, &info) < 0) {
2071         ERR("ioctl(%s, SNDCTL_DSP_GETOSPACE) failed (%s)\n", wwo->ossdev.dev_name, strerror(errno));
2072         OSS_CloseDevice(&wwo->ossdev);
2073         wwo->state = WINE_WS_CLOSED;
2074         return MMSYSERR_NOTENABLED;
2075     }
2076
2077     TRACE("got %d %d byte fragments (%d ms/fragment)\n", info.fragstotal,
2078         info.fragsize, (info.fragsize * 1000) / (wwo->ossdev.sample_rate *
2079         wwo->ossdev.channels * (wwo->ossdev.format == AFMT_U8 ? 1 : 2)));
2080
2081     /* Check that fragsize is correct per our settings above */
2082     if ((info.fragsize > 1024) && (LOWORD(audio_fragment) <= 10)) {
2083         /* we've tried to set 1K fragments or less, but it didn't work */
2084         WARN("fragment size set failed, size is now %d\n", info.fragsize);
2085     }
2086
2087     /* Remember fragsize and total buffer size for future use */
2088     wwo->dwFragmentSize = info.fragsize;
2089     wwo->dwBufferSize = info.fragstotal * info.fragsize;
2090     wwo->dwPlayedTotal = 0;
2091     wwo->dwWrittenTotal = 0;
2092     wwo->bNeedPost = TRUE;
2093
2094     TRACE("fd=%d fragstotal=%d fragsize=%d BufferSize=%d\n",
2095           wwo->ossdev.fd, info.fragstotal, info.fragsize, wwo->dwBufferSize);
2096     if (wwo->dwFragmentSize % wwo->waveFormat.Format.nBlockAlign) {
2097         ERR("Fragment doesn't contain an integral number of data blocks fragsize=%d BlockAlign=%d\n",wwo->dwFragmentSize,wwo->waveFormat.Format.nBlockAlign);
2098         /* Some SoundBlaster 16 cards return an incorrect (odd) fragment
2099          * size for 16 bit sound. This will cause a system crash when we try
2100          * to write just the specified odd number of bytes. So if we
2101          * detect something is wrong we'd better fix it.
2102          */
2103         wwo->dwFragmentSize-=wwo->dwFragmentSize % wwo->waveFormat.Format.nBlockAlign;
2104     }
2105
2106     OSS_InitRingMessage(&wwo->msgRing);
2107
2108     wwo->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
2109     wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
2110     if (wwo->hThread)
2111         SetThreadPriority(wwo->hThread, THREAD_PRIORITY_TIME_CRITICAL);
2112     WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
2113     CloseHandle(wwo->hStartUpEvent);
2114     wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
2115
2116     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%u, nSamplesPerSec=%u, nChannels=%u nBlockAlign=%u!\n",
2117           wwo->waveFormat.Format.wBitsPerSample, wwo->waveFormat.Format.nAvgBytesPerSec,
2118           wwo->waveFormat.Format.nSamplesPerSec, wwo->waveFormat.Format.nChannels,
2119           wwo->waveFormat.Format.nBlockAlign);
2120
2121     return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
2122 }
2123
2124 /**************************************************************************
2125  *                              wodClose                        [internal]
2126  */
2127 static DWORD wodClose(WORD wDevID)
2128 {
2129     DWORD               ret = MMSYSERR_NOERROR;
2130     WINE_WAVEOUT*       wwo;
2131
2132     TRACE("(%u);\n", wDevID);
2133
2134     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2135         WARN("bad device ID !\n");
2136         return MMSYSERR_BADDEVICEID;
2137     }
2138
2139     wwo = &WOutDev[wDevID];
2140     if (wwo->lpQueuePtr) {
2141         WARN("buffers still playing !\n");
2142         ret = WAVERR_STILLPLAYING;
2143     } else {
2144         if (wwo->hThread != INVALID_HANDLE_VALUE) {
2145             OSS_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
2146         }
2147
2148         OSS_DestroyRingMessage(&wwo->msgRing);
2149
2150         OSS_CloseDevice(&wwo->ossdev);
2151         wwo->state = WINE_WS_CLOSED;
2152         wwo->dwFragmentSize = 0;
2153         ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
2154     }
2155     return ret;
2156 }
2157
2158 /**************************************************************************
2159  *                              wodWrite                        [internal]
2160  *
2161  */
2162 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2163 {
2164     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
2165
2166     /* first, do the sanity checks... */
2167     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2168         WARN("bad dev ID !\n");
2169         return MMSYSERR_BADDEVICEID;
2170     }
2171
2172     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
2173         return WAVERR_UNPREPARED;
2174
2175     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2176         return WAVERR_STILLPLAYING;
2177
2178     lpWaveHdr->dwFlags &= ~WHDR_DONE;
2179     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2180     lpWaveHdr->lpNext = 0;
2181
2182     if ((lpWaveHdr->dwBufferLength & (WOutDev[wDevID].waveFormat.Format.nBlockAlign - 1)) != 0)
2183     {
2184         WARN("WaveHdr length isn't a multiple of the PCM block size: %d %% %d\n",lpWaveHdr->dwBufferLength,WOutDev[wDevID].waveFormat.Format.nBlockAlign);
2185         lpWaveHdr->dwBufferLength &= ~(WOutDev[wDevID].waveFormat.Format.nBlockAlign - 1);
2186     }
2187
2188     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
2189
2190     return MMSYSERR_NOERROR;
2191 }
2192
2193 /**************************************************************************
2194  *                      wodPause                                [internal]
2195  */
2196 static DWORD wodPause(WORD wDevID)
2197 {
2198     TRACE("(%u);!\n", wDevID);
2199
2200     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2201         WARN("bad device ID !\n");
2202         return MMSYSERR_BADDEVICEID;
2203     }
2204
2205     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
2206
2207     return MMSYSERR_NOERROR;
2208 }
2209
2210 /**************************************************************************
2211  *                      wodRestart                              [internal]
2212  */
2213 static DWORD wodRestart(WORD wDevID)
2214 {
2215     TRACE("(%u);\n", wDevID);
2216
2217     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2218         WARN("bad device ID !\n");
2219         return MMSYSERR_BADDEVICEID;
2220     }
2221
2222     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
2223
2224     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
2225     /* FIXME: Myst crashes with this ... hmm -MM
2226        return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
2227     */
2228
2229     return MMSYSERR_NOERROR;
2230 }
2231
2232 /**************************************************************************
2233  *                      wodReset                                [internal]
2234  */
2235 static DWORD wodReset(WORD wDevID)
2236 {
2237     TRACE("(%u);\n", wDevID);
2238
2239     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2240         WARN("bad device ID !\n");
2241         return MMSYSERR_BADDEVICEID;
2242     }
2243
2244     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
2245
2246     return MMSYSERR_NOERROR;
2247 }
2248
2249 /**************************************************************************
2250  *                              wodGetPosition                  [internal]
2251  */
2252 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
2253 {
2254     WINE_WAVEOUT*       wwo;
2255
2256     TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
2257
2258     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2259         WARN("bad device ID !\n");
2260         return MMSYSERR_BADDEVICEID;
2261     }
2262
2263     if (lpTime == NULL) {
2264         WARN("invalid parameter: lpTime == NULL\n");
2265         return MMSYSERR_INVALPARAM;
2266     }
2267
2268     wwo = &WOutDev[wDevID];
2269 #ifdef EXACT_WODPOSITION
2270     if (wwo->ossdev.open_access == O_RDWR) {
2271         if (wwo->ossdev.duplex_out_caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
2272             OSS_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
2273     } else {
2274         if (wwo->ossdev.out_caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
2275             OSS_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
2276     }
2277 #endif
2278
2279     return bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->waveFormat);
2280 }
2281
2282 /**************************************************************************
2283  *                              wodBreakLoop                    [internal]
2284  */
2285 static DWORD wodBreakLoop(WORD wDevID)
2286 {
2287     TRACE("(%u);\n", wDevID);
2288
2289     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2290         WARN("bad device ID !\n");
2291         return MMSYSERR_BADDEVICEID;
2292     }
2293     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
2294     return MMSYSERR_NOERROR;
2295 }
2296
2297 /**************************************************************************
2298  *                              wodGetVolume                    [internal]
2299  */
2300 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
2301 {
2302     int         mixer;
2303     int         volume;
2304     DWORD       left, right;
2305     DWORD       last_left, last_right;
2306
2307     TRACE("(%u, %p);\n", wDevID, lpdwVol);
2308
2309     if (lpdwVol == NULL) {
2310         WARN("not enabled\n");
2311         return MMSYSERR_NOTENABLED;
2312     }
2313     if (wDevID >= numOutDev) {
2314         WARN("invalid parameter\n");
2315         return MMSYSERR_INVALPARAM;
2316     }
2317     if (WOutDev[wDevID].ossdev.open_access == O_RDWR) {
2318         if (!(WOutDev[wDevID].ossdev.duplex_out_caps.dwSupport & WAVECAPS_VOLUME)) {
2319             TRACE("Volume not supported\n");
2320             return MMSYSERR_NOTSUPPORTED;
2321         }
2322     } else {
2323         if (!(WOutDev[wDevID].ossdev.out_caps.dwSupport & WAVECAPS_VOLUME)) {
2324             TRACE("Volume not supported\n");
2325             return MMSYSERR_NOTSUPPORTED;
2326         }
2327     }
2328
2329     if ((mixer = open(WOutDev[wDevID].ossdev.mixer_name, O_RDONLY|O_NDELAY)) < 0) {
2330         WARN("mixer device not available !\n");
2331         return MMSYSERR_NOTENABLED;
2332     }
2333     if (ioctl(mixer, SOUND_MIXER_READ_PCM, &volume) == -1) {
2334         close(mixer);
2335         WARN("ioctl(%s, SOUND_MIXER_READ_PCM) failed (%s)\n",
2336              WOutDev[wDevID].ossdev.mixer_name, strerror(errno));
2337         return MMSYSERR_NOTENABLED;
2338     }
2339     close(mixer);
2340
2341     left = LOBYTE(volume);
2342     right = HIBYTE(volume);
2343     TRACE("left=%d right=%d !\n", left, right);
2344     last_left  = (LOWORD(WOutDev[wDevID].volume) * 100) / 0xFFFFl;
2345     last_right = (HIWORD(WOutDev[wDevID].volume) * 100) / 0xFFFFl;
2346     TRACE("last_left=%d last_right=%d !\n", last_left, last_right);
2347     if (last_left == left && last_right == right)
2348         *lpdwVol = WOutDev[wDevID].volume;
2349     else
2350         *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) << 16);
2351     return MMSYSERR_NOERROR;
2352 }
2353
2354 /**************************************************************************
2355  *                              wodSetVolume                    [internal]
2356  */
2357 DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
2358 {
2359     int         mixer;
2360     int         volume;
2361     DWORD       left, right;
2362
2363     TRACE("(%u, %08X);\n", wDevID, dwParam);
2364
2365     left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
2366     right = (HIWORD(dwParam) * 100) / 0xFFFFl;
2367     volume = left + (right << 8);
2368
2369     if (wDevID >= numOutDev) {
2370         WARN("invalid parameter: wDevID > %d\n", numOutDev);
2371         return MMSYSERR_INVALPARAM;
2372     }
2373     if (WOutDev[wDevID].ossdev.open_access == O_RDWR) {
2374         if (!(WOutDev[wDevID].ossdev.duplex_out_caps.dwSupport & WAVECAPS_VOLUME)) {
2375             TRACE("Volume not supported\n");
2376             return MMSYSERR_NOTSUPPORTED;
2377         }
2378     } else {
2379         if (!(WOutDev[wDevID].ossdev.out_caps.dwSupport & WAVECAPS_VOLUME)) {
2380             TRACE("Volume not supported\n");
2381             return MMSYSERR_NOTSUPPORTED;
2382         }
2383     }
2384     if ((mixer = open(WOutDev[wDevID].ossdev.mixer_name, O_WRONLY|O_NDELAY)) < 0) {
2385         WARN("open(%s) failed (%s)\n", WOutDev[wDevID].ossdev.mixer_name, strerror(errno));
2386         return MMSYSERR_NOTENABLED;
2387     }
2388     if (ioctl(mixer, SOUND_MIXER_WRITE_PCM, &volume) == -1) {
2389         close(mixer);
2390         WARN("ioctl(%s, SOUND_MIXER_WRITE_PCM) failed (%s)\n",
2391             WOutDev[wDevID].ossdev.mixer_name, strerror(errno));
2392         return MMSYSERR_NOTENABLED;
2393     }
2394     TRACE("volume=%04x\n", (unsigned)volume);
2395     close(mixer);
2396
2397     /* save requested volume */
2398     WOutDev[wDevID].volume = dwParam;
2399
2400     return MMSYSERR_NOERROR;
2401 }
2402
2403 /**************************************************************************
2404  *                              wodMessage (WINEOSS.7)
2405  */
2406 DWORD WINAPI OSS_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
2407                             DWORD dwParam1, DWORD dwParam2)
2408 {
2409     TRACE("(%u, %s, %08X, %08X, %08X);\n",
2410           wDevID, getMessage(wMsg), dwUser, dwParam1, dwParam2);
2411
2412     switch (wMsg) {
2413     case DRVM_INIT:
2414     case DRVM_EXIT:
2415     case DRVM_ENABLE:
2416     case DRVM_DISABLE:
2417         /* FIXME: Pretend this is supported */
2418         return 0;
2419     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
2420     case WODM_CLOSE:            return wodClose         (wDevID);
2421     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
2422     case WODM_PAUSE:            return wodPause         (wDevID);
2423     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
2424     case WODM_BREAKLOOP:        return wodBreakLoop     (wDevID);
2425     case WODM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
2426     case WODM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
2427     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSW)dwParam1,      dwParam2);
2428     case WODM_GETNUMDEVS:       return numOutDev;
2429     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
2430     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
2431     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
2432     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
2433     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
2434     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
2435     case WODM_RESTART:          return wodRestart       (wDevID);
2436     case WODM_RESET:            return wodReset         (wDevID);
2437
2438     case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize      (wDevID, (LPDWORD)dwParam1);
2439     case DRV_QUERYDEVICEINTERFACE:     return wodDevInterface          (wDevID, (PWCHAR)dwParam1, dwParam2);
2440     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate      (wDevID, (PIDSDRIVER*)dwParam1);
2441     case DRV_QUERYDSOUNDDESC:   return wodDsDesc        (wDevID, (PDSDRIVERDESC)dwParam1);
2442     default:
2443         FIXME("unknown message %d!\n", wMsg);
2444     }
2445     return MMSYSERR_NOTSUPPORTED;
2446 }
2447
2448 /*======================================================================*
2449  *                  Low level WAVE IN implementation                    *
2450  *======================================================================*/
2451
2452 /**************************************************************************
2453  *                      widNotifyClient                 [internal]
2454  */
2455 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
2456 {
2457     TRACE("wMsg = 0x%04x (%s) dwParm1 = %04X dwParam2 = %04X\n", wMsg,
2458         wMsg == WIM_OPEN ? "WIM_OPEN" : wMsg == WIM_CLOSE ? "WIM_CLOSE" :
2459         wMsg == WIM_DATA ? "WIM_DATA" : "Unknown", dwParam1, dwParam2);
2460
2461     switch (wMsg) {
2462     case WIM_OPEN:
2463     case WIM_CLOSE:
2464     case WIM_DATA:
2465         if (wwi->wFlags != DCB_NULL &&
2466             !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
2467                             (HDRVR)wwi->waveDesc.hWave, wMsg,
2468                             wwi->waveDesc.dwInstance, dwParam1, dwParam2)) {
2469             WARN("can't notify client !\n");
2470             return MMSYSERR_ERROR;
2471         }
2472         break;
2473     default:
2474         FIXME("Unknown callback message %u\n", wMsg);
2475         return MMSYSERR_INVALPARAM;
2476     }
2477     return MMSYSERR_NOERROR;
2478 }
2479
2480 /**************************************************************************
2481  *                      widGetDevCaps                           [internal]
2482  */
2483 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
2484 {
2485     TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
2486
2487     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
2488
2489     if (wDevID >= numInDev) {
2490         TRACE("numOutDev reached !\n");
2491         return MMSYSERR_BADDEVICEID;
2492     }
2493
2494     memcpy(lpCaps, &WInDev[wDevID].ossdev.in_caps, min(dwSize, sizeof(*lpCaps)));
2495     return MMSYSERR_NOERROR;
2496 }
2497
2498 /**************************************************************************
2499  *                              widRecorder_ReadHeaders         [internal]
2500  */
2501 static void widRecorder_ReadHeaders(WINE_WAVEIN * wwi)
2502 {
2503     enum win_wm_message tmp_msg;
2504     DWORD               tmp_param;
2505     HANDLE              tmp_ev;
2506     WAVEHDR*            lpWaveHdr;
2507
2508     while (OSS_RetrieveRingMessage(&wwi->msgRing, &tmp_msg, &tmp_param, &tmp_ev)) {
2509         if (tmp_msg == WINE_WM_HEADER) {
2510             LPWAVEHDR*  wh;
2511             lpWaveHdr = (LPWAVEHDR)tmp_param;
2512             lpWaveHdr->lpNext = 0;
2513
2514             if (wwi->lpQueuePtr == 0)
2515                 wwi->lpQueuePtr = lpWaveHdr;
2516             else {
2517                 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2518                 *wh = lpWaveHdr;
2519             }
2520         } else {
2521             ERR("should only have headers left\n");
2522         }
2523     }
2524 }
2525
2526 /**************************************************************************
2527  *                              widRecorder                     [internal]
2528  */
2529 static  DWORD   CALLBACK        widRecorder(LPVOID pmt)
2530 {
2531     WORD                uDevID = (DWORD)pmt;
2532     WINE_WAVEIN*        wwi = &WInDev[uDevID];
2533     WAVEHDR*            lpWaveHdr;
2534     DWORD               dwSleepTime;
2535     DWORD               bytesRead;
2536     LPVOID              buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, wwi->dwFragmentSize);
2537     char               *pOffset = buffer;
2538     audio_buf_info      info;
2539     int                 xs;
2540     enum win_wm_message msg;
2541     DWORD               param;
2542     HANDLE              ev;
2543     int                 enable;
2544
2545     wwi->state = WINE_WS_STOPPED;
2546     wwi->dwTotalRecorded = 0;
2547     wwi->dwTotalRead = 0;
2548     wwi->lpQueuePtr = NULL;
2549
2550     SetEvent(wwi->hStartUpEvent);
2551
2552     /* disable input so capture will begin when triggered */
2553     wwi->ossdev.bInputEnabled = FALSE;
2554     enable = getEnables(&wwi->ossdev);
2555     if (ioctl(wwi->ossdev.fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0)
2556         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", wwi->ossdev.dev_name, strerror(errno));
2557
2558     /* the soundblaster live needs a micro wake to get its recording started
2559      * (or GETISPACE will have 0 frags all the time)
2560      */
2561     read(wwi->ossdev.fd, &xs, 4);
2562
2563     /* make sleep time to be # of ms to output a fragment */
2564     dwSleepTime = (wwi->dwFragmentSize * 1000) / wwi->waveFormat.Format.nAvgBytesPerSec;
2565     TRACE("sleeptime=%d ms\n", dwSleepTime);
2566
2567     for (;;) {
2568         /* wait for dwSleepTime or an event in thread's queue */
2569         /* FIXME: could improve wait time depending on queue state,
2570          * ie, number of queued fragments
2571          */
2572
2573         if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
2574         {
2575             lpWaveHdr = wwi->lpQueuePtr;
2576
2577             ioctl(wwi->ossdev.fd, SNDCTL_DSP_GETISPACE, &info);
2578             TRACE("info={frag=%d fsize=%d ftotal=%d bytes=%d}\n", info.fragments, info.fragsize, info.fragstotal, info.bytes);
2579
2580             /* read all the fragments accumulated so far */
2581             while ((info.fragments > 0) && (wwi->lpQueuePtr))
2582             {
2583                 info.fragments --;
2584
2585                 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwFragmentSize)
2586                 {
2587                     /* directly read fragment in wavehdr */
2588                     bytesRead = read(wwi->ossdev.fd,
2589                                      lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2590                                      wwi->dwFragmentSize);
2591
2592                     TRACE("bytesRead=%d (direct)\n", bytesRead);
2593                     if (bytesRead != (DWORD) -1)
2594                     {
2595                         /* update number of bytes recorded in current buffer and by this device */
2596                         lpWaveHdr->dwBytesRecorded += bytesRead;
2597                         wwi->dwTotalRead           += bytesRead;
2598                         wwi->dwTotalRecorded = wwi->dwTotalRead;
2599
2600                         /* buffer is full. notify client */
2601                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2602                         {
2603                             /* must copy the value of next waveHdr, because we have no idea of what
2604                              * will be done with the content of lpWaveHdr in callback
2605                              */
2606                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
2607
2608                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2609                             lpWaveHdr->dwFlags |=  WHDR_DONE;
2610
2611                             wwi->lpQueuePtr = lpNext;
2612                             widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2613                             lpWaveHdr = lpNext;
2614                         }
2615                     } else {
2616                         TRACE("read(%s, %p, %d) failed (%s)\n", wwi->ossdev.dev_name,
2617                             lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2618                             wwi->dwFragmentSize, strerror(errno));
2619                     }
2620                 }
2621                 else
2622                 {
2623                     /* read the fragment in a local buffer */
2624                     bytesRead = read(wwi->ossdev.fd, buffer, wwi->dwFragmentSize);
2625                     pOffset = buffer;
2626
2627                     TRACE("bytesRead=%d (local)\n", bytesRead);
2628
2629                     if (bytesRead == (DWORD) -1) {
2630                         TRACE("read(%s, %p, %d) failed (%s)\n", wwi->ossdev.dev_name,
2631                             buffer, wwi->dwFragmentSize, strerror(errno));
2632                         continue;
2633                     }
2634
2635                     /* copy data in client buffers */
2636                     while (bytesRead != (DWORD) -1 && bytesRead > 0)
2637                     {
2638                         DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
2639
2640                         memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2641                                pOffset,
2642                                dwToCopy);
2643
2644                         /* update number of bytes recorded in current buffer and by this device */
2645                         lpWaveHdr->dwBytesRecorded += dwToCopy;
2646                         wwi->dwTotalRead           += dwToCopy;
2647                         wwi->dwTotalRecorded = wwi->dwTotalRead;
2648                         bytesRead -= dwToCopy;
2649                         pOffset   += dwToCopy;
2650
2651                         /* client buffer is full. notify client */
2652                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2653                         {
2654                             /* must copy the value of next waveHdr, because we have no idea of what
2655                              * will be done with the content of lpWaveHdr in callback
2656                              */
2657                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
2658                             TRACE("lpNext=%p\n", lpNext);
2659
2660                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2661                             lpWaveHdr->dwFlags |=  WHDR_DONE;
2662
2663                             wwi->lpQueuePtr = lpNext;
2664                             widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2665
2666                             lpWaveHdr = lpNext;
2667                             if (!lpNext && bytesRead) {
2668                                 /* before we give up, check for more header messages */
2669                                 while (OSS_PeekRingMessage(&wwi->msgRing, &msg, &param, &ev))
2670                                 {
2671                                     if (msg == WINE_WM_HEADER) {
2672                                         LPWAVEHDR hdr;
2673                                         OSS_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev);
2674                                         hdr = ((LPWAVEHDR)param);
2675                                         TRACE("msg = %s, hdr = %p, ev = %p\n", getCmdString(msg), hdr, ev);
2676                                         hdr->lpNext = 0;
2677                                         if (lpWaveHdr == 0) {
2678                                             /* new head of queue */
2679                                             wwi->lpQueuePtr = lpWaveHdr = hdr;
2680                                         } else {
2681                                             /* insert buffer at the end of queue */
2682                                             LPWAVEHDR*  wh;
2683                                             for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2684                                             *wh = hdr;
2685                                         }
2686                                     } else
2687                                         break;
2688                                 }
2689
2690                                 if (lpWaveHdr == 0) {
2691                                     /* no more buffer to copy data to, but we did read more.
2692                                      * what hasn't been copied will be dropped
2693                                      */
2694                                     WARN("buffer under run! %u bytes dropped.\n", bytesRead);
2695                                     wwi->lpQueuePtr = NULL;
2696                                     break;
2697                                 }
2698                             }
2699                         }
2700                     }
2701                 }
2702             }
2703         }
2704
2705         WAIT_OMR(&wwi->msgRing, dwSleepTime);
2706
2707         while (OSS_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev))
2708         {
2709             TRACE("msg=%s param=0x%x\n", getCmdString(msg), param);
2710             switch (msg) {
2711             case WINE_WM_PAUSING:
2712                 wwi->state = WINE_WS_PAUSED;
2713                 /*FIXME("Device should stop recording\n");*/
2714                 SetEvent(ev);
2715                 break;
2716             case WINE_WM_STARTING:
2717                 wwi->state = WINE_WS_PLAYING;
2718
2719                 if (wwi->ossdev.bTriggerSupport)
2720                 {
2721                     /* start the recording */
2722                     wwi->ossdev.bInputEnabled = TRUE;
2723                     enable = getEnables(&wwi->ossdev);
2724                     if (ioctl(wwi->ossdev.fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
2725                         wwi->ossdev.bInputEnabled = FALSE;
2726                         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", wwi->ossdev.dev_name, strerror(errno));
2727                     }
2728                 }
2729                 else
2730                 {
2731                     unsigned char data[4];
2732                     /* read 4 bytes to start the recording */
2733                     read(wwi->ossdev.fd, data, 4);
2734                 }
2735
2736                 SetEvent(ev);
2737                 break;
2738             case WINE_WM_HEADER:
2739                 lpWaveHdr = (LPWAVEHDR)param;
2740                 lpWaveHdr->lpNext = 0;
2741
2742                 /* insert buffer at the end of queue */
2743                 {
2744                     LPWAVEHDR*  wh;
2745                     for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2746                     *wh = lpWaveHdr;
2747                 }
2748                 break;
2749             case WINE_WM_STOPPING:
2750                 if (wwi->state != WINE_WS_STOPPED)
2751                 {
2752                     if (wwi->ossdev.bTriggerSupport)
2753                     {
2754                         /* stop the recording */
2755                         wwi->ossdev.bInputEnabled = FALSE;
2756                         enable = getEnables(&wwi->ossdev);
2757                         if (ioctl(wwi->ossdev.fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
2758                             wwi->ossdev.bInputEnabled = FALSE;
2759                             ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", wwi->ossdev.dev_name, strerror(errno));
2760                         }
2761                     }
2762
2763                     /* read any headers in queue */
2764                     widRecorder_ReadHeaders(wwi);
2765
2766                     /* return current buffer to app */
2767                     lpWaveHdr = wwi->lpQueuePtr;
2768                     if (lpWaveHdr)
2769                     {
2770                         LPWAVEHDR       lpNext = lpWaveHdr->lpNext;
2771                         TRACE("stop %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
2772                         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2773                         lpWaveHdr->dwFlags |= WHDR_DONE;
2774                         wwi->lpQueuePtr = lpNext;
2775                         widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2776                     }
2777                 }
2778                 wwi->state = WINE_WS_STOPPED;
2779                 SetEvent(ev);
2780                 break;
2781             case WINE_WM_RESETTING:
2782                 if (wwi->state != WINE_WS_STOPPED)
2783                 {
2784                     if (wwi->ossdev.bTriggerSupport)
2785                     {
2786                         /* stop the recording */
2787                         wwi->ossdev.bInputEnabled = FALSE;
2788                         enable = getEnables(&wwi->ossdev);
2789                         if (ioctl(wwi->ossdev.fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
2790                             wwi->ossdev.bInputEnabled = FALSE;
2791                             ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", wwi->ossdev.dev_name, strerror(errno));
2792                         }
2793                     }
2794                 }
2795                 wwi->state = WINE_WS_STOPPED;
2796                 wwi->dwTotalRecorded = 0;
2797                 wwi->dwTotalRead = 0;
2798
2799                 /* read any headers in queue */
2800                 widRecorder_ReadHeaders(wwi);
2801
2802                 /* return all buffers to the app */
2803                 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
2804                     TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
2805                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2806                     lpWaveHdr->dwFlags |= WHDR_DONE;
2807                     wwi->lpQueuePtr = lpWaveHdr->lpNext;
2808                     widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2809                 }
2810
2811                 wwi->lpQueuePtr = NULL;
2812                 SetEvent(ev);
2813                 break;
2814             case WINE_WM_UPDATE:
2815                 if (wwi->state == WINE_WS_PLAYING) {
2816                     audio_buf_info tmp_info;
2817                     if (ioctl(wwi->ossdev.fd, SNDCTL_DSP_GETISPACE, &tmp_info) < 0)
2818                         ERR("ioctl(%s, SNDCTL_DSP_GETISPACE) failed (%s)\n", wwi->ossdev.dev_name, strerror(errno));
2819                     else
2820                         wwi->dwTotalRecorded = wwi->dwTotalRead + tmp_info.bytes;
2821                 }
2822                 SetEvent(ev);
2823                 break;
2824             case WINE_WM_CLOSING:
2825                 wwi->hThread = 0;
2826                 wwi->state = WINE_WS_CLOSED;
2827                 SetEvent(ev);
2828                 HeapFree(GetProcessHeap(), 0, buffer);
2829                 ExitThread(0);
2830                 /* shouldn't go here */
2831             default:
2832                 FIXME("unknown message %d\n", msg);
2833                 break;
2834             }
2835         }
2836     }
2837     ExitThread(0);
2838     /* just for not generating compilation warnings... should never be executed */
2839     return 0;
2840 }
2841
2842
2843 /**************************************************************************
2844  *                              widOpen                         [internal]
2845  */
2846 DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
2847 {
2848     WINE_WAVEIN*        wwi;
2849     audio_buf_info      info;
2850     int                 audio_fragment;
2851     DWORD               ret;
2852
2853     TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
2854     if (lpDesc == NULL) {
2855         WARN("Invalid Parameter !\n");
2856         return MMSYSERR_INVALPARAM;
2857     }
2858     if (wDevID >= numInDev) {
2859         WARN("bad device id: %d >= %d\n", wDevID, numInDev);
2860         return MMSYSERR_BADDEVICEID;
2861     }
2862
2863     /* only PCM format is supported so far... */
2864     if (!supportedFormat(lpDesc->lpFormat)) {
2865         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
2866              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
2867              lpDesc->lpFormat->nSamplesPerSec);
2868         return WAVERR_BADFORMAT;
2869     }
2870
2871     if (dwFlags & WAVE_FORMAT_QUERY) {
2872         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
2873              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
2874              lpDesc->lpFormat->nSamplesPerSec);
2875         return MMSYSERR_NOERROR;
2876     }
2877
2878     TRACE("OSS_OpenDevice requested this format: %dx%dx%d %s\n",
2879           lpDesc->lpFormat->nSamplesPerSec,
2880           lpDesc->lpFormat->wBitsPerSample,
2881           lpDesc->lpFormat->nChannels,
2882           lpDesc->lpFormat->wFormatTag == WAVE_FORMAT_PCM ? "WAVE_FORMAT_PCM" :
2883           lpDesc->lpFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? "WAVE_FORMAT_EXTENSIBLE" :
2884           "UNSUPPORTED");
2885
2886     wwi = &WInDev[wDevID];
2887
2888     if (wwi->state != WINE_WS_CLOSED) return MMSYSERR_ALLOCATED;
2889
2890     if ((dwFlags & WAVE_DIRECTSOUND) &&
2891         !(wwi->ossdev.in_caps_support & WAVECAPS_DIRECTSOUND))
2892         /* not supported, ignore it */
2893         dwFlags &= ~WAVE_DIRECTSOUND;
2894
2895     if (dwFlags & WAVE_DIRECTSOUND) {
2896         TRACE("has DirectSoundCapture driver\n");
2897         if (wwi->ossdev.in_caps_support & WAVECAPS_SAMPLEACCURATE)
2898             /* we have realtime DirectSound, fragments just waste our time,
2899              * but a large buffer is good, so choose 64KB (32 * 2^11) */
2900             audio_fragment = 0x0020000B;
2901         else
2902             /* to approximate realtime, we must use small fragments,
2903              * let's try to fragment the above 64KB (256 * 2^8) */
2904             audio_fragment = 0x01000008;
2905     } else {
2906         TRACE("doesn't have DirectSoundCapture driver\n");
2907         if (wwi->ossdev.open_count > 0) {
2908             TRACE("Using output device audio_fragment\n");
2909             /* FIXME: This may not be optimal for capture but it allows us
2910              * to do hardware playback without hardware capture. */
2911             audio_fragment = wwi->ossdev.audio_fragment;
2912         } else {
2913             /* A wave device must have a worst case latency of 10 ms so calculate
2914              * the largest fragment size less than 10 ms long.
2915              */
2916             int fsize = lpDesc->lpFormat->nAvgBytesPerSec / 100;        /* 10 ms chunk */
2917             int shift = 0;
2918             while ((1 << shift) <= fsize)
2919                 shift++;
2920             shift--;
2921             audio_fragment = 0x00100000 + shift;        /* 16 fragments of 2^shift */
2922         }
2923     }
2924
2925     TRACE("requesting %d %d byte fragments (%d ms)\n", audio_fragment >> 16,
2926         1 << (audio_fragment & 0xffff),
2927         ((1 << (audio_fragment & 0xffff)) * 1000) / lpDesc->lpFormat->nAvgBytesPerSec);
2928
2929     ret = OSS_OpenDevice(&wwi->ossdev, O_RDONLY, &audio_fragment,
2930                          1,
2931                          lpDesc->lpFormat->nSamplesPerSec,
2932                          lpDesc->lpFormat->nChannels,
2933                          (lpDesc->lpFormat->wBitsPerSample == 16)
2934                          ? AFMT_S16_LE : AFMT_U8);
2935     if (ret != 0) return ret;
2936     wwi->state = WINE_WS_STOPPED;
2937
2938     if (wwi->lpQueuePtr) {
2939         WARN("Should have an empty queue (%p)\n", wwi->lpQueuePtr);
2940         wwi->lpQueuePtr = NULL;
2941     }
2942     wwi->dwTotalRecorded = 0;
2943     wwi->dwTotalRead = 0;
2944     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
2945
2946     wwi->waveDesc = *lpDesc;
2947     copy_format(lpDesc->lpFormat, &wwi->waveFormat);
2948
2949     if (wwi->waveFormat.Format.wBitsPerSample == 0) {
2950         WARN("Resetting zeroed wBitsPerSample\n");
2951         wwi->waveFormat.Format.wBitsPerSample = 8 *
2952             (wwi->waveFormat.Format.nAvgBytesPerSec /
2953              wwi->waveFormat.Format.nSamplesPerSec) /
2954             wwi->waveFormat.Format.nChannels;
2955     }
2956
2957     if (ioctl(wwi->ossdev.fd, SNDCTL_DSP_GETISPACE, &info) < 0) {
2958         ERR("ioctl(%s, SNDCTL_DSP_GETISPACE) failed (%s)\n",
2959             wwi->ossdev.dev_name, strerror(errno));
2960         OSS_CloseDevice(&wwi->ossdev);
2961         wwi->state = WINE_WS_CLOSED;
2962         return MMSYSERR_NOTENABLED;
2963     }
2964
2965     TRACE("got %d %d byte fragments (%d ms/fragment)\n", info.fragstotal,
2966         info.fragsize, (info.fragsize * 1000) / (wwi->ossdev.sample_rate *
2967         wwi->ossdev.channels * (wwi->ossdev.format == AFMT_U8 ? 1 : 2)));
2968
2969     wwi->dwFragmentSize = info.fragsize;
2970
2971     TRACE("dwFragmentSize=%u\n", wwi->dwFragmentSize);
2972     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%u, nSamplesPerSec=%u, nChannels=%u nBlockAlign=%u!\n",
2973           wwi->waveFormat.Format.wBitsPerSample, wwi->waveFormat.Format.nAvgBytesPerSec,
2974           wwi->waveFormat.Format.nSamplesPerSec, wwi->waveFormat.Format.nChannels,
2975           wwi->waveFormat.Format.nBlockAlign);
2976
2977     OSS_InitRingMessage(&wwi->msgRing);
2978
2979     wwi->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
2980     wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
2981     if (wwi->hThread)
2982         SetThreadPriority(wwi->hThread, THREAD_PRIORITY_TIME_CRITICAL);
2983     WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
2984     CloseHandle(wwi->hStartUpEvent);
2985     wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
2986
2987     return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
2988 }
2989
2990 /**************************************************************************
2991  *                              widClose                        [internal]
2992  */
2993 static DWORD widClose(WORD wDevID)
2994 {
2995     WINE_WAVEIN*        wwi;
2996
2997     TRACE("(%u);\n", wDevID);
2998     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2999         WARN("can't close !\n");
3000         return MMSYSERR_INVALHANDLE;
3001     }
3002
3003     wwi = &WInDev[wDevID];
3004
3005     if (wwi->lpQueuePtr != NULL) {
3006         WARN("still buffers open !\n");
3007         return WAVERR_STILLPLAYING;
3008     }
3009
3010     OSS_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
3011     OSS_CloseDevice(&wwi->ossdev);
3012     wwi->state = WINE_WS_CLOSED;
3013     wwi->dwFragmentSize = 0;
3014     OSS_DestroyRingMessage(&wwi->msgRing);
3015     return widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
3016 }
3017
3018 /**************************************************************************
3019  *                              widAddBuffer            [internal]
3020  */
3021 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3022 {
3023     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
3024
3025     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
3026         WARN("can't do it !\n");
3027         return MMSYSERR_INVALHANDLE;
3028     }
3029     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED)) {
3030         TRACE("never been prepared !\n");
3031         return WAVERR_UNPREPARED;
3032     }
3033     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) {
3034         TRACE("header already in use !\n");
3035         return WAVERR_STILLPLAYING;
3036     }
3037
3038     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
3039     lpWaveHdr->dwFlags &= ~WHDR_DONE;
3040     lpWaveHdr->dwBytesRecorded = 0;
3041     lpWaveHdr->lpNext = NULL;
3042
3043     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
3044     return MMSYSERR_NOERROR;
3045 }
3046
3047 /**************************************************************************
3048  *                      widStart                                [internal]
3049  */
3050 static DWORD widStart(WORD wDevID)
3051 {
3052     TRACE("(%u);\n", wDevID);
3053     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
3054         WARN("can't start recording !\n");
3055         return MMSYSERR_INVALHANDLE;
3056     }
3057
3058     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
3059     return MMSYSERR_NOERROR;
3060 }
3061
3062 /**************************************************************************
3063  *                      widStop                                 [internal]
3064  */
3065 static DWORD widStop(WORD wDevID)
3066 {
3067     TRACE("(%u);\n", wDevID);
3068     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
3069         WARN("can't stop !\n");
3070         return MMSYSERR_INVALHANDLE;
3071     }
3072
3073     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
3074
3075     return MMSYSERR_NOERROR;
3076 }
3077
3078 /**************************************************************************
3079  *                      widReset                                [internal]
3080  */
3081 static DWORD widReset(WORD wDevID)
3082 {
3083     TRACE("(%u);\n", wDevID);
3084     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
3085         WARN("can't reset !\n");
3086         return MMSYSERR_INVALHANDLE;
3087     }
3088     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
3089     return MMSYSERR_NOERROR;
3090 }
3091
3092 /**************************************************************************
3093  *                              widGetPosition                  [internal]
3094  */
3095 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
3096 {
3097     WINE_WAVEIN*        wwi;
3098
3099     TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
3100
3101     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
3102         WARN("can't get pos !\n");
3103         return MMSYSERR_INVALHANDLE;
3104     }
3105
3106     if (lpTime == NULL) {
3107         WARN("invalid parameter: lpTime == NULL\n");
3108         return MMSYSERR_INVALPARAM;
3109     }
3110
3111     wwi = &WInDev[wDevID];
3112 #ifdef EXACT_WIDPOSITION
3113     if (wwi->ossdev.in_caps_support & WAVECAPS_SAMPLEACCURATE)
3114         OSS_AddRingMessage(&(wwi->msgRing), WINE_WM_UPDATE, 0, TRUE);
3115 #endif
3116
3117     return bytes_to_mmtime(lpTime, wwi->dwTotalRecorded, &wwi->waveFormat);
3118 }
3119
3120 /**************************************************************************
3121  *                              widMessage (WINEOSS.6)
3122  */
3123 DWORD WINAPI OSS_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3124                             DWORD dwParam1, DWORD dwParam2)
3125 {
3126     TRACE("(%u, %s, %08X, %08X, %08X);\n",
3127           wDevID, getMessage(wMsg), dwUser, dwParam1, dwParam2);
3128
3129     switch (wMsg) {
3130     case DRVM_INIT:
3131     case DRVM_EXIT:
3132     case DRVM_ENABLE:
3133     case DRVM_DISABLE:
3134         /* FIXME: Pretend this is supported */
3135         return 0;
3136     case WIDM_OPEN:             return widOpen       (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
3137     case WIDM_CLOSE:            return widClose      (wDevID);
3138     case WIDM_ADDBUFFER:        return widAddBuffer  (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3139     case WIDM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
3140     case WIDM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
3141     case WIDM_GETDEVCAPS:       return widGetDevCaps (wDevID, (LPWAVEINCAPSW)dwParam1, dwParam2);
3142     case WIDM_GETNUMDEVS:       return numInDev;
3143     case WIDM_GETPOS:           return widGetPosition(wDevID, (LPMMTIME)dwParam1, dwParam2);
3144     case WIDM_RESET:            return widReset      (wDevID);
3145     case WIDM_START:            return widStart      (wDevID);
3146     case WIDM_STOP:             return widStop       (wDevID);
3147     case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize      (wDevID, (LPDWORD)dwParam1);
3148     case DRV_QUERYDEVICEINTERFACE:     return widDevInterface          (wDevID, (PWCHAR)dwParam1, dwParam2);
3149     case DRV_QUERYDSOUNDIFACE:  return widDsCreate   (wDevID, (PIDSCDRIVER*)dwParam1);
3150     case DRV_QUERYDSOUNDDESC:   return widDsDesc     (wDevID, (PDSDRIVERDESC)dwParam1);
3151     default:
3152         FIXME("unknown message %u!\n", wMsg);
3153     }
3154     return MMSYSERR_NOTSUPPORTED;
3155 }
3156
3157 #else /* !HAVE_OSS */
3158
3159 /**************************************************************************
3160  *                              wodMessage (WINEOSS.7)
3161  */
3162 DWORD WINAPI OSS_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3163                             DWORD dwParam1, DWORD dwParam2)
3164 {
3165     FIXME("(%u, %04X, %08X, %08X, %08X):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3166     return MMSYSERR_NOTENABLED;
3167 }
3168
3169 /**************************************************************************
3170  *                              widMessage (WINEOSS.6)
3171  */
3172 DWORD WINAPI OSS_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3173                             DWORD dwParam1, DWORD dwParam2)
3174 {
3175     FIXME("(%u, %04X, %08X, %08X, %08X):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3176     return MMSYSERR_NOTENABLED;
3177 }
3178
3179 #endif /* HAVE_OSS */