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