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