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