If unable to set the desired format, OSS_RawOpenDevice should call
[wine] / dlls / winmm / wineoss / audio.c
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
2 /*
3  * Sample Wine Driver for Open Sound System (featured in Linux and FreeBSD)
4  *
5  * Copyright 1994 Martin Ayotte
6  *           1999 Eric Pouech (async playing in waveOut/waveIn)
7  *           2000 Eric Pouech (loops in waveOut)
8  *           2002 Eric Pouech (full duplex)
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  */
24 /*
25  * FIXME:
26  *      pause in waveOut does not work correctly in loop mode
27  */
28
29 /*#define EMULATE_SB16*/
30
31 /* unless someone makes a wineserver kernel module, Unix pipes are faster than win32 events */
32 #define USE_PIPE_SYNC
33
34 /* an exact wodGetPosition is usually not worth the extra context switches,
35  * as we're going to have near fragment accuracy anyway */
36 /* #define EXACT_WODPOSITION */
37
38 #include "config.h"
39
40 #include <stdlib.h>
41 #include <stdio.h>
42 #include <string.h>
43 #ifdef HAVE_UNISTD_H
44 # include <unistd.h>
45 #endif
46 #include <errno.h>
47 #include <fcntl.h>
48 #ifdef HAVE_SYS_IOCTL_H
49 # include <sys/ioctl.h>
50 #endif
51 #ifdef HAVE_SYS_MMAN_H
52 # include <sys/mman.h>
53 #endif
54 #ifdef HAVE_SYS_POLL_H
55 # include <sys/poll.h>
56 #endif
57
58 #include "windef.h"
59 #include "wingdi.h"
60 #include "winerror.h"
61 #include "wine/winuser16.h"
62 #include "mmddk.h"
63 #include "dsound.h"
64 #include "dsdriver.h"
65 #include "oss.h"
66 #include "wine/debug.h"
67
68 WINE_DEFAULT_DEBUG_CHANNEL(wave);
69
70 /* Allow 1% deviation for sample rates (some ES137x cards) */
71 #define NEAR_MATCH(rate1,rate2) (((100*((int)(rate1)-(int)(rate2)))/(rate1))==0)
72
73 #ifdef HAVE_OSS
74
75 #define MAX_WAVEDRV     (3)
76
77 /* state diagram for waveOut writing:
78  *
79  * +---------+-------------+---------------+---------------------------------+
80  * |  state  |  function   |     event     |            new state            |
81  * +---------+-------------+---------------+---------------------------------+
82  * |         | open()      |               | STOPPED                         |
83  * | PAUSED  | write()     |               | PAUSED                          |
84  * | STOPPED | write()     | <thrd create> | PLAYING                         |
85  * | PLAYING | write()     | HEADER        | PLAYING                         |
86  * | (other) | write()     | <error>       |                                 |
87  * | (any)   | pause()     | PAUSING       | PAUSED                          |
88  * | PAUSED  | restart()   | RESTARTING    | PLAYING (if no thrd => STOPPED) |
89  * | (any)   | reset()     | RESETTING     | STOPPED                         |
90  * | (any)   | close()     | CLOSING       | CLOSED                          |
91  * +---------+-------------+---------------+---------------------------------+
92  */
93
94 /* states of the playing device */
95 #define WINE_WS_PLAYING         0
96 #define WINE_WS_PAUSED          1
97 #define WINE_WS_STOPPED         2
98 #define WINE_WS_CLOSED          3
99
100 /* events to be send to device */
101 enum win_wm_message {
102     WINE_WM_PAUSING = WM_USER + 1, WINE_WM_RESTARTING, WINE_WM_RESETTING, WINE_WM_HEADER,
103     WINE_WM_UPDATE, WINE_WM_BREAKLOOP, WINE_WM_CLOSING
104 };
105
106 #ifdef USE_PIPE_SYNC
107 #define SIGNAL_OMR(omr) do { int x = 0; write((omr)->msg_pipe[1], &x, sizeof(x)); } while (0)
108 #define CLEAR_OMR(omr) do { int x = 0; read((omr)->msg_pipe[0], &x, sizeof(x)); } while (0)
109 #define RESET_OMR(omr) do { } while (0)
110 #define WAIT_OMR(omr, sleep) \
111   do { struct pollfd pfd; pfd.fd = (omr)->msg_pipe[0]; \
112        pfd.events = POLLIN; poll(&pfd, 1, sleep); } while (0)
113 #else
114 #define SIGNAL_OMR(omr) do { SetEvent((omr)->msg_event); } while (0)
115 #define CLEAR_OMR(omr) do { } while (0)
116 #define RESET_OMR(omr) do { ResetEvent((omr)->msg_event); } while (0)
117 #define WAIT_OMR(omr, sleep) \
118   do { WaitForSingleObject((omr)->msg_event, sleep); } while (0)
119 #endif
120
121 typedef struct {
122     enum win_wm_message         msg;    /* message identifier */
123     DWORD                       param;  /* parameter for this message */
124     HANDLE                      hEvent; /* if message is synchronous, handle of event for synchro */
125 } OSS_MSG;
126
127 /* implement an in-process message ring for better performance
128  * (compared to passing thru the server)
129  * this ring will be used by the input (resp output) record (resp playback) routine
130  */
131 typedef struct {
132     /* FIXME: this could be made a dynamically growing array (if needed) */
133     /* maybe it's needed, a Humongous game manages to transmit 128 messages at once at startup */
134 #define OSS_RING_BUFFER_SIZE    192
135     OSS_MSG                     messages[OSS_RING_BUFFER_SIZE];
136     int                         msg_tosave;
137     int                         msg_toget;
138 #ifdef USE_PIPE_SYNC
139     int                         msg_pipe[2];
140 #else
141     HANDLE                      msg_event;
142 #endif
143     CRITICAL_SECTION            msg_crst;
144 } OSS_MSG_RING;
145
146 typedef struct tagOSS_DEVICE {
147     const char*                 dev_name;
148     const char*                 mixer_name;
149     unsigned                    open_count;
150     WAVEOUTCAPSA                out_caps;
151     WAVEINCAPSA                 in_caps;
152     unsigned                    open_access;
153     int                         fd;
154     DWORD                       owner_tid;
155     unsigned                    sample_rate;
156     unsigned                    stereo;
157     unsigned                    format;
158     unsigned                    audio_fragment;
159     BOOL                        full_duplex;
160     BOOL                        bTriggerSupport;
161 } OSS_DEVICE;
162
163 static OSS_DEVICE   OSS_Devices[MAX_WAVEDRV];
164
165 typedef struct {
166     OSS_DEVICE*                 ossdev;
167     volatile int                state;                  /* one of the WINE_WS_ manifest constants */
168     WAVEOPENDESC                waveDesc;
169     WORD                        wFlags;
170     PCMWAVEFORMAT               format;
171
172     /* OSS information */
173     DWORD                       dwFragmentSize;         /* size of OSS buffer fragment */
174     DWORD                       dwBufferSize;           /* size of whole OSS buffer in bytes */
175     LPWAVEHDR                   lpQueuePtr;             /* start of queued WAVEHDRs (waiting to be notified) */
176     LPWAVEHDR                   lpPlayPtr;              /* start of not yet fully played buffers */
177     DWORD                       dwPartialOffset;        /* Offset of not yet written bytes in lpPlayPtr */
178
179     LPWAVEHDR                   lpLoopPtr;              /* pointer of first buffer in loop, if any */
180     DWORD                       dwLoops;                /* private copy of loop counter */
181
182     DWORD                       dwPlayedTotal;          /* number of bytes actually played since opening */
183     DWORD                       dwWrittenTotal;         /* number of bytes written to OSS buffer since opening */
184     BOOL                        bNeedPost;              /* whether audio still needs to be physically started */
185
186     /* synchronization stuff */
187     HANDLE                      hStartUpEvent;
188     HANDLE                      hThread;
189     DWORD                       dwThreadID;
190     OSS_MSG_RING                msgRing;
191
192     /* DirectSound stuff */
193     LPBYTE                      mapping;
194     DWORD                       maplen;
195 } WINE_WAVEOUT;
196
197 typedef struct {
198     OSS_DEVICE*                 ossdev;
199     volatile int                state;
200     DWORD                       dwFragmentSize;         /* OpenSound '/dev/dsp' give us that size */
201     WAVEOPENDESC                waveDesc;
202     WORD                        wFlags;
203     PCMWAVEFORMAT               format;
204     LPWAVEHDR                   lpQueuePtr;
205     DWORD                       dwTotalRecorded;
206
207     /* synchronization stuff */
208     HANDLE                      hThread;
209     DWORD                       dwThreadID;
210     HANDLE                      hStartUpEvent;
211     OSS_MSG_RING                msgRing;
212 } WINE_WAVEIN;
213
214 static WINE_WAVEOUT     WOutDev   [MAX_WAVEDRV];
215 static WINE_WAVEIN      WInDev    [MAX_WAVEDRV];
216 static unsigned         numOutDev;
217 static unsigned         numInDev;
218
219 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
220
221 /* These strings used only for tracing */
222 static const char *wodPlayerCmdString[] = {
223     "WINE_WM_PAUSING",
224     "WINE_WM_RESTARTING",
225     "WINE_WM_RESETTING",
226     "WINE_WM_HEADER",
227     "WINE_WM_UPDATE",
228     "WINE_WM_BREAKLOOP",
229     "WINE_WM_CLOSING",
230 };
231
232 /*======================================================================*
233  *                  Low level WAVE implementation                       *
234  *======================================================================*/
235
236 /******************************************************************
237  *              OSS_RawOpenDevice
238  *
239  * Low level device opening (from values stored in ossdev)
240  */
241 static DWORD      OSS_RawOpenDevice(OSS_DEVICE* ossdev, int* frag)
242 {
243     int fd, val, err;
244
245     if ((fd = open(ossdev->dev_name, ossdev->open_access|O_NDELAY, 0)) == -1)
246     {
247         WARN("Couldn't open %s (%s)\n", ossdev->dev_name, strerror(errno));
248         return (errno == EBUSY) ? MMSYSERR_ALLOCATED : MMSYSERR_ERROR;
249     }
250     fcntl(fd, F_SETFD, 1); /* set close on exec flag */
251     /* turn full duplex on if it has been requested */
252     if (ossdev->open_access == O_RDWR && ossdev->full_duplex)
253         ioctl(fd, SNDCTL_DSP_SETDUPLEX, 0);
254
255     if (ossdev->audio_fragment)
256     {
257         ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &ossdev->audio_fragment);
258     }
259
260     /* First size and stereo then samplerate */
261     if (ossdev->format)
262     {
263         val = ossdev->format;
264         ioctl(fd, SNDCTL_DSP_SETFMT, &val);
265         if (val != ossdev->format) {
266             TRACE("Can't set format to %d (returned %d)\n", ossdev->format, val);
267             err=WAVERR_BADFORMAT;
268             goto error;
269         }
270     }
271     if (ossdev->stereo)
272     {
273         val = ossdev->stereo;
274         ioctl(fd, SNDCTL_DSP_STEREO, &val);
275         if (val != ossdev->stereo) {
276             TRACE("Can't set stereo to %u (returned %d)\n", ossdev->stereo, val);
277             err=WAVERR_BADFORMAT;
278             goto error;
279         }
280     }
281     if (ossdev->sample_rate)
282     {
283         val = ossdev->sample_rate;
284         ioctl(fd, SNDCTL_DSP_SPEED, &val);
285         if (!NEAR_MATCH(val, ossdev->sample_rate)) {
286             TRACE("Can't set sample_rate to %u (returned %d)\n", ossdev->sample_rate, val);
287             err=WAVERR_BADFORMAT;
288             goto error;
289         }
290     }
291     ossdev->fd = fd;
292     return MMSYSERR_NOERROR;
293
294 error:
295     close(fd);
296     return err;
297 }
298
299 /******************************************************************
300  *              OSS_OpenDevice
301  *
302  * since OSS has poor capabilities in full duplex, we try here to let a program
303  * open the device for both waveout and wavein streams...
304  * this is hackish, but it's the way OSS interface is done...
305  */
306 static DWORD    OSS_OpenDevice(OSS_DEVICE* ossdev, unsigned req_access,
307                                int* frag, int sample_rate, int stereo, int fmt)
308 {
309     DWORD       ret;
310
311     if (ossdev->full_duplex && (req_access == O_RDONLY || req_access == O_WRONLY))
312         req_access = O_RDWR;
313
314     /* FIXME: this should be protected, and it also contains a race with OSS_CloseDevice */
315     if (ossdev->open_count == 0)
316     {
317         if (access(ossdev->dev_name, 0) != 0) return MMSYSERR_NODRIVER;
318
319         ossdev->audio_fragment = (frag) ? *frag : 0;
320         ossdev->sample_rate = sample_rate;
321         ossdev->stereo = stereo;
322         ossdev->format = fmt;
323         ossdev->open_access = req_access;
324         ossdev->owner_tid = GetCurrentThreadId();
325
326         if ((ret = OSS_RawOpenDevice(ossdev, frag)) != MMSYSERR_NOERROR) return ret;
327     }
328     else
329     {
330         /* check we really open with the same parameters */
331         if (ossdev->open_access != req_access)
332         {
333             WARN("Mismatch in access...\n");
334             return WAVERR_BADFORMAT;
335         }
336         /* FIXME: if really needed, we could do, in this case, on the fly
337          * PCM conversion (using the MSACM ad hoc driver)
338          */
339         if (ossdev->audio_fragment != (frag ? *frag : 0) ||
340             ossdev->sample_rate != sample_rate ||
341             ossdev->stereo != stereo ||
342             ossdev->format != fmt)
343         {
344             WARN("FullDuplex: mismatch in PCM parameters for input and output\n"
345                  "OSS doesn't allow us different parameters\n"
346                  "audio_frag(%x/%x) sample_rate(%d/%d) stereo(%d/%d) fmt(%d/%d)\n",
347                  ossdev->audio_fragment, frag ? *frag : 0,
348                  ossdev->sample_rate, sample_rate,
349                  ossdev->stereo, stereo,
350                  ossdev->format, fmt);
351             return WAVERR_BADFORMAT;
352         }
353         if (GetCurrentThreadId() != ossdev->owner_tid)
354         {
355             WARN("Another thread is trying to access audio...\n");
356             return MMSYSERR_ERROR;
357         }
358     }
359
360     ossdev->open_count++;
361
362     return MMSYSERR_NOERROR;
363 }
364
365 /******************************************************************
366  *              OSS_CloseDevice
367  *
368  *
369  */
370 static void     OSS_CloseDevice(OSS_DEVICE* ossdev)
371 {
372     if (--ossdev->open_count == 0)
373     {
374        /* reset the device before we close it in case it is in a bad state */
375        ioctl(ossdev->fd, SNDCTL_DSP_RESET, 0);
376        close(ossdev->fd);
377     }
378 }
379
380 /******************************************************************
381  *              OSS_ResetDevice
382  *
383  * Resets the device. OSS Commercial requires the device to be closed
384  * after a SNDCTL_DSP_RESET ioctl call... this function implements
385  * this behavior...
386  */
387 static DWORD     OSS_ResetDevice(OSS_DEVICE* ossdev)
388 {
389     DWORD       ret;
390
391     if (ioctl(ossdev->fd, SNDCTL_DSP_RESET, NULL) == -1) 
392     {
393         perror("ioctl SNDCTL_DSP_RESET");
394         return -1;
395     }
396     TRACE("Changing fd from %d to ", ossdev->fd);
397     close(ossdev->fd);
398     ret = OSS_RawOpenDevice(ossdev, &ossdev->audio_fragment);
399     TRACE("%d\n", ossdev->fd);
400     return ret;
401 }
402
403 /******************************************************************
404  *              OSS_WaveOutInit
405  *
406  *
407  */
408 static BOOL     OSS_WaveOutInit(OSS_DEVICE* ossdev)
409 {
410     int                 smplrate;
411     int                 samplesize = 16;
412     int                 dsp_stereo = 1;
413     int                 bytespersmpl;
414     int                 caps;
415     int                 mask;
416
417     if (OSS_OpenDevice(ossdev, O_WRONLY, NULL, 0, 0, 0) != 0) return FALSE;
418
419     memset(&ossdev->out_caps, 0, sizeof(ossdev->out_caps));
420
421     ioctl(ossdev->fd, SNDCTL_DSP_RESET, 0);
422
423     /* FIXME: some programs compare this string against the content of the registry
424      * for MM drivers. The names have to match in order for the program to work
425      * (e.g. MS win9x mplayer.exe)
426      */
427 #ifdef EMULATE_SB16
428     ossdev->out_caps.wMid = 0x0002;
429     ossdev->out_caps.wPid = 0x0104;
430     strcpy(ossdev->out_caps.szPname, "SB16 Wave Out");
431 #else
432     ossdev->out_caps.wMid = 0x00FF;     /* Manufac ID */
433     ossdev->out_caps.wPid = 0x0001;     /* Product ID */
434     /*    strcpy(ossdev->out_caps.szPname, "OpenSoundSystem WAVOUT Driver");*/
435     strcpy(ossdev->out_caps.szPname, "CS4236/37/38");
436 #endif
437     ossdev->out_caps.vDriverVersion = 0x0100;
438     ossdev->out_caps.dwFormats = 0x00000000;
439     ossdev->out_caps.dwSupport = WAVECAPS_VOLUME;
440
441     ioctl(ossdev->fd, SNDCTL_DSP_GETFMTS, &mask);
442     TRACE("OSS dsp out mask=%08x\n", mask);
443
444     /* First bytespersampl, then stereo */
445     bytespersmpl = (ioctl(ossdev->fd, SNDCTL_DSP_SAMPLESIZE, &samplesize) != 0) ? 1 : 2;
446
447     ossdev->out_caps.wChannels = (ioctl(ossdev->fd, SNDCTL_DSP_STEREO, &dsp_stereo) != 0) ? 1 : 2;
448     if (ossdev->out_caps.wChannels > 1) ossdev->out_caps.dwSupport |= WAVECAPS_LRVOLUME;
449
450     smplrate = 44100;
451     if (ioctl(ossdev->fd, SNDCTL_DSP_SPEED, &smplrate) == 0) {
452         if (mask & AFMT_U8) {
453             ossdev->out_caps.dwFormats |= WAVE_FORMAT_4M08;
454             if (ossdev->out_caps.wChannels > 1)
455                 ossdev->out_caps.dwFormats |= WAVE_FORMAT_4S08;
456         }
457         if ((mask & AFMT_S16_LE) && bytespersmpl > 1) {
458             ossdev->out_caps.dwFormats |= WAVE_FORMAT_4M16;
459             if (ossdev->out_caps.wChannels > 1)
460                 ossdev->out_caps.dwFormats |= WAVE_FORMAT_4S16;
461         }
462     }
463     smplrate = 22050;
464     if (ioctl(ossdev->fd, SNDCTL_DSP_SPEED, &smplrate) == 0) {
465         if (mask & AFMT_U8) {
466             ossdev->out_caps.dwFormats |= WAVE_FORMAT_2M08;
467             if (ossdev->out_caps.wChannels > 1)
468                 ossdev->out_caps.dwFormats |= WAVE_FORMAT_2S08;
469         }
470         if ((mask & AFMT_S16_LE) && bytespersmpl > 1) {
471             ossdev->out_caps.dwFormats |= WAVE_FORMAT_2M16;
472             if (ossdev->out_caps.wChannels > 1)
473                 ossdev->out_caps.dwFormats |= WAVE_FORMAT_2S16;
474         }
475     }
476     smplrate = 11025;
477     if (ioctl(ossdev->fd, SNDCTL_DSP_SPEED, &smplrate) == 0) {
478         if (mask & AFMT_U8) {
479             ossdev->out_caps.dwFormats |= WAVE_FORMAT_1M08;
480             if (ossdev->out_caps.wChannels > 1)
481                 ossdev->out_caps.dwFormats |= WAVE_FORMAT_1S08;
482         }
483         if ((mask & AFMT_S16_LE) && bytespersmpl > 1) {
484             ossdev->out_caps.dwFormats |= WAVE_FORMAT_1M16;
485             if (ossdev->out_caps.wChannels > 1)
486                 ossdev->out_caps.dwFormats |= WAVE_FORMAT_1S16;
487         }
488     }
489     if (ioctl(ossdev->fd, SNDCTL_DSP_GETCAPS, &caps) == 0) {
490         TRACE("OSS dsp out caps=%08X\n", caps);
491         if ((caps & DSP_CAP_REALTIME) && !(caps & DSP_CAP_BATCH)) {
492             ossdev->out_caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
493         }
494         /* well, might as well use the DirectSound cap flag for something */
495         if ((caps & DSP_CAP_TRIGGER) && (caps & DSP_CAP_MMAP) &&
496             !(caps & DSP_CAP_BATCH))
497             ossdev->out_caps.dwSupport |= WAVECAPS_DIRECTSOUND;
498     }
499     OSS_CloseDevice(ossdev);
500     TRACE("out dwFormats = %08lX, dwSupport = %08lX\n",
501           ossdev->out_caps.dwFormats, ossdev->out_caps.dwSupport);
502     return TRUE;
503 }
504
505 /******************************************************************
506  *              OSS_WaveInInit
507  *
508  *
509  */
510 static BOOL OSS_WaveInInit(OSS_DEVICE* ossdev)
511 {
512     int                 smplrate;
513     int                 samplesize = 16;
514     int                 dsp_stereo = 1;
515     int                 bytespersmpl;
516     int                 caps;
517     int                 mask;
518
519     if (OSS_OpenDevice(ossdev, O_RDONLY, NULL, 0, 0, 0) != 0) return FALSE;
520
521     memset(&ossdev->in_caps, 0, sizeof(ossdev->in_caps));
522
523     ioctl(ossdev->fd, SNDCTL_DSP_RESET, 0);
524
525 #ifdef EMULATE_SB16
526     ossdev->in_caps.wMid = 0x0002;
527     ossdev->in_caps.wPid = 0x0004;
528     strcpy(ossdev->in_caps.szPname, "SB16 Wave In");
529 #else
530     ossdev->in_caps.wMid = 0x00FF;      /* Manufac ID */
531     ossdev->in_caps.wPid = 0x0001;      /* Product ID */
532     strcpy(ossdev->in_caps.szPname, "OpenSoundSystem WAVIN Driver");
533 #endif
534     ossdev->in_caps.dwFormats = 0x00000000;
535     ossdev->in_caps.wChannels = (ioctl(ossdev->fd, SNDCTL_DSP_STEREO, &dsp_stereo) != 0) ? 1 : 2;
536
537     ossdev->bTriggerSupport = FALSE;
538     if (ioctl(ossdev->fd, SNDCTL_DSP_GETCAPS, &caps) == 0) {
539         TRACE("OSS dsp in caps=%08X\n", caps);
540         if (caps & DSP_CAP_TRIGGER)
541             ossdev->bTriggerSupport = TRUE;
542     }
543
544     ioctl(ossdev->fd, SNDCTL_DSP_GETFMTS, &mask);
545     TRACE("OSS in dsp mask=%08x\n", mask);
546
547     bytespersmpl = (ioctl(ossdev->fd, SNDCTL_DSP_SAMPLESIZE, &samplesize) != 0) ? 1 : 2;
548     smplrate = 44100;
549     if (ioctl(ossdev->fd, SNDCTL_DSP_SPEED, &smplrate) == 0) {
550         if (mask & AFMT_U8) {
551             ossdev->in_caps.dwFormats |= WAVE_FORMAT_4M08;
552             if (ossdev->in_caps.wChannels > 1)
553                 ossdev->in_caps.dwFormats |= WAVE_FORMAT_4S08;
554         }
555         if ((mask & AFMT_S16_LE) && bytespersmpl > 1) {
556             ossdev->in_caps.dwFormats |= WAVE_FORMAT_4M16;
557             if (ossdev->in_caps.wChannels > 1)
558                 ossdev->in_caps.dwFormats |= WAVE_FORMAT_4S16;
559         }
560     }
561     smplrate = 22050;
562     if (ioctl(ossdev->fd, SNDCTL_DSP_SPEED, &smplrate) == 0) {
563         if (mask & AFMT_U8) {
564             ossdev->in_caps.dwFormats |= WAVE_FORMAT_2M08;
565             if (ossdev->in_caps.wChannels > 1)
566                 ossdev->in_caps.dwFormats |= WAVE_FORMAT_2S08;
567         }
568         if ((mask & AFMT_S16_LE) && bytespersmpl > 1) {
569             ossdev->in_caps.dwFormats |= WAVE_FORMAT_2M16;
570             if (ossdev->in_caps.wChannels > 1)
571                 ossdev->in_caps.dwFormats |= WAVE_FORMAT_2S16;
572         }
573     }
574     smplrate = 11025;
575     if (ioctl(ossdev->fd, SNDCTL_DSP_SPEED, &smplrate) == 0) {
576         if (mask & AFMT_U8) {
577             ossdev->in_caps.dwFormats |= WAVE_FORMAT_1M08;
578             if (ossdev->in_caps.wChannels > 1)
579                 ossdev->in_caps.dwFormats |= WAVE_FORMAT_1S08;
580         }
581         if ((mask & AFMT_S16_LE) && bytespersmpl > 1) {
582             ossdev->in_caps.dwFormats |= WAVE_FORMAT_1M16;
583             if (ossdev->in_caps.wChannels > 1)
584                 ossdev->in_caps.dwFormats |= WAVE_FORMAT_1S16;
585         }
586     }
587     OSS_CloseDevice(ossdev);
588     TRACE("in dwFormats = %08lX\n", ossdev->in_caps.dwFormats);
589     return TRUE;
590 }
591
592 /******************************************************************
593  *              OSS_WaveFullDuplexInit
594  *
595  *
596  */
597 static void OSS_WaveFullDuplexInit(OSS_DEVICE* ossdev)
598 {
599     int         caps;
600
601     if (OSS_OpenDevice(ossdev, O_RDWR, NULL, 0, 0, 0) != 0) return;
602     if (ioctl(ossdev->fd, SNDCTL_DSP_GETCAPS, &caps) == 0)
603     {
604         ossdev->full_duplex = (caps & DSP_CAP_DUPLEX);
605     }
606     OSS_CloseDevice(ossdev);
607 }
608
609 /******************************************************************
610  *              OSS_WaveInit
611  *
612  * Initialize internal structures from OSS information
613  */
614 LONG OSS_WaveInit(void)
615 {
616     int         i;
617
618     /* FIXME: only one device is supported */
619     memset(&OSS_Devices, 0, sizeof(OSS_Devices));
620     /* FIXME: should check that dsp actually points to dsp0, or that dsp0 exists
621      * we should also be able to configure (bitmap) which devices we want to use...
622      * - or even store the name of all drivers in our configuration
623      */
624     OSS_Devices[0].dev_name   = "/dev/dsp";
625     OSS_Devices[0].mixer_name = "/dev/mixer";
626     OSS_Devices[1].dev_name   = "/dev/dsp1";
627     OSS_Devices[1].mixer_name = "/dev/mixer1";
628     OSS_Devices[2].dev_name   = "/dev/dsp2";
629     OSS_Devices[2].mixer_name = "/dev/mixer2";
630
631     /* start with output device */
632     for (i = 0; i < MAX_WAVEDRV; ++i)
633     {
634         if (OSS_WaveOutInit(&OSS_Devices[i]))
635         {
636             WOutDev[numOutDev].state = WINE_WS_CLOSED;
637             WOutDev[numOutDev].ossdev = &OSS_Devices[i];
638             numOutDev++;
639         }
640     }
641
642     /* then do input device */
643     for (i = 0; i < MAX_WAVEDRV; ++i)
644     {
645         if (OSS_WaveInInit(&OSS_Devices[i]))
646         {
647             WInDev[numInDev].state = WINE_WS_CLOSED;
648             WInDev[numInDev].ossdev = &OSS_Devices[i];
649             numInDev++;
650         }
651     }
652
653     /* finish with the full duplex bits */
654     for (i = 0; i < MAX_WAVEDRV; i++)
655         OSS_WaveFullDuplexInit(&OSS_Devices[i]);
656
657     return 0;
658 }
659
660 /******************************************************************
661  *              OSS_InitRingMessage
662  *
663  * Initialize the ring of messages for passing between driver's caller and playback/record
664  * thread
665  */
666 static int OSS_InitRingMessage(OSS_MSG_RING* omr)
667 {
668     omr->msg_toget = 0;
669     omr->msg_tosave = 0;
670 #ifdef USE_PIPE_SYNC
671     if (pipe(omr->msg_pipe) < 0) {
672         omr->msg_pipe[0] = -1;
673         omr->msg_pipe[1] = -1;
674         ERR("could not create pipe, error=%s\n", strerror(errno));
675     }
676 #else
677     omr->msg_event = CreateEventA(NULL, FALSE, FALSE, NULL);
678 #endif
679     memset(omr->messages, 0, sizeof(OSS_MSG) * OSS_RING_BUFFER_SIZE);
680     InitializeCriticalSection(&omr->msg_crst);
681     return 0;
682 }
683
684 /******************************************************************
685  *              OSS_DestroyRingMessage
686  *
687  */
688 static int OSS_DestroyRingMessage(OSS_MSG_RING* omr)
689 {
690 #ifdef USE_PIPE_SYNC
691     close(omr->msg_pipe[0]);
692     close(omr->msg_pipe[1]);
693 #else
694     CloseHandle(omr->msg_event);
695 #endif
696     DeleteCriticalSection(&omr->msg_crst);
697     return 0;
698 }
699
700 /******************************************************************
701  *              OSS_AddRingMessage
702  *
703  * Inserts a new message into the ring (should be called from DriverProc derivated routines)
704  */
705 static int OSS_AddRingMessage(OSS_MSG_RING* omr, enum win_wm_message msg, DWORD param, BOOL wait)
706 {
707     HANDLE      hEvent = INVALID_HANDLE_VALUE;
708
709     EnterCriticalSection(&omr->msg_crst);
710     if ((omr->msg_toget == ((omr->msg_tosave + 1) % OSS_RING_BUFFER_SIZE))) /* buffer overflow ? */
711     {
712         ERR("buffer overflow !?\n");
713         LeaveCriticalSection(&omr->msg_crst);
714         return 0;
715     }
716     if (wait)
717     {
718         hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
719         if (hEvent == INVALID_HANDLE_VALUE)
720         {
721             ERR("can't create event !?\n");
722             LeaveCriticalSection(&omr->msg_crst);
723             return 0;
724         }
725         if (omr->msg_toget != omr->msg_tosave && omr->messages[omr->msg_toget].msg != WINE_WM_HEADER)
726             FIXME("two fast messages in the queue!!!!\n");
727
728         /* fast messages have to be added at the start of the queue */
729         omr->msg_toget = (omr->msg_toget + OSS_RING_BUFFER_SIZE - 1) % OSS_RING_BUFFER_SIZE;
730
731         omr->messages[omr->msg_toget].msg = msg;
732         omr->messages[omr->msg_toget].param = param;
733         omr->messages[omr->msg_toget].hEvent = hEvent;
734     }
735     else
736     {
737         omr->messages[omr->msg_tosave].msg = msg;
738         omr->messages[omr->msg_tosave].param = param;
739         omr->messages[omr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
740         omr->msg_tosave = (omr->msg_tosave + 1) % OSS_RING_BUFFER_SIZE;
741     }
742     LeaveCriticalSection(&omr->msg_crst);
743     /* signal a new message */
744     SIGNAL_OMR(omr);
745     if (wait)
746     {
747         /* wait for playback/record thread to have processed the message */
748         WaitForSingleObject(hEvent, INFINITE);
749         CloseHandle(hEvent);
750     }
751     return 1;
752 }
753
754 /******************************************************************
755  *              OSS_RetrieveRingMessage
756  *
757  * Get a message from the ring. Should be called by the playback/record thread.
758  */
759 static int OSS_RetrieveRingMessage(OSS_MSG_RING* omr,
760                                    enum win_wm_message *msg, DWORD *param, HANDLE *hEvent)
761 {
762     EnterCriticalSection(&omr->msg_crst);
763
764     if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
765     {
766         LeaveCriticalSection(&omr->msg_crst);
767         return 0;
768     }
769
770     *msg = omr->messages[omr->msg_toget].msg;
771     omr->messages[omr->msg_toget].msg = 0;
772     *param = omr->messages[omr->msg_toget].param;
773     *hEvent = omr->messages[omr->msg_toget].hEvent;
774     omr->msg_toget = (omr->msg_toget + 1) % OSS_RING_BUFFER_SIZE;
775     CLEAR_OMR(omr);
776     LeaveCriticalSection(&omr->msg_crst);
777     return 1;
778 }
779
780 /*======================================================================*
781  *                  Low level WAVE OUT implementation                   *
782  *======================================================================*/
783
784 /**************************************************************************
785  *                      wodNotifyClient                 [internal]
786  */
787 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
788 {
789     TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
790
791     switch (wMsg) {
792     case WOM_OPEN:
793     case WOM_CLOSE:
794     case WOM_DONE:
795         if (wwo->wFlags != DCB_NULL &&
796             !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
797                             (HDRVR)wwo->waveDesc.hWave, wMsg,
798                             wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
799             WARN("can't notify client !\n");
800             return MMSYSERR_ERROR;
801         }
802         break;
803     default:
804         FIXME("Unknown callback message %u\n", wMsg);
805         return MMSYSERR_INVALPARAM;
806     }
807     return MMSYSERR_NOERROR;
808 }
809
810 /**************************************************************************
811  *                              wodUpdatePlayedTotal    [internal]
812  *
813  */
814 static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo, audio_buf_info* info)
815 {
816     audio_buf_info dspspace;
817     if (!info) info = &dspspace;
818
819     if (ioctl(wwo->ossdev->fd, SNDCTL_DSP_GETOSPACE, info) < 0) {
820         ERR("ioctl can't 'SNDCTL_DSP_GETOSPACE' !\n");
821         return FALSE;
822     }
823     wwo->dwPlayedTotal = wwo->dwWrittenTotal - (wwo->dwBufferSize - info->bytes);
824     return TRUE;
825 }
826
827 /**************************************************************************
828  *                              wodPlayer_BeginWaveHdr          [internal]
829  *
830  * Makes the specified lpWaveHdr the currently playing wave header.
831  * If the specified wave header is a begin loop and we're not already in
832  * a loop, setup the loop.
833  */
834 static void wodPlayer_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
835 {
836     wwo->lpPlayPtr = lpWaveHdr;
837
838     if (!lpWaveHdr) return;
839
840     if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
841         if (wwo->lpLoopPtr) {
842             WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
843         } else {
844             TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
845             wwo->lpLoopPtr = lpWaveHdr;
846             /* Windows does not touch WAVEHDR.dwLoops,
847              * so we need to make an internal copy */
848             wwo->dwLoops = lpWaveHdr->dwLoops;
849         }
850     }
851     wwo->dwPartialOffset = 0;
852 }
853
854 /**************************************************************************
855  *                              wodPlayer_PlayPtrNext           [internal]
856  *
857  * Advance the play pointer to the next waveheader, looping if required.
858  */
859 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEOUT* wwo)
860 {
861     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
862
863     wwo->dwPartialOffset = 0;
864     if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
865         /* We're at the end of a loop, loop if required */
866         if (--wwo->dwLoops > 0) {
867             wwo->lpPlayPtr = wwo->lpLoopPtr;
868         } else {
869             /* Handle overlapping loops correctly */
870             if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
871                 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
872                 /* shall we consider the END flag for the closing loop or for
873                  * the opening one or for both ???
874                  * code assumes for closing loop only
875                  */
876             } else {
877                 lpWaveHdr = lpWaveHdr->lpNext;
878             }
879             wwo->lpLoopPtr = NULL;
880             wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
881         }
882     } else {
883         /* We're not in a loop.  Advance to the next wave header */
884         wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
885     }
886
887     return lpWaveHdr;
888 }
889
890 /**************************************************************************
891  *                           wodPlayer_DSPWait                  [internal]
892  * Returns the number of milliseconds to wait for the DSP buffer to write
893  * one fragment.
894  */
895 static DWORD wodPlayer_DSPWait(const WINE_WAVEOUT *wwo)
896 {
897     /* time for one fragment to be played */
898     return wwo->dwFragmentSize * 1000 / wwo->format.wf.nAvgBytesPerSec;
899 }
900
901 /**************************************************************************
902  *                           wodPlayer_NotifyWait               [internal]
903  * Returns the number of milliseconds to wait before attempting to notify
904  * completion of the specified wavehdr.
905  * This is based on the number of bytes remaining to be written in the
906  * wave.
907  */
908 static DWORD wodPlayer_NotifyWait(const WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
909 {
910     DWORD dwMillis;
911
912     if (lpWaveHdr->reserved < wwo->dwPlayedTotal) {
913         dwMillis = 1;
914     } else {
915         dwMillis = (lpWaveHdr->reserved - wwo->dwPlayedTotal) * 1000 / wwo->format.wf.nAvgBytesPerSec;
916         if (!dwMillis) dwMillis = 1;
917     }
918
919     return dwMillis;
920 }
921
922
923 /**************************************************************************
924  *                           wodPlayer_WriteMaxFrags            [internal]
925  * Writes the maximum number of bytes possible to the DSP and returns
926  * TRUE iff the current playPtr has been fully played
927  */
928 static BOOL wodPlayer_WriteMaxFrags(WINE_WAVEOUT* wwo, DWORD* bytes)
929 {
930     DWORD       dwLength = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
931     DWORD       toWrite = min(dwLength, *bytes);
932     int         written;
933     BOOL        ret = FALSE;
934
935     TRACE("Writing wavehdr %p.%lu[%lu]/%lu\n",
936           wwo->lpPlayPtr, wwo->dwPartialOffset, wwo->lpPlayPtr->dwBufferLength, toWrite);
937
938     if (toWrite > 0)
939     {
940         written = write(wwo->ossdev->fd, wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toWrite);
941         if (written <= 0) return FALSE;
942     }
943     else
944         written = 0;
945
946     if (written >= dwLength) {
947         /* If we wrote all current wavehdr, skip to the next one */
948         wodPlayer_PlayPtrNext(wwo);
949         ret = TRUE;
950     } else {
951         /* Remove the amount written */
952         wwo->dwPartialOffset += written;
953     }
954     *bytes -= written;
955     wwo->dwWrittenTotal += written;
956
957     return ret;
958 }
959
960
961 /**************************************************************************
962  *                              wodPlayer_NotifyCompletions     [internal]
963  *
964  * Notifies and remove from queue all wavehdrs which have been played to
965  * the speaker (ie. they have cleared the OSS buffer).  If force is true,
966  * we notify all wavehdrs and remove them all from the queue even if they
967  * are unplayed or part of a loop.
968  */
969 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
970 {
971     LPWAVEHDR           lpWaveHdr;
972
973     /* Start from lpQueuePtr and keep notifying until:
974      * - we hit an unwritten wavehdr
975      * - we hit the beginning of a running loop
976      * - we hit a wavehdr which hasn't finished playing
977      */
978     while ((lpWaveHdr = wwo->lpQueuePtr) &&
979            (force ||
980             (lpWaveHdr != wwo->lpPlayPtr &&
981              lpWaveHdr != wwo->lpLoopPtr &&
982              lpWaveHdr->reserved <= wwo->dwPlayedTotal))) {
983
984         wwo->lpQueuePtr = lpWaveHdr->lpNext;
985
986         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
987         lpWaveHdr->dwFlags |= WHDR_DONE;
988
989         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
990     }
991     return  (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
992         wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
993 }
994
995 /**************************************************************************
996  *                              wodPlayer_Reset                 [internal]
997  *
998  * wodPlayer helper. Resets current output stream.
999  */
1000 static  void    wodPlayer_Reset(WINE_WAVEOUT* wwo, BOOL reset)
1001 {
1002     wodUpdatePlayedTotal(wwo, NULL);
1003     /* updates current notify list */
1004     wodPlayer_NotifyCompletions(wwo, FALSE);
1005
1006     /* flush all possible output */
1007     if (OSS_ResetDevice(wwo->ossdev) != MMSYSERR_NOERROR)
1008     {
1009         wwo->hThread = 0;
1010         wwo->state = WINE_WS_STOPPED;
1011         ExitThread(-1);
1012     }
1013
1014     if (reset) {
1015         enum win_wm_message     msg;
1016         DWORD                   param;
1017         HANDLE                  ev;
1018
1019         /* remove any buffer */
1020         wodPlayer_NotifyCompletions(wwo, TRUE);
1021
1022         wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1023         wwo->state = WINE_WS_STOPPED;
1024         wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1025         /* Clear partial wavehdr */
1026         wwo->dwPartialOffset = 0;
1027
1028         /* remove any existing message in the ring */
1029         EnterCriticalSection(&wwo->msgRing.msg_crst);
1030         /* return all pending headers in queue */
1031         while (OSS_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
1032         {
1033             if (msg != WINE_WM_HEADER)
1034             {
1035                 FIXME("shouldn't have headers left\n");
1036                 SetEvent(ev);
1037                 continue;
1038             }
1039             ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
1040             ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
1041
1042             wodNotifyClient(wwo, WOM_DONE, param, 0);
1043         }
1044         RESET_OMR(&wwo->msgRing);
1045         LeaveCriticalSection(&wwo->msgRing.msg_crst);
1046     } else {
1047         if (wwo->lpLoopPtr) {
1048             /* complicated case, not handled yet (could imply modifying the loop counter */
1049             FIXME("Pausing while in loop isn't correctly handled yet, except strange results\n");
1050             wwo->lpPlayPtr = wwo->lpLoopPtr;
1051             wwo->dwPartialOffset = 0;
1052             wwo->dwWrittenTotal = wwo->dwPlayedTotal; /* this is wrong !!! */
1053         } else {
1054             LPWAVEHDR   ptr;
1055             DWORD       sz = wwo->dwPartialOffset;
1056
1057             /* reset all the data as if we had written only up to lpPlayedTotal bytes */
1058             /* compute the max size playable from lpQueuePtr */
1059             for (ptr = wwo->lpQueuePtr; ptr != wwo->lpPlayPtr; ptr = ptr->lpNext) {
1060                 sz += ptr->dwBufferLength;
1061             }
1062             /* because the reset lpPlayPtr will be lpQueuePtr */
1063             if (wwo->dwWrittenTotal > wwo->dwPlayedTotal + sz) ERR("grin\n");
1064             wwo->dwPartialOffset = sz - (wwo->dwWrittenTotal - wwo->dwPlayedTotal);
1065             wwo->dwWrittenTotal = wwo->dwPlayedTotal;
1066             wwo->lpPlayPtr = wwo->lpQueuePtr;
1067         }
1068         wwo->state = WINE_WS_PAUSED;
1069     }
1070 }
1071
1072 /**************************************************************************
1073  *                    wodPlayer_ProcessMessages                 [internal]
1074  */
1075 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
1076 {
1077     LPWAVEHDR           lpWaveHdr;
1078     enum win_wm_message msg;
1079     DWORD               param;
1080     HANDLE              ev;
1081
1082     while (OSS_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
1083         TRACE("Received %s %lx\n", wodPlayerCmdString[msg - WM_USER - 1], param);
1084         switch (msg) {
1085         case WINE_WM_PAUSING:
1086             wodPlayer_Reset(wwo, FALSE);
1087             SetEvent(ev);
1088             break;
1089         case WINE_WM_RESTARTING:
1090             if (wwo->state == WINE_WS_PAUSED)
1091             {
1092                 wwo->state = WINE_WS_PLAYING;
1093             }
1094             SetEvent(ev);
1095             break;
1096         case WINE_WM_HEADER:
1097             lpWaveHdr = (LPWAVEHDR)param;
1098
1099             /* insert buffer at the end of queue */
1100             {
1101                 LPWAVEHDR*      wh;
1102                 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1103                 *wh = lpWaveHdr;
1104             }
1105             if (!wwo->lpPlayPtr)
1106                 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
1107             if (wwo->state == WINE_WS_STOPPED)
1108                 wwo->state = WINE_WS_PLAYING;
1109             break;
1110         case WINE_WM_RESETTING:
1111             wodPlayer_Reset(wwo, TRUE);
1112             SetEvent(ev);
1113             break;
1114         case WINE_WM_UPDATE:
1115             wodUpdatePlayedTotal(wwo, NULL);
1116             SetEvent(ev);
1117             break;
1118         case WINE_WM_BREAKLOOP:
1119             if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
1120                 /* ensure exit at end of current loop */
1121                 wwo->dwLoops = 1;
1122             }
1123             SetEvent(ev);
1124             break;
1125         case WINE_WM_CLOSING:
1126             /* sanity check: this should not happen since the device must have been reset before */
1127             if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1128             wwo->hThread = 0;
1129             wwo->state = WINE_WS_CLOSED;
1130             SetEvent(ev);
1131             ExitThread(0);
1132             /* shouldn't go here */
1133         default:
1134             FIXME("unknown message %d\n", msg);
1135             break;
1136         }
1137     }
1138 }
1139
1140 /**************************************************************************
1141  *                           wodPlayer_FeedDSP                  [internal]
1142  * Feed as much sound data as we can into the DSP and return the number of
1143  * milliseconds before it will be necessary to feed the DSP again.
1144  */
1145 static DWORD wodPlayer_FeedDSP(WINE_WAVEOUT* wwo)
1146 {
1147     audio_buf_info dspspace;
1148     DWORD       availInQ;
1149
1150     wodUpdatePlayedTotal(wwo, &dspspace);
1151     availInQ = dspspace.bytes;
1152     TRACE("fragments=%d/%d, fragsize=%d, bytes=%d\n",
1153           dspspace.fragments, dspspace.fragstotal, dspspace.fragsize, dspspace.bytes);
1154
1155     /* input queue empty and output buffer with less than one fragment to play */
1156     if (!wwo->lpPlayPtr && wwo->dwBufferSize < availInQ + wwo->dwFragmentSize) {
1157         TRACE("Run out of wavehdr:s...\n");
1158         return INFINITE;
1159     }
1160
1161     /* no more room... no need to try to feed */
1162     if (dspspace.fragments != 0) {
1163         /* Feed from partial wavehdr */
1164         if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0) {
1165             wodPlayer_WriteMaxFrags(wwo, &availInQ);
1166         }
1167
1168         /* Feed wavehdrs until we run out of wavehdrs or DSP space */
1169         if (wwo->dwPartialOffset == 0 && wwo->lpPlayPtr) {
1170             do {
1171                 TRACE("Setting time to elapse for %p to %lu\n",
1172                       wwo->lpPlayPtr, wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength);
1173                 /* note the value that dwPlayedTotal will return when this wave finishes playing */
1174                 wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
1175             } while (wodPlayer_WriteMaxFrags(wwo, &availInQ) && wwo->lpPlayPtr && availInQ > 0);
1176         }
1177
1178         if (wwo->bNeedPost) {
1179             /* OSS doesn't start before it gets either 2 fragments or a SNDCTL_DSP_POST;
1180              * if it didn't get one, we give it the other */
1181             if (wwo->dwBufferSize < availInQ + 2 * wwo->dwFragmentSize)
1182                 ioctl(wwo->ossdev->fd, SNDCTL_DSP_POST, 0);
1183             wwo->bNeedPost = FALSE;
1184         }
1185     }
1186
1187     return wodPlayer_DSPWait(wwo);
1188 }
1189
1190
1191 /**************************************************************************
1192  *                              wodPlayer                       [internal]
1193  */
1194 static  DWORD   CALLBACK        wodPlayer(LPVOID pmt)
1195 {
1196     WORD          uDevID = (DWORD)pmt;
1197     WINE_WAVEOUT* wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
1198     DWORD         dwNextFeedTime = INFINITE;   /* Time before DSP needs feeding */
1199     DWORD         dwNextNotifyTime = INFINITE; /* Time before next wave completion */
1200     DWORD         dwSleepTime;
1201
1202     wwo->state = WINE_WS_STOPPED;
1203     SetEvent(wwo->hStartUpEvent);
1204
1205     for (;;) {
1206         /** Wait for the shortest time before an action is required.  If there
1207          *  are no pending actions, wait forever for a command.
1208          */
1209         dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
1210         TRACE("waiting %lums (%lu,%lu)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
1211         WAIT_OMR(&wwo->msgRing, dwSleepTime);
1212         wodPlayer_ProcessMessages(wwo);
1213         if (wwo->state == WINE_WS_PLAYING) {
1214             dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1215             dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1216             if (dwNextFeedTime == INFINITE) {
1217                 /* FeedDSP ran out of data, but before flushing, */
1218                 /* check that a notification didn't give us more */
1219                 wodPlayer_ProcessMessages(wwo);
1220                 if (!wwo->lpPlayPtr) {
1221                     TRACE("flushing\n");
1222                     ioctl(wwo->ossdev->fd, SNDCTL_DSP_SYNC, 0);
1223                     wwo->dwPlayedTotal = wwo->dwWrittenTotal;
1224                 }
1225                 else {
1226                     TRACE("recovering\n");
1227                     dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1228                 }
1229             }
1230         } else {
1231             dwNextFeedTime = dwNextNotifyTime = INFINITE;
1232         }
1233     }
1234 }
1235
1236 /**************************************************************************
1237  *                      wodGetDevCaps                           [internal]
1238  */
1239 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSA lpCaps, DWORD dwSize)
1240 {
1241     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1242
1243     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1244
1245     if (wDevID >= numOutDev) {
1246         TRACE("numOutDev reached !\n");
1247         return MMSYSERR_BADDEVICEID;
1248     }
1249
1250     memcpy(lpCaps, &WOutDev[wDevID].ossdev->out_caps, min(dwSize, sizeof(*lpCaps)));
1251     return MMSYSERR_NOERROR;
1252 }
1253
1254 /**************************************************************************
1255  *                              wodOpen                         [internal]
1256  */
1257 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1258 {
1259     int                 audio_fragment;
1260     WINE_WAVEOUT*       wwo;
1261     audio_buf_info      info;
1262     DWORD               ret;
1263
1264     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
1265     if (lpDesc == NULL) {
1266         WARN("Invalid Parameter !\n");
1267         return MMSYSERR_INVALPARAM;
1268     }
1269     if (wDevID >= numOutDev) {
1270         TRACE("MAX_WAVOUTDRV reached !\n");
1271         return MMSYSERR_BADDEVICEID;
1272     }
1273
1274     /* only PCM format is supported so far... */
1275     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1276         lpDesc->lpFormat->nChannels == 0 ||
1277         lpDesc->lpFormat->nSamplesPerSec == 0) {
1278         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1279              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1280              lpDesc->lpFormat->nSamplesPerSec);
1281         return WAVERR_BADFORMAT;
1282     }
1283
1284     if (dwFlags & WAVE_FORMAT_QUERY) {
1285         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1286              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1287              lpDesc->lpFormat->nSamplesPerSec);
1288         return MMSYSERR_NOERROR;
1289     }
1290
1291     wwo = &WOutDev[wDevID];
1292
1293     if ((dwFlags & WAVE_DIRECTSOUND) && 
1294         !(wwo->ossdev->out_caps.dwSupport & WAVECAPS_DIRECTSOUND))
1295         /* not supported, ignore it */
1296         dwFlags &= ~WAVE_DIRECTSOUND;
1297
1298     if (dwFlags & WAVE_DIRECTSOUND) {
1299         if (wwo->ossdev->out_caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
1300             /* we have realtime DirectSound, fragments just waste our time,
1301              * but a large buffer is good, so choose 64KB (32 * 2^11) */
1302             audio_fragment = 0x0020000B;
1303         else
1304             /* to approximate realtime, we must use small fragments,
1305              * let's try to fragment the above 64KB (256 * 2^8) */
1306             audio_fragment = 0x01000008;
1307     } else {
1308         /* shockwave player uses only 4 1k-fragments at a rate of 22050 bytes/sec
1309          * thus leading to 46ms per fragment, and a turnaround time of 185ms
1310          */
1311         /* 16 fragments max, 2^10=1024 bytes per fragment */
1312         audio_fragment = 0x000F000A;
1313     }
1314     if (wwo->state != WINE_WS_CLOSED) return MMSYSERR_ALLOCATED;
1315     /* we want to be able to mmap() the device, which means it must be opened readable,
1316      * otherwise mmap() will fail (at least under Linux) */
1317     ret = OSS_OpenDevice(wwo->ossdev,
1318                          (dwFlags & WAVE_DIRECTSOUND) ? O_RDWR : O_WRONLY,
1319                          &audio_fragment, lpDesc->lpFormat->nSamplesPerSec,
1320                          (lpDesc->lpFormat->nChannels > 1) ? 1 : 0,
1321                          (lpDesc->lpFormat->wBitsPerSample == 16)
1322                              ? AFMT_S16_LE : AFMT_U8);
1323     if (ret != 0) return ret;
1324     wwo->state = WINE_WS_STOPPED;
1325
1326     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1327
1328     memcpy(&wwo->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
1329     memcpy(&wwo->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1330
1331     if (wwo->format.wBitsPerSample == 0) {
1332         WARN("Resetting zeroed wBitsPerSample\n");
1333         wwo->format.wBitsPerSample = 8 *
1334             (wwo->format.wf.nAvgBytesPerSec /
1335              wwo->format.wf.nSamplesPerSec) /
1336             wwo->format.wf.nChannels;
1337     }
1338     /* Read output space info for future reference */
1339     if (ioctl(wwo->ossdev->fd, SNDCTL_DSP_GETOSPACE, &info) < 0) {
1340         ERR("ioctl can't 'SNDCTL_DSP_GETOSPACE' !\n");
1341         OSS_CloseDevice(wwo->ossdev);
1342         wwo->state = WINE_WS_CLOSED;
1343         return MMSYSERR_NOTENABLED;
1344     }
1345
1346     /* Check that fragsize is correct per our settings above */
1347     if ((info.fragsize > 1024) && (LOWORD(audio_fragment) <= 10)) {
1348         /* we've tried to set 1K fragments or less, but it didn't work */
1349         ERR("fragment size set failed, size is now %d\n", info.fragsize);
1350         MESSAGE("Your Open Sound System driver did not let us configure small enough sound fragments.\n");
1351         MESSAGE("This may cause delays and other problems in audio playback with certain applications.\n");
1352     }
1353
1354     /* Remember fragsize and total buffer size for future use */
1355     wwo->dwFragmentSize = info.fragsize;
1356     wwo->dwBufferSize = info.fragstotal * info.fragsize;
1357     wwo->dwPlayedTotal = 0;
1358     wwo->dwWrittenTotal = 0;
1359     wwo->bNeedPost = TRUE;
1360
1361     OSS_InitRingMessage(&wwo->msgRing);
1362
1363     if (!(dwFlags & WAVE_DIRECTSOUND)) {
1364         wwo->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
1365         wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
1366         WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
1367         CloseHandle(wwo->hStartUpEvent);
1368     } else {
1369         wwo->hThread = INVALID_HANDLE_VALUE;
1370         wwo->dwThreadID = 0;
1371     }
1372     wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
1373
1374     TRACE("fd=%d fragmentSize=%ld\n",
1375           wwo->ossdev->fd, wwo->dwFragmentSize);
1376     if (wwo->dwFragmentSize % wwo->format.wf.nBlockAlign)
1377         ERR("Fragment doesn't contain an integral number of data blocks\n");
1378
1379     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
1380           wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec,
1381           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
1382           wwo->format.wf.nBlockAlign);
1383
1384     return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
1385 }
1386
1387 /**************************************************************************
1388  *                              wodClose                        [internal]
1389  */
1390 static DWORD wodClose(WORD wDevID)
1391 {
1392     DWORD               ret = MMSYSERR_NOERROR;
1393     WINE_WAVEOUT*       wwo;
1394
1395     TRACE("(%u);\n", wDevID);
1396
1397     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
1398         WARN("bad device ID !\n");
1399         return MMSYSERR_BADDEVICEID;
1400     }
1401
1402     wwo = &WOutDev[wDevID];
1403     if (wwo->lpQueuePtr) {
1404         WARN("buffers still playing !\n");
1405         ret = WAVERR_STILLPLAYING;
1406     } else {
1407         if (wwo->hThread != INVALID_HANDLE_VALUE) {
1408             OSS_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1409         }
1410         if (wwo->mapping) {
1411             munmap(wwo->mapping, wwo->maplen);
1412             wwo->mapping = NULL;
1413         }
1414
1415         OSS_DestroyRingMessage(&wwo->msgRing);
1416
1417         OSS_CloseDevice(wwo->ossdev);
1418         wwo->state = WINE_WS_CLOSED;
1419         wwo->dwFragmentSize = 0;
1420         ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1421     }
1422     return ret;
1423 }
1424
1425 /**************************************************************************
1426  *                              wodWrite                        [internal]
1427  *
1428  */
1429 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1430 {
1431     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1432
1433     /* first, do the sanity checks... */
1434     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
1435         WARN("bad dev ID !\n");
1436         return MMSYSERR_BADDEVICEID;
1437     }
1438
1439     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1440         return WAVERR_UNPREPARED;
1441
1442     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1443         return WAVERR_STILLPLAYING;
1444
1445     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1446     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1447     lpWaveHdr->lpNext = 0;
1448
1449     if ((lpWaveHdr->dwBufferLength & ~(WOutDev[wDevID].format.wf.nBlockAlign - 1)) != 0)
1450     {
1451         WARN("WaveHdr length isn't a multiple of the PCM block size\n");
1452         lpWaveHdr->dwBufferLength &= ~(WOutDev[wDevID].format.wf.nBlockAlign - 1);
1453     }
1454
1455     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1456
1457     return MMSYSERR_NOERROR;
1458 }
1459
1460 /**************************************************************************
1461  *                              wodPrepare                      [internal]
1462  */
1463 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1464 {
1465     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1466
1467     if (wDevID >= numOutDev) {
1468         WARN("bad device ID !\n");
1469         return MMSYSERR_BADDEVICEID;
1470     }
1471
1472     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1473         return WAVERR_STILLPLAYING;
1474
1475     lpWaveHdr->dwFlags |= WHDR_PREPARED;
1476     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1477     return MMSYSERR_NOERROR;
1478 }
1479
1480 /**************************************************************************
1481  *                              wodUnprepare                    [internal]
1482  */
1483 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1484 {
1485     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1486
1487     if (wDevID >= numOutDev) {
1488         WARN("bad device ID !\n");
1489         return MMSYSERR_BADDEVICEID;
1490     }
1491
1492     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1493         return WAVERR_STILLPLAYING;
1494
1495     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1496     lpWaveHdr->dwFlags |= WHDR_DONE;
1497
1498     return MMSYSERR_NOERROR;
1499 }
1500
1501 /**************************************************************************
1502  *                      wodPause                                [internal]
1503  */
1504 static DWORD wodPause(WORD wDevID)
1505 {
1506     TRACE("(%u);!\n", wDevID);
1507
1508     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
1509         WARN("bad device ID !\n");
1510         return MMSYSERR_BADDEVICEID;
1511     }
1512
1513     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1514
1515     return MMSYSERR_NOERROR;
1516 }
1517
1518 /**************************************************************************
1519  *                      wodRestart                              [internal]
1520  */
1521 static DWORD wodRestart(WORD wDevID)
1522 {
1523     TRACE("(%u);\n", wDevID);
1524
1525     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
1526         WARN("bad device ID !\n");
1527         return MMSYSERR_BADDEVICEID;
1528     }
1529
1530     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1531
1532     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1533     /* FIXME: Myst crashes with this ... hmm -MM
1534        return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1535     */
1536
1537     return MMSYSERR_NOERROR;
1538 }
1539
1540 /**************************************************************************
1541  *                      wodReset                                [internal]
1542  */
1543 static DWORD wodReset(WORD wDevID)
1544 {
1545     TRACE("(%u);\n", wDevID);
1546
1547     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
1548         WARN("bad device ID !\n");
1549         return MMSYSERR_BADDEVICEID;
1550     }
1551
1552     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1553
1554     return MMSYSERR_NOERROR;
1555 }
1556
1557 /**************************************************************************
1558  *                              wodGetPosition                  [internal]
1559  */
1560 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1561 {
1562     int                 time;
1563     DWORD               val;
1564     WINE_WAVEOUT*       wwo;
1565
1566     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1567
1568     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
1569         WARN("bad device ID !\n");
1570         return MMSYSERR_BADDEVICEID;
1571     }
1572
1573     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1574
1575     wwo = &WOutDev[wDevID];
1576 #ifdef EXACT_WODPOSITION
1577     OSS_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1578 #endif
1579     val = wwo->dwPlayedTotal;
1580
1581     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
1582           lpTime->wType, wwo->format.wBitsPerSample,
1583           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
1584           wwo->format.wf.nAvgBytesPerSec);
1585     TRACE("dwPlayedTotal=%lu\n", val);
1586
1587     switch (lpTime->wType) {
1588     case TIME_BYTES:
1589         lpTime->u.cb = val;
1590         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
1591         break;
1592     case TIME_SAMPLES:
1593         lpTime->u.sample = val * 8 / wwo->format.wBitsPerSample /wwo->format.wf.nChannels;
1594         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
1595         break;
1596     case TIME_SMPTE:
1597         time = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1598         lpTime->u.smpte.hour = time / 108000;
1599         time -= lpTime->u.smpte.hour * 108000;
1600         lpTime->u.smpte.min = time / 1800;
1601         time -= lpTime->u.smpte.min * 1800;
1602         lpTime->u.smpte.sec = time / 30;
1603         time -= lpTime->u.smpte.sec * 30;
1604         lpTime->u.smpte.frame = time;
1605         lpTime->u.smpte.fps = 30;
1606         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
1607               lpTime->u.smpte.hour, lpTime->u.smpte.min,
1608               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
1609         break;
1610     default:
1611         FIXME("Format %d not supported ! use TIME_MS !\n", lpTime->wType);
1612         lpTime->wType = TIME_MS;
1613     case TIME_MS:
1614         lpTime->u.ms = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1615         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
1616         break;
1617     }
1618     return MMSYSERR_NOERROR;
1619 }
1620
1621 /**************************************************************************
1622  *                              wodBreakLoop                    [internal]
1623  */
1624 static DWORD wodBreakLoop(WORD wDevID)
1625 {
1626     TRACE("(%u);\n", wDevID);
1627
1628     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
1629         WARN("bad device ID !\n");
1630         return MMSYSERR_BADDEVICEID;
1631     }
1632     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
1633     return MMSYSERR_NOERROR;
1634 }
1635
1636 /**************************************************************************
1637  *                              wodGetVolume                    [internal]
1638  */
1639 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1640 {
1641     int         mixer;
1642     int         volume;
1643     DWORD       left, right;
1644
1645     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1646
1647     if (lpdwVol == NULL)
1648         return MMSYSERR_NOTENABLED;
1649     if (wDevID >= numOutDev) return MMSYSERR_INVALPARAM;
1650
1651     if ((mixer = open(WOutDev[wDevID].ossdev->mixer_name, O_RDONLY|O_NDELAY)) < 0) {
1652         WARN("mixer device not available !\n");
1653         return MMSYSERR_NOTENABLED;
1654     }
1655     if (ioctl(mixer, SOUND_MIXER_READ_PCM, &volume) == -1) {
1656         WARN("unable to read mixer !\n");
1657         return MMSYSERR_NOTENABLED;
1658     }
1659     close(mixer);
1660     left = LOBYTE(volume);
1661     right = HIBYTE(volume);
1662     TRACE("left=%ld right=%ld !\n", left, right);
1663     *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) << 16);
1664     return MMSYSERR_NOERROR;
1665 }
1666
1667 /**************************************************************************
1668  *                              wodSetVolume                    [internal]
1669  */
1670 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1671 {
1672     int         mixer;
1673     int         volume;
1674     DWORD       left, right;
1675
1676     TRACE("(%u, %08lX);\n", wDevID, dwParam);
1677
1678     left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
1679     right = (HIWORD(dwParam) * 100) / 0xFFFFl;
1680     volume = left + (right << 8);
1681
1682     if (wDevID >= numOutDev) return MMSYSERR_INVALPARAM;
1683
1684     if ((mixer = open(WOutDev[wDevID].ossdev->mixer_name, O_WRONLY|O_NDELAY)) < 0) {
1685         WARN("mixer device not available !\n");
1686         return MMSYSERR_NOTENABLED;
1687     }
1688     if (ioctl(mixer, SOUND_MIXER_WRITE_PCM, &volume) == -1) {
1689         WARN("unable to set mixer !\n");
1690         return MMSYSERR_NOTENABLED;
1691     } else {
1692         TRACE("volume=%04x\n", (unsigned)volume);
1693     }
1694     close(mixer);
1695     return MMSYSERR_NOERROR;
1696 }
1697
1698 /**************************************************************************
1699  *                              wodMessage (WINEOSS.7)
1700  */
1701 DWORD WINAPI OSS_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1702                             DWORD dwParam1, DWORD dwParam2)
1703 {
1704     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
1705           wDevID, wMsg, dwUser, dwParam1, dwParam2);
1706
1707     switch (wMsg) {
1708     case DRVM_INIT:
1709     case DRVM_EXIT:
1710     case DRVM_ENABLE:
1711     case DRVM_DISABLE:
1712         /* FIXME: Pretend this is supported */
1713         return 0;
1714     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1715     case WODM_CLOSE:            return wodClose         (wDevID);
1716     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1717     case WODM_PAUSE:            return wodPause         (wDevID);
1718     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
1719     case WODM_BREAKLOOP:        return wodBreakLoop     (wDevID);
1720     case WODM_PREPARE:          return wodPrepare       (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1721     case WODM_UNPREPARE:        return wodUnprepare     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1722     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSA)dwParam1,      dwParam2);
1723     case WODM_GETNUMDEVS:       return numOutDev;
1724     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1725     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1726     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1727     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1728     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
1729     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
1730     case WODM_RESTART:          return wodRestart       (wDevID);
1731     case WODM_RESET:            return wodReset         (wDevID);
1732
1733     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate(wDevID, (PIDSDRIVER*)dwParam1);
1734     default:
1735         FIXME("unknown message %d!\n", wMsg);
1736     }
1737     return MMSYSERR_NOTSUPPORTED;
1738 }
1739
1740 /*======================================================================*
1741  *                  Low level DSOUND implementation                     *
1742  *======================================================================*/
1743
1744 typedef struct IDsDriverImpl IDsDriverImpl;
1745 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1746
1747 struct IDsDriverImpl
1748 {
1749     /* IUnknown fields */
1750     ICOM_VFIELD(IDsDriver);
1751     DWORD               ref;
1752     /* IDsDriverImpl fields */
1753     UINT                wDevID;
1754     IDsDriverBufferImpl*primary;
1755 };
1756
1757 struct IDsDriverBufferImpl
1758 {
1759     /* IUnknown fields */
1760     ICOM_VFIELD(IDsDriverBuffer);
1761     DWORD               ref;
1762     /* IDsDriverBufferImpl fields */
1763     IDsDriverImpl*      drv;
1764     DWORD               buflen;
1765 };
1766
1767 static HRESULT DSDB_MapPrimary(IDsDriverBufferImpl *dsdb)
1768 {
1769     WINE_WAVEOUT *wwo = &(WOutDev[dsdb->drv->wDevID]);
1770     if (!wwo->mapping) {
1771         wwo->mapping = mmap(NULL, wwo->maplen, PROT_WRITE, MAP_SHARED,
1772                             wwo->ossdev->fd, 0);
1773         if (wwo->mapping == (LPBYTE)-1) {
1774             ERR("(%p): Could not map sound device for direct access (%s)\n", dsdb, strerror(errno));
1775             return DSERR_GENERIC;
1776         }
1777         TRACE("(%p): sound device has been mapped for direct access at %p, size=%ld\n", dsdb, wwo->mapping, wwo->maplen);
1778
1779         /* for some reason, es1371 and sblive! sometimes have junk in here.
1780          * clear it, or we get junk noise */
1781         /* some libc implementations are buggy: their memset reads from the buffer...
1782          * to work around it, we have to zero the block by hand. We don't do the expected:
1783          * memset(wwo->mapping,0, wwo->maplen);
1784          */
1785         {
1786             char*       p1 = wwo->mapping;
1787             unsigned    len = wwo->maplen;
1788
1789             if (len >= 16) /* so we can have at least a 4 long area to store... */
1790             {
1791                 /* the mmap:ed value is (at least) dword aligned
1792                  * so, start filling the complete unsigned long:s
1793                  */
1794                 int             b = len >> 2;
1795                 unsigned long*  p4 = (unsigned long*)p1;
1796
1797                 while (b--) *p4++ = 0;
1798                 /* prepare for filling the rest */
1799                 len &= 3;
1800                 p1 = (unsigned char*)p4;
1801             }
1802             /* in all cases, fill the remaining bytes */
1803             while (len-- != 0) *p1++ = 0;
1804         }
1805     }
1806     return DS_OK;
1807 }
1808
1809 static HRESULT DSDB_UnmapPrimary(IDsDriverBufferImpl *dsdb)
1810 {
1811     WINE_WAVEOUT *wwo = &(WOutDev[dsdb->drv->wDevID]);
1812     if (wwo->mapping) {
1813         if (munmap(wwo->mapping, wwo->maplen) < 0) {
1814             ERR("(%p): Could not unmap sound device (errno=%d)\n", dsdb, errno);
1815             return DSERR_GENERIC;
1816         }
1817         wwo->mapping = NULL;
1818         TRACE("(%p): sound device unmapped\n", dsdb);
1819     }
1820     return DS_OK;
1821 }
1822
1823 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
1824 {
1825     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1826     FIXME("(): stub!\n");
1827     return DSERR_UNSUPPORTED;
1828 }
1829
1830 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
1831 {
1832     ICOM_THIS(IDsDriverBufferImpl,iface);
1833     This->ref++;
1834     return This->ref;
1835 }
1836
1837 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
1838 {
1839     ICOM_THIS(IDsDriverBufferImpl,iface);
1840     if (--This->ref)
1841         return This->ref;
1842     if (This == This->drv->primary)
1843         This->drv->primary = NULL;
1844     DSDB_UnmapPrimary(This);
1845     HeapFree(GetProcessHeap(),0,This);
1846     return 0;
1847 }
1848
1849 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
1850                                                LPVOID*ppvAudio1,LPDWORD pdwLen1,
1851                                                LPVOID*ppvAudio2,LPDWORD pdwLen2,
1852                                                DWORD dwWritePosition,DWORD dwWriteLen,
1853                                                DWORD dwFlags)
1854 {
1855     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1856     /* since we (GetDriverDesc flags) have specified DSDDESC_DONTNEEDPRIMARYLOCK,
1857      * and that we don't support secondary buffers, this method will never be called */
1858     TRACE("(%p): stub\n",iface);
1859     return DSERR_UNSUPPORTED;
1860 }
1861
1862 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
1863                                                  LPVOID pvAudio1,DWORD dwLen1,
1864                                                  LPVOID pvAudio2,DWORD dwLen2)
1865 {
1866     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1867     TRACE("(%p): stub\n",iface);
1868     return DSERR_UNSUPPORTED;
1869 }
1870
1871 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
1872                                                     LPWAVEFORMATEX pwfx)
1873 {
1874     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1875
1876     TRACE("(%p,%p)\n",iface,pwfx);
1877     /* On our request (GetDriverDesc flags), DirectSound has by now used
1878      * waveOutClose/waveOutOpen to set the format...
1879      * unfortunately, this means our mmap() is now gone...
1880      * so we need to somehow signal to our DirectSound implementation
1881      * that it should completely recreate this HW buffer...
1882      * this unexpected error code should do the trick... */
1883     return DSERR_BUFFERLOST;
1884 }
1885
1886 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
1887 {
1888     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1889     TRACE("(%p,%ld): stub\n",iface,dwFreq);
1890     return DSERR_UNSUPPORTED;
1891 }
1892
1893 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
1894 {
1895     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1896     FIXME("(%p,%p): stub!\n",iface,pVolPan);
1897     return DSERR_UNSUPPORTED;
1898 }
1899
1900 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
1901 {
1902     /* ICOM_THIS(IDsDriverImpl,iface); */
1903     TRACE("(%p,%ld): stub\n",iface,dwNewPos);
1904     return DSERR_UNSUPPORTED;
1905 }
1906
1907 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
1908                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
1909 {
1910     ICOM_THIS(IDsDriverBufferImpl,iface);
1911     count_info info;
1912     DWORD ptr;
1913
1914     TRACE("(%p)\n",iface);
1915     if (WOutDev[This->drv->wDevID].state == WINE_WS_CLOSED) {
1916         ERR("device not open, but accessing?\n");
1917         return DSERR_UNINITIALIZED;
1918     }
1919     if (ioctl(WOutDev[This->drv->wDevID].ossdev->fd, SNDCTL_DSP_GETOPTR, &info) < 0) {
1920         ERR("ioctl failed (%d)\n", errno);
1921         return DSERR_GENERIC;
1922     }
1923     ptr = info.ptr & ~3; /* align the pointer, just in case */
1924     if (lpdwPlay) *lpdwPlay = ptr;
1925     if (lpdwWrite) {
1926         /* add some safety margin (not strictly necessary, but...) */
1927         if (WOutDev[This->drv->wDevID].ossdev->out_caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
1928             *lpdwWrite = ptr + 32;
1929         else
1930             *lpdwWrite = ptr + WOutDev[This->drv->wDevID].dwFragmentSize;
1931         while (*lpdwWrite > This->buflen)
1932             *lpdwWrite -= This->buflen;
1933     }
1934     TRACE("playpos=%ld, writepos=%ld\n", lpdwPlay?*lpdwPlay:0, lpdwWrite?*lpdwWrite:0);
1935     return DS_OK;
1936 }
1937
1938 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
1939 {
1940     ICOM_THIS(IDsDriverBufferImpl,iface);
1941     int enable = PCM_ENABLE_OUTPUT;
1942     TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
1943     if (ioctl(WOutDev[This->drv->wDevID].ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1944         ERR("ioctl failed (%d)\n", errno);
1945         return DSERR_GENERIC;
1946     }
1947     return DS_OK;
1948 }
1949
1950 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
1951 {
1952     ICOM_THIS(IDsDriverBufferImpl,iface);
1953     int enable = 0;
1954     TRACE("(%p)\n",iface);
1955     /* no more playing */
1956     if (ioctl(WOutDev[This->drv->wDevID].ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1957         ERR("ioctl failed (%d)\n", errno);
1958         return DSERR_GENERIC;
1959     }
1960 #if 0
1961     /* the play position must be reset to the beginning of the buffer */
1962     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_RESET, 0) < 0) {
1963         ERR("ioctl failed (%d)\n", errno);
1964         return DSERR_GENERIC;
1965     }
1966 #endif
1967     /* Most OSS drivers just can't stop the playback without closing the device...
1968      * so we need to somehow signal to our DirectSound implementation
1969      * that it should completely recreate this HW buffer...
1970      * this unexpected error code should do the trick... */
1971     return DSERR_BUFFERLOST;
1972 }
1973
1974 static ICOM_VTABLE(IDsDriverBuffer) dsdbvt =
1975 {
1976     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1977     IDsDriverBufferImpl_QueryInterface,
1978     IDsDriverBufferImpl_AddRef,
1979     IDsDriverBufferImpl_Release,
1980     IDsDriverBufferImpl_Lock,
1981     IDsDriverBufferImpl_Unlock,
1982     IDsDriverBufferImpl_SetFormat,
1983     IDsDriverBufferImpl_SetFrequency,
1984     IDsDriverBufferImpl_SetVolumePan,
1985     IDsDriverBufferImpl_SetPosition,
1986     IDsDriverBufferImpl_GetPosition,
1987     IDsDriverBufferImpl_Play,
1988     IDsDriverBufferImpl_Stop
1989 };
1990
1991 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
1992 {
1993     /* ICOM_THIS(IDsDriverImpl,iface); */
1994     FIXME("(%p): stub!\n",iface);
1995     return DSERR_UNSUPPORTED;
1996 }
1997
1998 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
1999 {
2000     ICOM_THIS(IDsDriverImpl,iface);
2001     This->ref++;
2002     return This->ref;
2003 }
2004
2005 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
2006 {
2007     ICOM_THIS(IDsDriverImpl,iface);
2008     if (--This->ref)
2009         return This->ref;
2010     HeapFree(GetProcessHeap(),0,This);
2011     return 0;
2012 }
2013
2014 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
2015 {
2016     ICOM_THIS(IDsDriverImpl,iface);
2017     TRACE("(%p,%p)\n",iface,pDesc);
2018     pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
2019         DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK;
2020     strcpy(pDesc->szDesc,"WineOSS DirectSound Driver");
2021     strcpy(pDesc->szDrvName,"wineoss.drv");
2022     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
2023     pDesc->wVxdId               = 0;
2024     pDesc->wReserved            = 0;
2025     pDesc->ulDeviceNum          = This->wDevID;
2026     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
2027     pDesc->pvDirectDrawHeap     = NULL;
2028     pDesc->dwMemStartAddress    = 0;
2029     pDesc->dwMemEndAddress      = 0;
2030     pDesc->dwMemAllocExtra      = 0;
2031     pDesc->pvReserved1          = NULL;
2032     pDesc->pvReserved2          = NULL;
2033     return DS_OK;
2034 }
2035
2036 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
2037 {
2038     ICOM_THIS(IDsDriverImpl,iface);
2039     int enable = 0;
2040
2041     TRACE("(%p)\n",iface);
2042     /* make sure the card doesn't start playing before we want it to */
2043     if (ioctl(WOutDev[This->wDevID].ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
2044         ERR("ioctl failed (%d)\n", errno);
2045         return DSERR_GENERIC;
2046     }
2047     return DS_OK;
2048 }
2049
2050 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
2051 {
2052     ICOM_THIS(IDsDriverImpl,iface);
2053     TRACE("(%p)\n",iface);
2054     if (This->primary) {
2055         ERR("problem with DirectSound: primary not released\n");
2056         return DSERR_GENERIC;
2057     }
2058     return DS_OK;
2059 }
2060
2061 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
2062 {
2063     /* ICOM_THIS(IDsDriverImpl,iface); */
2064     TRACE("(%p,%p)\n",iface,pCaps);
2065     memset(pCaps, 0, sizeof(*pCaps));
2066     /* FIXME: need to check actual capabilities */
2067     pCaps->dwFlags = DSCAPS_PRIMARYMONO | DSCAPS_PRIMARYSTEREO |
2068         DSCAPS_PRIMARY8BIT | DSCAPS_PRIMARY16BIT;
2069     pCaps->dwPrimaryBuffers = 1;
2070     /* the other fields only apply to secondary buffers, which we don't support
2071      * (unless we want to mess with wavetable synthesizers and MIDI) */
2072     return DS_OK;
2073 }
2074
2075 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
2076                                                       LPWAVEFORMATEX pwfx,
2077                                                       DWORD dwFlags, DWORD dwCardAddress,
2078                                                       LPDWORD pdwcbBufferSize,
2079                                                       LPBYTE *ppbBuffer,
2080                                                       LPVOID *ppvObj)
2081 {
2082     ICOM_THIS(IDsDriverImpl,iface);
2083     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
2084     HRESULT err;
2085     audio_buf_info info;
2086     int enable = 0;
2087
2088     TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
2089     /* we only support primary buffers */
2090     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
2091         return DSERR_UNSUPPORTED;
2092     if (This->primary)
2093         return DSERR_ALLOCATED;
2094     if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
2095         return DSERR_CONTROLUNAVAIL;
2096
2097     *ippdsdb = (IDsDriverBufferImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
2098     if (*ippdsdb == NULL)
2099         return DSERR_OUTOFMEMORY;
2100     ICOM_VTBL(*ippdsdb) = &dsdbvt;
2101     (*ippdsdb)->ref     = 1;
2102     (*ippdsdb)->drv     = This;
2103
2104     /* check how big the DMA buffer is now */
2105     if (ioctl(WOutDev[This->wDevID].ossdev->fd, SNDCTL_DSP_GETOSPACE, &info) < 0) {
2106         ERR("ioctl failed (%d)\n", errno);
2107         HeapFree(GetProcessHeap(),0,*ippdsdb);
2108         *ippdsdb = NULL;
2109         return DSERR_GENERIC;
2110     }
2111     WOutDev[This->wDevID].maplen = (*ippdsdb)->buflen = info.fragstotal * info.fragsize;
2112
2113     /* map the DMA buffer */
2114     err = DSDB_MapPrimary(*ippdsdb);
2115     if (err != DS_OK) {
2116         HeapFree(GetProcessHeap(),0,*ippdsdb);
2117         *ippdsdb = NULL;
2118         return err;
2119     }
2120
2121     /* primary buffer is ready to go */
2122     *pdwcbBufferSize    = WOutDev[This->wDevID].maplen;
2123     *ppbBuffer          = WOutDev[This->wDevID].mapping;
2124
2125     /* some drivers need some extra nudging after mapping */
2126     if (ioctl(WOutDev[This->wDevID].ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
2127         ERR("ioctl failed (%d)\n", errno);
2128         return DSERR_GENERIC;
2129     }
2130
2131     This->primary = *ippdsdb;
2132
2133     return DS_OK;
2134 }
2135
2136 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
2137                                                          PIDSDRIVERBUFFER pBuffer,
2138                                                          LPVOID *ppvObj)
2139 {
2140     /* ICOM_THIS(IDsDriverImpl,iface); */
2141     TRACE("(%p,%p): stub\n",iface,pBuffer);
2142     return DSERR_INVALIDCALL;
2143 }
2144
2145 static ICOM_VTABLE(IDsDriver) dsdvt =
2146 {
2147     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
2148     IDsDriverImpl_QueryInterface,
2149     IDsDriverImpl_AddRef,
2150     IDsDriverImpl_Release,
2151     IDsDriverImpl_GetDriverDesc,
2152     IDsDriverImpl_Open,
2153     IDsDriverImpl_Close,
2154     IDsDriverImpl_GetCaps,
2155     IDsDriverImpl_CreateSoundBuffer,
2156     IDsDriverImpl_DuplicateSoundBuffer
2157 };
2158
2159 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
2160 {
2161     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
2162
2163     /* the HAL isn't much better than the HEL if we can't do mmap() */
2164     if (!(WOutDev[wDevID].ossdev->out_caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
2165         ERR("DirectSound flag not set\n");
2166         MESSAGE("This sound card's driver does not support direct access\n");
2167         MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
2168         return MMSYSERR_NOTSUPPORTED;
2169     }
2170
2171     *idrv = (IDsDriverImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
2172     if (!*idrv)
2173         return MMSYSERR_NOMEM;
2174     ICOM_VTBL(*idrv)    = &dsdvt;
2175     (*idrv)->ref        = 1;
2176
2177     (*idrv)->wDevID     = wDevID;
2178     (*idrv)->primary    = NULL;
2179     return MMSYSERR_NOERROR;
2180 }
2181
2182 /*======================================================================*
2183  *                  Low level WAVE IN implementation                    *
2184  *======================================================================*/
2185
2186 /**************************************************************************
2187  *                      widNotifyClient                 [internal]
2188  */
2189 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
2190 {
2191     TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
2192
2193     switch (wMsg) {
2194     case WIM_OPEN:
2195     case WIM_CLOSE:
2196     case WIM_DATA:
2197         if (wwi->wFlags != DCB_NULL &&
2198             !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
2199                             (HDRVR)wwi->waveDesc.hWave, wMsg,
2200                             wwi->waveDesc.dwInstance, dwParam1, dwParam2)) {
2201             WARN("can't notify client !\n");
2202             return MMSYSERR_ERROR;
2203         }
2204         break;
2205     default:
2206         FIXME("Unknown callback message %u\n", wMsg);
2207         return MMSYSERR_INVALPARAM;
2208     }
2209     return MMSYSERR_NOERROR;
2210 }
2211
2212 /**************************************************************************
2213  *                      widGetDevCaps                           [internal]
2214  */
2215 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSA lpCaps, DWORD dwSize)
2216 {
2217     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
2218
2219     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
2220
2221     if (wDevID >= numInDev) {
2222         TRACE("numOutDev reached !\n");
2223         return MMSYSERR_BADDEVICEID;
2224     }
2225
2226     memcpy(lpCaps, &WInDev[wDevID].ossdev->in_caps, min(dwSize, sizeof(*lpCaps)));
2227     return MMSYSERR_NOERROR;
2228 }
2229
2230 /**************************************************************************
2231  *                              widRecorder                     [internal]
2232  */
2233 static  DWORD   CALLBACK        widRecorder(LPVOID pmt)
2234 {
2235     WORD                uDevID = (DWORD)pmt;
2236     WINE_WAVEIN*        wwi = (WINE_WAVEIN*)&WInDev[uDevID];
2237     WAVEHDR*            lpWaveHdr;
2238     DWORD               dwSleepTime;
2239     DWORD               bytesRead;
2240     LPVOID              buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, wwi->dwFragmentSize);
2241     LPVOID              pOffset = buffer;
2242     audio_buf_info      info;
2243     int                 xs;
2244     enum win_wm_message msg;
2245     DWORD               param;
2246     HANDLE              ev;
2247
2248     wwi->state = WINE_WS_STOPPED;
2249     wwi->dwTotalRecorded = 0;
2250
2251     SetEvent(wwi->hStartUpEvent);
2252
2253     /* the soundblaster live needs a micro wake to get its recording started
2254      * (or GETISPACE will have 0 frags all the time)
2255      */
2256     read(wwi->ossdev->fd, &xs, 4);
2257
2258         /* make sleep time to be # of ms to output a fragment */
2259     dwSleepTime = (wwi->dwFragmentSize * 1000) / wwi->format.wf.nAvgBytesPerSec;
2260     TRACE("sleeptime=%ld ms\n", dwSleepTime);
2261
2262     for (;;) {
2263         /* wait for dwSleepTime or an event in thread's queue */
2264         /* FIXME: could improve wait time depending on queue state,
2265          * ie, number of queued fragments
2266          */
2267
2268         if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
2269         {
2270             lpWaveHdr = wwi->lpQueuePtr;
2271
2272             ioctl(wwi->ossdev->fd, SNDCTL_DSP_GETISPACE, &info);
2273             TRACE("info={frag=%d fsize=%d ftotal=%d bytes=%d}\n", info.fragments, info.fragsize, info.fragstotal, info.bytes);
2274
2275             /* read all the fragments accumulated so far */
2276             while ((info.fragments > 0) && (wwi->lpQueuePtr))
2277             {
2278                 info.fragments --;
2279
2280                 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwFragmentSize)
2281                 {
2282                     /* directly read fragment in wavehdr */
2283                     bytesRead = read(wwi->ossdev->fd,
2284                                      lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2285                                      wwi->dwFragmentSize);
2286
2287                     TRACE("bytesRead=%ld (direct)\n", bytesRead);
2288                     if (bytesRead != (DWORD) -1)
2289                     {
2290                         /* update number of bytes recorded in current buffer and by this device */
2291                         lpWaveHdr->dwBytesRecorded += bytesRead;
2292                         wwi->dwTotalRecorded       += bytesRead;
2293
2294                         /* buffer is full. notify client */
2295                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2296                         {
2297                             /* must copy the value of next waveHdr, because we have no idea of what
2298                              * will be done with the content of lpWaveHdr in callback
2299                              */
2300                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
2301
2302                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2303                             lpWaveHdr->dwFlags |=  WHDR_DONE;
2304
2305                             widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2306                             lpWaveHdr = wwi->lpQueuePtr = lpNext;
2307                         }
2308                     }
2309                 }
2310                 else
2311                 {
2312                     /* read the fragment in a local buffer */
2313                     bytesRead = read(wwi->ossdev->fd, buffer, wwi->dwFragmentSize);
2314                     pOffset = buffer;
2315
2316                     TRACE("bytesRead=%ld (local)\n", bytesRead);
2317
2318                     /* copy data in client buffers */
2319                     while (bytesRead != (DWORD) -1 && bytesRead > 0)
2320                     {
2321                         DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
2322
2323                         memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2324                                pOffset,
2325                                dwToCopy);
2326
2327                         /* update number of bytes recorded in current buffer and by this device */
2328                         lpWaveHdr->dwBytesRecorded += dwToCopy;
2329                         wwi->dwTotalRecorded += dwToCopy;
2330                         bytesRead -= dwToCopy;
2331                         pOffset   += dwToCopy;
2332
2333                         /* client buffer is full. notify client */
2334                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2335                         {
2336                             /* must copy the value of next waveHdr, because we have no idea of what
2337                              * will be done with the content of lpWaveHdr in callback
2338                              */
2339                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
2340                             TRACE("lpNext=%p\n", lpNext);
2341
2342                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2343                             lpWaveHdr->dwFlags |=  WHDR_DONE;
2344
2345                             widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2346
2347                             wwi->lpQueuePtr = lpWaveHdr = lpNext;
2348                             if (!lpNext && bytesRead) {
2349                                 /* no more buffer to copy data to, but we did read more.
2350                                  * what hasn't been copied will be dropped
2351                                  */
2352                                 WARN("buffer under run! %lu bytes dropped.\n", bytesRead);
2353                                 wwi->lpQueuePtr = NULL;
2354                                 break;
2355                             }
2356                         }
2357                     }
2358                 }
2359             }
2360         }
2361
2362         WAIT_OMR(&wwi->msgRing, dwSleepTime);
2363
2364         while (OSS_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev))
2365         {
2366
2367             TRACE("msg=0x%x param=0x%lx\n", msg, param);
2368             switch (msg) {
2369             case WINE_WM_PAUSING:
2370                 wwi->state = WINE_WS_PAUSED;
2371                 /*FIXME("Device should stop recording\n");*/
2372                 SetEvent(ev);
2373                 break;
2374             case WINE_WM_RESTARTING:
2375             {
2376                 int enable = PCM_ENABLE_INPUT;
2377                 wwi->state = WINE_WS_PLAYING;
2378
2379                 if (wwi->ossdev->bTriggerSupport)
2380                 {
2381                     /* start the recording */
2382                     if (ioctl(wwi->ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0)
2383                     {
2384                         ERR("ioctl(SNDCTL_DSP_SETTRIGGER) failed (%d)\n", errno);
2385                     }
2386                 }
2387                 else
2388                 {
2389                     unsigned char data[4];
2390                     /* read 4 bytes to start the recording */
2391                     read(wwi->ossdev->fd, data, 4);
2392                 }
2393
2394                 SetEvent(ev);
2395                 break;
2396             }
2397             case WINE_WM_HEADER:
2398                 lpWaveHdr = (LPWAVEHDR)param;
2399                 lpWaveHdr->lpNext = 0;
2400
2401                 /* insert buffer at the end of queue */
2402                 {
2403                     LPWAVEHDR*  wh;
2404                     for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2405                     *wh = lpWaveHdr;
2406                 }
2407                 break;
2408             case WINE_WM_RESETTING:
2409                 wwi->state = WINE_WS_STOPPED;
2410                 /* return all buffers to the app */
2411                 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
2412                     TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
2413                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2414                     lpWaveHdr->dwFlags |= WHDR_DONE;
2415
2416                     widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2417                 }
2418                 wwi->lpQueuePtr = NULL;
2419                 SetEvent(ev);
2420                 break;
2421             case WINE_WM_CLOSING:
2422                 wwi->hThread = 0;
2423                 wwi->state = WINE_WS_CLOSED;
2424                 SetEvent(ev);
2425                 HeapFree(GetProcessHeap(), 0, buffer);
2426                 ExitThread(0);
2427                 /* shouldn't go here */
2428             default:
2429                 FIXME("unknown message %d\n", msg);
2430                 break;
2431             }
2432         }
2433     }
2434     ExitThread(0);
2435     /* just for not generating compilation warnings... should never be executed */
2436     return 0;
2437 }
2438
2439
2440 /**************************************************************************
2441  *                              widOpen                         [internal]
2442  */
2443 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
2444 {
2445     WINE_WAVEIN*        wwi;
2446     int                 fragment_size;
2447     int                 audio_fragment;
2448     DWORD               ret;
2449
2450     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
2451     if (lpDesc == NULL) {
2452         WARN("Invalid Parameter !\n");
2453         return MMSYSERR_INVALPARAM;
2454     }
2455     if (wDevID >= numInDev) return MMSYSERR_BADDEVICEID;
2456
2457     /* only PCM format is supported so far... */
2458     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
2459         lpDesc->lpFormat->nChannels == 0 ||
2460         lpDesc->lpFormat->nSamplesPerSec == 0) {
2461         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
2462              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
2463              lpDesc->lpFormat->nSamplesPerSec);
2464         return WAVERR_BADFORMAT;
2465     }
2466
2467     if (dwFlags & WAVE_FORMAT_QUERY) {
2468         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
2469              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
2470              lpDesc->lpFormat->nSamplesPerSec);
2471         return MMSYSERR_NOERROR;
2472     }
2473
2474     wwi = &WInDev[wDevID];
2475
2476     if (wwi->state != WINE_WS_CLOSED) return MMSYSERR_ALLOCATED;
2477     /* This is actually hand tuned to work so that my SB Live:
2478      * - does not skip
2479      * - does not buffer too much
2480      * when sending with the Shoutcast winamp plugin
2481      */
2482     /* 15 fragments max, 2^10 = 1024 bytes per fragment */
2483     audio_fragment = 0x000F000A;
2484     ret = OSS_OpenDevice(wwi->ossdev, O_RDONLY, &audio_fragment,
2485                          lpDesc->lpFormat->nSamplesPerSec,
2486                          (lpDesc->lpFormat->nChannels > 1) ? 1 : 0,
2487                          (lpDesc->lpFormat->wBitsPerSample == 16)
2488                          ? AFMT_S16_LE : AFMT_U8);
2489     if (ret != 0) return ret;
2490     wwi->state = WINE_WS_STOPPED;
2491
2492     if (wwi->lpQueuePtr) {
2493         WARN("Should have an empty queue (%p)\n", wwi->lpQueuePtr);
2494         wwi->lpQueuePtr = NULL;
2495     }
2496     wwi->dwTotalRecorded = 0;
2497     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
2498
2499     memcpy(&wwi->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
2500     memcpy(&wwi->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
2501
2502     if (wwi->format.wBitsPerSample == 0) {
2503         WARN("Resetting zeroed wBitsPerSample\n");
2504         wwi->format.wBitsPerSample = 8 *
2505             (wwi->format.wf.nAvgBytesPerSec /
2506              wwi->format.wf.nSamplesPerSec) /
2507             wwi->format.wf.nChannels;
2508     }
2509
2510     ioctl(wwi->ossdev->fd, SNDCTL_DSP_GETBLKSIZE, &fragment_size);
2511     if (fragment_size == -1) {
2512         WARN("IOCTL can't 'SNDCTL_DSP_GETBLKSIZE' !\n");
2513         OSS_CloseDevice(wwi->ossdev);
2514         wwi->state = WINE_WS_CLOSED;
2515         return MMSYSERR_NOTENABLED;
2516     }
2517     wwi->dwFragmentSize = fragment_size;
2518
2519     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
2520           wwi->format.wBitsPerSample, wwi->format.wf.nAvgBytesPerSec,
2521           wwi->format.wf.nSamplesPerSec, wwi->format.wf.nChannels,
2522           wwi->format.wf.nBlockAlign);
2523
2524     OSS_InitRingMessage(&wwi->msgRing);
2525
2526     wwi->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
2527     wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
2528     WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
2529     CloseHandle(wwi->hStartUpEvent);
2530     wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
2531
2532     return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
2533 }
2534
2535 /**************************************************************************
2536  *                              widClose                        [internal]
2537  */
2538 static DWORD widClose(WORD wDevID)
2539 {
2540     WINE_WAVEIN*        wwi;
2541
2542     TRACE("(%u);\n", wDevID);
2543     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2544         WARN("can't close !\n");
2545         return MMSYSERR_INVALHANDLE;
2546     }
2547
2548     wwi = &WInDev[wDevID];
2549
2550     if (wwi->lpQueuePtr != NULL) {
2551         WARN("still buffers open !\n");
2552         return WAVERR_STILLPLAYING;
2553     }
2554
2555     OSS_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
2556     OSS_CloseDevice(wwi->ossdev);
2557     wwi->state = WINE_WS_CLOSED;
2558     wwi->dwFragmentSize = 0;
2559     OSS_DestroyRingMessage(&wwi->msgRing);
2560     return widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
2561 }
2562
2563 /**************************************************************************
2564  *                              widAddBuffer            [internal]
2565  */
2566 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2567 {
2568     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2569
2570     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2571         WARN("can't do it !\n");
2572         return MMSYSERR_INVALHANDLE;
2573     }
2574     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED)) {
2575         TRACE("never been prepared !\n");
2576         return WAVERR_UNPREPARED;
2577     }
2578     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) {
2579         TRACE("header already in use !\n");
2580         return WAVERR_STILLPLAYING;
2581     }
2582
2583     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2584     lpWaveHdr->dwFlags &= ~WHDR_DONE;
2585     lpWaveHdr->dwBytesRecorded = 0;
2586     lpWaveHdr->lpNext = NULL;
2587
2588     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
2589     return MMSYSERR_NOERROR;
2590 }
2591
2592 /**************************************************************************
2593  *                              widPrepare                      [internal]
2594  */
2595 static DWORD widPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2596 {
2597     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2598
2599     if (wDevID >= numInDev) return MMSYSERR_INVALHANDLE;
2600
2601     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2602         return WAVERR_STILLPLAYING;
2603
2604     lpWaveHdr->dwFlags |= WHDR_PREPARED;
2605     lpWaveHdr->dwFlags &= ~WHDR_DONE;
2606     lpWaveHdr->dwBytesRecorded = 0;
2607     TRACE("header prepared !\n");
2608     return MMSYSERR_NOERROR;
2609 }
2610
2611 /**************************************************************************
2612  *                              widUnprepare                    [internal]
2613  */
2614 static DWORD widUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2615 {
2616     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2617     if (wDevID >= numInDev) return MMSYSERR_INVALHANDLE;
2618
2619     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2620         return WAVERR_STILLPLAYING;
2621
2622     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
2623     lpWaveHdr->dwFlags |= WHDR_DONE;
2624
2625     return MMSYSERR_NOERROR;
2626 }
2627
2628 /**************************************************************************
2629  *                      widStart                                [internal]
2630  */
2631 static DWORD widStart(WORD wDevID)
2632 {
2633     TRACE("(%u);\n", wDevID);
2634     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2635         WARN("can't start recording !\n");
2636         return MMSYSERR_INVALHANDLE;
2637     }
2638
2639     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
2640     return MMSYSERR_NOERROR;
2641 }
2642
2643 /**************************************************************************
2644  *                      widStop                                 [internal]
2645  */
2646 static DWORD widStop(WORD wDevID)
2647 {
2648     TRACE("(%u);\n", wDevID);
2649     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2650         WARN("can't stop !\n");
2651         return MMSYSERR_INVALHANDLE;
2652     }
2653     /* FIXME: reset aint stop */
2654     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
2655
2656     return MMSYSERR_NOERROR;
2657 }
2658
2659 /**************************************************************************
2660  *                      widReset                                [internal]
2661  */
2662 static DWORD widReset(WORD wDevID)
2663 {
2664     TRACE("(%u);\n", wDevID);
2665     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2666         WARN("can't reset !\n");
2667         return MMSYSERR_INVALHANDLE;
2668     }
2669     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
2670     return MMSYSERR_NOERROR;
2671 }
2672
2673 /**************************************************************************
2674  *                              widGetPosition                  [internal]
2675  */
2676 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
2677 {
2678     int                 time;
2679     WINE_WAVEIN*        wwi;
2680
2681     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
2682
2683     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2684         WARN("can't get pos !\n");
2685         return MMSYSERR_INVALHANDLE;
2686     }
2687     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
2688
2689     wwi = &WInDev[wDevID];
2690
2691     TRACE("wType=%04X !\n", lpTime->wType);
2692     TRACE("wBitsPerSample=%u\n", wwi->format.wBitsPerSample);
2693     TRACE("nSamplesPerSec=%lu\n", wwi->format.wf.nSamplesPerSec);
2694     TRACE("nChannels=%u\n", wwi->format.wf.nChannels);
2695     TRACE("nAvgBytesPerSec=%lu\n", wwi->format.wf.nAvgBytesPerSec);
2696     switch (lpTime->wType) {
2697     case TIME_BYTES:
2698         lpTime->u.cb = wwi->dwTotalRecorded;
2699         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
2700         break;
2701     case TIME_SAMPLES:
2702         lpTime->u.sample = wwi->dwTotalRecorded * 8 /
2703             wwi->format.wBitsPerSample;
2704         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
2705         break;
2706     case TIME_SMPTE:
2707         time = wwi->dwTotalRecorded /
2708             (wwi->format.wf.nAvgBytesPerSec / 1000);
2709         lpTime->u.smpte.hour = time / 108000;
2710         time -= lpTime->u.smpte.hour * 108000;
2711         lpTime->u.smpte.min = time / 1800;
2712         time -= lpTime->u.smpte.min * 1800;
2713         lpTime->u.smpte.sec = time / 30;
2714         time -= lpTime->u.smpte.sec * 30;
2715         lpTime->u.smpte.frame = time;
2716         lpTime->u.smpte.fps = 30;
2717         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
2718               lpTime->u.smpte.hour, lpTime->u.smpte.min,
2719               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
2720         break;
2721     case TIME_MS:
2722         lpTime->u.ms = wwi->dwTotalRecorded /
2723             (wwi->format.wf.nAvgBytesPerSec / 1000);
2724         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
2725         break;
2726     default:
2727         FIXME("format not supported (%u) ! use TIME_MS !\n", lpTime->wType);
2728         lpTime->wType = TIME_MS;
2729     }
2730     return MMSYSERR_NOERROR;
2731 }
2732
2733 /**************************************************************************
2734  *                              widMessage (WINEOSS.6)
2735  */
2736 DWORD WINAPI OSS_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2737                             DWORD dwParam1, DWORD dwParam2)
2738 {
2739     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
2740           wDevID, wMsg, dwUser, dwParam1, dwParam2);
2741
2742     switch (wMsg) {
2743     case DRVM_INIT:
2744     case DRVM_EXIT:
2745     case DRVM_ENABLE:
2746     case DRVM_DISABLE:
2747         /* FIXME: Pretend this is supported */
2748         return 0;
2749     case WIDM_OPEN:             return widOpen       (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2750     case WIDM_CLOSE:            return widClose      (wDevID);
2751     case WIDM_ADDBUFFER:        return widAddBuffer  (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2752     case WIDM_PREPARE:          return widPrepare    (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2753     case WIDM_UNPREPARE:        return widUnprepare  (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2754     case WIDM_GETDEVCAPS:       return widGetDevCaps (wDevID, (LPWAVEINCAPSA)dwParam1, dwParam2);
2755     case WIDM_GETNUMDEVS:       return numInDev;
2756     case WIDM_GETPOS:           return widGetPosition(wDevID, (LPMMTIME)dwParam1, dwParam2);
2757     case WIDM_RESET:            return widReset      (wDevID);
2758     case WIDM_START:            return widStart      (wDevID);
2759     case WIDM_STOP:             return widStop       (wDevID);
2760     default:
2761         FIXME("unknown message %u!\n", wMsg);
2762     }
2763     return MMSYSERR_NOTSUPPORTED;
2764 }
2765
2766 #else /* !HAVE_OSS */
2767
2768 /**************************************************************************
2769  *                              wodMessage (WINEOSS.7)
2770  */
2771 DWORD WINAPI OSS_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2772                             DWORD dwParam1, DWORD dwParam2)
2773 {
2774     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2775     return MMSYSERR_NOTENABLED;
2776 }
2777
2778 /**************************************************************************
2779  *                              widMessage (WINEOSS.6)
2780  */
2781 DWORD WINAPI OSS_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2782                             DWORD dwParam1, DWORD dwParam2)
2783 {
2784     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2785     return MMSYSERR_NOTENABLED;
2786 }
2787
2788 #endif /* HAVE_OSS */