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