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