Added driver notify implementation.
[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  *      Direct Sound Capture driver does not work (not complete yet)
28  */
29
30 /*#define EMULATE_SB16*/
31
32 /* unless someone makes a wineserver kernel module, Unix pipes are faster than win32 events */
33 #define USE_PIPE_SYNC
34
35 /* an exact wodGetPosition is usually not worth the extra context switches,
36  * as we're going to have near fragment accuracy anyway */
37 /* #define EXACT_WODPOSITION */
38
39 #include "config.h"
40
41 #include <stdlib.h>
42 #include <stdio.h>
43 #include <string.h>
44 #ifdef HAVE_UNISTD_H
45 # include <unistd.h>
46 #endif
47 #include <errno.h>
48 #include <fcntl.h>
49 #ifdef HAVE_SYS_IOCTL_H
50 # include <sys/ioctl.h>
51 #endif
52 #ifdef HAVE_SYS_MMAN_H
53 # include <sys/mman.h>
54 #endif
55 #ifdef HAVE_SYS_POLL_H
56 # include <sys/poll.h>
57 #endif
58
59 #include "windef.h"
60 #include "wingdi.h"
61 #include "winerror.h"
62 #include "wine/winuser16.h"
63 #include "mmddk.h"
64 #include "dsound.h"
65 #include "dsdriver.h"
66 #include "oss.h"
67 #include "wine/debug.h"
68
69 WINE_DEFAULT_DEBUG_CHANNEL(wave);
70
71 /* Allow 1% deviation for sample rates (some ES137x cards) */
72 #define NEAR_MATCH(rate1,rate2) (((100*((int)(rate1)-(int)(rate2)))/(rate1))==0)
73
74 #ifdef HAVE_OSS
75
76 #define MAX_WAVEDRV     (6)
77
78 /* state diagram for waveOut writing:
79  *
80  * +---------+-------------+---------------+---------------------------------+
81  * |  state  |  function   |     event     |            new state            |
82  * +---------+-------------+---------------+---------------------------------+
83  * |         | open()      |               | STOPPED                         |
84  * | PAUSED  | write()     |               | PAUSED                          |
85  * | STOPPED | write()     | <thrd create> | PLAYING                         |
86  * | PLAYING | write()     | HEADER        | PLAYING                         |
87  * | (other) | write()     | <error>       |                                 |
88  * | (any)   | pause()     | PAUSING       | PAUSED                          |
89  * | PAUSED  | restart()   | RESTARTING    | PLAYING (if no thrd => STOPPED) |
90  * | (any)   | reset()     | RESETTING     | STOPPED                         |
91  * | (any)   | close()     | CLOSING       | CLOSED                          |
92  * +---------+-------------+---------------+---------------------------------+
93  */
94
95 /* states of the playing device */
96 #define WINE_WS_PLAYING         0
97 #define WINE_WS_PAUSED          1
98 #define WINE_WS_STOPPED         2
99 #define WINE_WS_CLOSED          3
100
101 /* events to be send to device */
102 enum win_wm_message {
103     WINE_WM_PAUSING = WM_USER + 1, WINE_WM_RESTARTING, WINE_WM_RESETTING, WINE_WM_HEADER,
104     WINE_WM_UPDATE, WINE_WM_BREAKLOOP, WINE_WM_CLOSING, WINE_WM_STARTING, WINE_WM_STOPPING
105 };
106
107 #ifdef USE_PIPE_SYNC
108 #define SIGNAL_OMR(omr) do { int x = 0; write((omr)->msg_pipe[1], &x, sizeof(x)); } while (0)
109 #define CLEAR_OMR(omr) do { int x = 0; read((omr)->msg_pipe[0], &x, sizeof(x)); } while (0)
110 #define RESET_OMR(omr) do { } while (0)
111 #define WAIT_OMR(omr, sleep) \
112   do { struct pollfd pfd; pfd.fd = (omr)->msg_pipe[0]; \
113        pfd.events = POLLIN; poll(&pfd, 1, sleep); } while (0)
114 #else
115 #define SIGNAL_OMR(omr) do { SetEvent((omr)->msg_event); } while (0)
116 #define CLEAR_OMR(omr) do { } while (0)
117 #define RESET_OMR(omr) do { ResetEvent((omr)->msg_event); } while (0)
118 #define WAIT_OMR(omr, sleep) \
119   do { WaitForSingleObject((omr)->msg_event, sleep); } while (0)
120 #endif
121
122 typedef struct {
123     enum win_wm_message         msg;    /* message identifier */
124     DWORD                       param;  /* parameter for this message */
125     HANDLE                      hEvent; /* if message is synchronous, handle of event for synchro */
126 } OSS_MSG;
127
128 /* implement an in-process message ring for better performance
129  * (compared to passing thru the server)
130  * this ring will be used by the input (resp output) record (resp playback) routine
131  */
132 typedef struct {
133     /* FIXME: this could be made a dynamically growing array (if needed) */
134     /* maybe it's needed, a Humongous game manages to transmit 128 messages at once at startup */
135 #define OSS_RING_BUFFER_SIZE    192
136     OSS_MSG                     messages[OSS_RING_BUFFER_SIZE];
137     int                         msg_tosave;
138     int                         msg_toget;
139 #ifdef USE_PIPE_SYNC
140     int                         msg_pipe[2];
141 #else
142     HANDLE                      msg_event;
143 #endif
144     CRITICAL_SECTION            msg_crst;
145 } OSS_MSG_RING;
146
147 typedef struct tagOSS_DEVICE {
148     char                        dev_name[32];
149     char                        mixer_name[32];
150     unsigned                    open_count;
151     WAVEOUTCAPSA                out_caps;
152     WAVEINCAPSA                 in_caps;
153     DWORD                       in_caps_support;
154     unsigned                    open_access;
155     int                         fd;
156     DWORD                       owner_tid;
157     int                         sample_rate;
158     int                         stereo;
159     int                         format;
160     unsigned                    audio_fragment;
161     BOOL                        full_duplex;
162     BOOL                        bTriggerSupport;
163     BOOL                        bOutputEnabled;
164     BOOL                        bInputEnabled;
165     DSDRIVERDESC                ds_desc;
166     DSDRIVERCAPS                ds_caps;
167     DSCDRIVERCAPS               dsc_caps;
168     GUID                        ds_guid;
169     GUID                        dsc_guid;
170 } OSS_DEVICE;
171
172 static OSS_DEVICE   OSS_Devices[MAX_WAVEDRV];
173
174 typedef struct {
175     OSS_DEVICE*                 ossdev;
176     volatile int                state;                  /* one of the WINE_WS_ manifest constants */
177     WAVEOPENDESC                waveDesc;
178     WORD                        wFlags;
179     PCMWAVEFORMAT               format;
180
181     /* OSS information */
182     DWORD                       dwFragmentSize;         /* size of OSS buffer fragment */
183     DWORD                       dwBufferSize;           /* size of whole OSS buffer in bytes */
184     LPWAVEHDR                   lpQueuePtr;             /* start of queued WAVEHDRs (waiting to be notified) */
185     LPWAVEHDR                   lpPlayPtr;              /* start of not yet fully played buffers */
186     DWORD                       dwPartialOffset;        /* Offset of not yet written bytes in lpPlayPtr */
187
188     LPWAVEHDR                   lpLoopPtr;              /* pointer of first buffer in loop, if any */
189     DWORD                       dwLoops;                /* private copy of loop counter */
190
191     DWORD                       dwPlayedTotal;          /* number of bytes actually played since opening */
192     DWORD                       dwWrittenTotal;         /* number of bytes written to OSS buffer since opening */
193     BOOL                        bNeedPost;              /* whether audio still needs to be physically started */
194
195     /* synchronization stuff */
196     HANDLE                      hStartUpEvent;
197     HANDLE                      hThread;
198     DWORD                       dwThreadID;
199     OSS_MSG_RING                msgRing;
200
201     /* DirectSound stuff */
202     LPBYTE                      mapping;
203     DWORD                       maplen;
204 } WINE_WAVEOUT;
205
206 typedef struct {
207     OSS_DEVICE*                 ossdev;
208     volatile int                state;
209     DWORD                       dwFragmentSize;         /* OpenSound '/dev/dsp' give us that size */
210     WAVEOPENDESC                waveDesc;
211     WORD                        wFlags;
212     PCMWAVEFORMAT               format;
213     LPWAVEHDR                   lpQueuePtr;
214     DWORD                       dwTotalRecorded;
215
216     /* synchronization stuff */
217     HANDLE                      hThread;
218     DWORD                       dwThreadID;
219     HANDLE                      hStartUpEvent;
220     OSS_MSG_RING                msgRing;
221
222     /* DirectSound stuff */
223     LPBYTE                      mapping;
224     DWORD                       maplen;
225 } WINE_WAVEIN;
226
227 static WINE_WAVEOUT     WOutDev   [MAX_WAVEDRV];
228 static WINE_WAVEIN      WInDev    [MAX_WAVEDRV];
229 static unsigned         numOutDev;
230 static unsigned         numInDev;
231
232 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
233 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv);
234 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
235 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc);
236 static DWORD wodDsGuid(UINT wDevID, LPGUID pGuid);
237 static DWORD widDsGuid(UINT wDevID, LPGUID pGuid);
238
239 /* These strings used only for tracing */
240 static const char *wodPlayerCmdString[] = {
241     "WINE_WM_PAUSING",
242     "WINE_WM_RESTARTING",
243     "WINE_WM_RESETTING",
244     "WINE_WM_HEADER",
245     "WINE_WM_UPDATE",
246     "WINE_WM_BREAKLOOP",
247     "WINE_WM_CLOSING",
248     "WINE_WM_STARTING",
249     "WINE_WM_STOPPING",
250 };
251
252 static int getEnables(OSS_DEVICE *ossdev)
253 {
254     return ( (ossdev->bOutputEnabled ? PCM_ENABLE_OUTPUT : 0) | 
255              (ossdev->bInputEnabled  ? PCM_ENABLE_INPUT  : 0) );
256 }
257
258 /*======================================================================*
259  *                  Low level WAVE implementation                       *
260  *======================================================================*/
261
262 /******************************************************************
263  *              OSS_RawOpenDevice
264  *
265  * Low level device opening (from values stored in ossdev)
266  */
267 static DWORD      OSS_RawOpenDevice(OSS_DEVICE* ossdev, int strict_format)
268 {
269     int fd, val, rc;
270     TRACE("(%p,%d)\n",ossdev,strict_format);
271
272     if ((fd = open(ossdev->dev_name, ossdev->open_access|O_NDELAY, 0)) == -1)
273     {
274         WARN("Couldn't open %s (%s)\n", ossdev->dev_name, strerror(errno));
275         return (errno == EBUSY) ? MMSYSERR_ALLOCATED : MMSYSERR_ERROR;
276     }
277     fcntl(fd, F_SETFD, 1); /* set close on exec flag */
278     /* turn full duplex on if it has been requested */
279     if (ossdev->open_access == O_RDWR && ossdev->full_duplex) {
280         rc = ioctl(fd, SNDCTL_DSP_SETDUPLEX, 0);
281         /* on *BSD, as full duplex is always enabled by default, this ioctl
282          * will fail with EINVAL
283          * so, we don't consider EINVAL an error here
284          */
285         if (rc != 0 && errno != EINVAL) {
286             ERR("ioctl(%s, SNDCTL_DSP_SETDUPLEX) failed (%s)\n", ossdev->dev_name, strerror(errno));
287             goto error;
288         }
289     }
290
291     if (ossdev->audio_fragment) {
292         rc = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &ossdev->audio_fragment);
293         if (rc != 0) {
294             ERR("ioctl(%s, SNDCTL_DSP_SETFRAGMENT) failed (%s)\n", ossdev->dev_name, strerror(errno));
295             goto error;
296         }
297     }
298
299     /* First size and stereo then samplerate */
300     if (ossdev->format>=0)
301     {
302         val = ossdev->format;
303         rc = ioctl(fd, SNDCTL_DSP_SETFMT, &ossdev->format);
304         if (rc != 0 || val != ossdev->format) {
305             TRACE("Can't set format to %d (returned %d)\n", val, ossdev->format);
306             if (strict_format)
307                 goto error;
308         }
309     }
310     if (ossdev->stereo>=0)
311     {
312         val = ossdev->stereo;
313         rc = ioctl(fd, SNDCTL_DSP_STEREO, &ossdev->stereo);
314         if (rc != 0 || val != ossdev->stereo) {
315             TRACE("Can't set stereo to %u (returned %d)\n", val, ossdev->stereo);
316             if (strict_format)
317                 goto error;
318         }
319     }
320     if (ossdev->sample_rate>=0)
321     {
322         val = ossdev->sample_rate;
323         rc = ioctl(fd, SNDCTL_DSP_SPEED, &ossdev->sample_rate);
324         if (rc != 0 || !NEAR_MATCH(val, ossdev->sample_rate)) {
325             TRACE("Can't set sample_rate to %u (returned %d)\n", val, ossdev->sample_rate);
326             if (strict_format)
327                 goto error;
328         }
329     }
330     ossdev->fd = fd;
331
332     if (ossdev->bTriggerSupport) {
333         int trigger;
334         rc = ioctl(fd, SNDCTL_DSP_GETTRIGGER, &trigger);
335         if (rc != 0) {
336             ERR("ioctl(%s, SNDCTL_DSP_GETTRIGGER) failed (%s)\n", 
337                 ossdev->dev_name, strerror(errno));
338             goto error;
339         }
340         
341         ossdev->bOutputEnabled = ((trigger & PCM_ENABLE_OUTPUT) == PCM_ENABLE_OUTPUT);
342         ossdev->bInputEnabled  = ((trigger & PCM_ENABLE_INPUT) == PCM_ENABLE_INPUT);
343     } else {
344         ossdev->bOutputEnabled = TRUE;  /* OSS enables by default */
345         ossdev->bInputEnabled  = TRUE;  /* OSS enables by default */
346     }
347
348     return MMSYSERR_NOERROR;
349
350 error:
351     close(fd);
352     return WAVERR_BADFORMAT;
353 }
354
355 /******************************************************************
356  *              OSS_OpenDevice
357  *
358  * since OSS has poor capabilities in full duplex, we try here to let a program
359  * open the device for both waveout and wavein streams...
360  * this is hackish, but it's the way OSS interface is done...
361  */
362 static DWORD OSS_OpenDevice(OSS_DEVICE* ossdev, unsigned req_access,
363                             int* frag, int strict_format,
364                             int sample_rate, int stereo, int fmt)
365 {
366     DWORD       ret;
367     TRACE("(%p,%u,%p,%d,%d,%d,%x)\n",ossdev,req_access,frag,strict_format,sample_rate,stereo,fmt);
368
369     if (ossdev->full_duplex && (req_access == O_RDONLY || req_access == O_WRONLY))
370         req_access = O_RDWR;
371
372     /* FIXME: this should be protected, and it also contains a race with OSS_CloseDevice */
373     if (ossdev->open_count == 0)
374     {
375         if (access(ossdev->dev_name, 0) != 0) return MMSYSERR_NODRIVER;
376
377         ossdev->audio_fragment = (frag) ? *frag : 0;
378         ossdev->sample_rate = sample_rate;
379         ossdev->stereo = stereo;
380         ossdev->format = fmt;
381         ossdev->open_access = req_access;
382         ossdev->owner_tid = GetCurrentThreadId();
383
384         if ((ret = OSS_RawOpenDevice(ossdev,strict_format)) != MMSYSERR_NOERROR) return ret;
385     }
386     else
387     {
388         /* check we really open with the same parameters */
389         if (ossdev->open_access != req_access)
390         {
391             ERR("FullDuplex: Mismatch in access. Your sound device is not full duplex capable.\n");
392             return WAVERR_BADFORMAT;
393         }
394
395         /* check if the audio parameters are the same */
396         if (ossdev->sample_rate != sample_rate ||
397             ossdev->stereo != stereo ||
398             ossdev->format != fmt)
399         {
400             /* This is not a fatal error because MSACM might do the remapping */ 
401             WARN("FullDuplex: mismatch in PCM parameters for input and output\n"
402                  "OSS doesn't allow us different parameters\n"
403                  "audio_frag(%x/%x) sample_rate(%d/%d) stereo(%d/%d) fmt(%d/%d)\n",
404                  ossdev->audio_fragment, frag ? *frag : 0,
405                  ossdev->sample_rate, sample_rate,
406                  ossdev->stereo, stereo,
407                  ossdev->format, fmt);
408             return WAVERR_BADFORMAT;
409         }
410         /* check if the fragment sizes are the same */
411         if (ossdev->audio_fragment != (frag ? *frag : 0) ) {
412             ERR("FullDuplex: Playback and Capture hardware acceleration levels are different.\n"
413                 "Use: \"HardwareAcceleration\" = \"Emulation\" in the [dsound] section of your config file.\n");
414             return WAVERR_BADFORMAT;
415         }
416         if (GetCurrentThreadId() != ossdev->owner_tid)
417         {
418             WARN("Another thread is trying to access audio...\n");
419             return MMSYSERR_ERROR;
420         }
421     }
422
423     ossdev->open_count++;
424
425     return MMSYSERR_NOERROR;
426 }
427
428 /******************************************************************
429  *              OSS_CloseDevice
430  *
431  *
432  */
433 static void     OSS_CloseDevice(OSS_DEVICE* ossdev)
434 {
435     TRACE("(%p)\n",ossdev);
436     if (ossdev->open_count>0) {
437         ossdev->open_count--;
438     } else {
439         WARN("OSS_CloseDevice called too many times\n");
440     }
441     if (ossdev->open_count == 0)
442     {
443        /* reset the device before we close it in case it is in a bad state */
444        ioctl(ossdev->fd, SNDCTL_DSP_RESET, 0);
445        close(ossdev->fd);
446     }
447 }
448
449 /******************************************************************
450  *              OSS_ResetDevice
451  *
452  * Resets the device. OSS Commercial requires the device to be closed
453  * after a SNDCTL_DSP_RESET ioctl call... this function implements
454  * this behavior...
455  * FIXME: This causes problems when doing full duplex so we really
456  * only reset when not doing full duplex. We need to do this better
457  * someday. 
458  */
459 static DWORD     OSS_ResetDevice(OSS_DEVICE* ossdev)
460 {
461     DWORD       ret = MMSYSERR_NOERROR;
462     int         old_fd = ossdev->fd;
463     TRACE("(%p)\n", ossdev);
464
465     if (ossdev->open_count == 1) {
466         if (ioctl(ossdev->fd, SNDCTL_DSP_RESET, NULL) == -1) 
467         {
468             perror("ioctl SNDCTL_DSP_RESET");
469             return -1;
470         }
471         close(ossdev->fd);
472         ret = OSS_RawOpenDevice(ossdev, 1);
473         TRACE("Changing fd from %d to %d\n", old_fd, ossdev->fd);
474     } else 
475         WARN("Not resetting device because it is in full duplex mode!\n");
476     
477     return ret;
478 }
479
480 const static int win_std_oss_fmts[2]={AFMT_U8,AFMT_S16_LE};
481 const static int win_std_rates[5]={96000,48000,44100,22050,11025};
482 const static int win_std_formats[2][2][5]=
483     {{{WAVE_FORMAT_96M08, WAVE_FORMAT_48M08, WAVE_FORMAT_4M08,
484        WAVE_FORMAT_2M08,  WAVE_FORMAT_1M08},
485       {WAVE_FORMAT_96S08, WAVE_FORMAT_48S08, WAVE_FORMAT_4S08,
486        WAVE_FORMAT_2S08,  WAVE_FORMAT_1S08}},
487      {{WAVE_FORMAT_96M16, WAVE_FORMAT_48M16, WAVE_FORMAT_4M16,
488        WAVE_FORMAT_2M16,  WAVE_FORMAT_1M16},
489       {WAVE_FORMAT_96S16, WAVE_FORMAT_48S16, WAVE_FORMAT_4S16,
490        WAVE_FORMAT_2S16,  WAVE_FORMAT_1S16}},
491     };
492
493 /******************************************************************
494  *              OSS_WaveOutInit
495  *
496  *
497  */
498 static BOOL OSS_WaveOutInit(OSS_DEVICE* ossdev)
499 {
500     int rc,arg;
501     int f,c,r;
502     TRACE("(%p) %s\n", ossdev, ossdev->dev_name);
503
504     if (OSS_OpenDevice(ossdev, O_WRONLY, NULL, 0,-1,-1,-1) != 0) return FALSE;
505     ioctl(ossdev->fd, SNDCTL_DSP_RESET, 0);
506
507 #ifdef SOUND_MIXER_INFO
508     {
509         int mixer;
510         if ((mixer = open(ossdev->mixer_name, O_RDONLY|O_NDELAY)) >= 0) {
511             mixer_info info;
512             if (ioctl(mixer, SOUND_MIXER_INFO, &info) >= 0) {
513                 close(mixer);
514                 strncpy(ossdev->ds_desc.szDesc, info.name, sizeof(info.name));
515                 strcpy(ossdev->ds_desc.szDrvName, "wineoss.drv");
516                 strncpy(ossdev->out_caps.szPname, info.name, sizeof(info.name));
517                 TRACE("%s\n", ossdev->ds_desc.szDesc);
518             } else {
519                 ERR("%s: can't read info!\n", ossdev->mixer_name);
520                 OSS_CloseDevice(ossdev);
521                 close(mixer);
522                 return FALSE;
523             }
524         } else {
525             ERR("%s: not found!\n", ossdev->mixer_name);
526             OSS_CloseDevice(ossdev);
527             return FALSE;
528         }
529     }
530 #endif /* SOUND_MIXER_INFO */
531
532     /* FIXME: some programs compare this string against the content of the
533      * registry for MM drivers. The names have to match in order for the
534      * program to work (e.g. MS win9x mplayer.exe)
535      */
536 #ifdef EMULATE_SB16
537     ossdev->out_caps.wMid = 0x0002;
538     ossdev->out_caps.wPid = 0x0104;
539     strcpy(ossdev->out_caps.szPname, "SB16 Wave Out");
540 #else
541     ossdev->out_caps.wMid = 0x00FF; /* Manufac ID */
542     ossdev->out_caps.wPid = 0x0001; /* Product ID */
543 #endif
544     ossdev->out_caps.vDriverVersion = 0x0100;
545     ossdev->out_caps.wChannels = 1;
546     ossdev->out_caps.dwFormats = 0x00000000;
547     ossdev->out_caps.wReserved1 = 0;
548     ossdev->out_caps.dwSupport = WAVECAPS_VOLUME;
549
550     /* direct sound caps */
551     ossdev->ds_caps.dwFlags = 0;
552     ossdev->ds_caps.dwPrimaryBuffers = 1;
553
554     if (WINE_TRACE_ON(wave)) {
555         /* Note that this only reports the formats supported by the hardware.
556          * The driver may support other formats and do the conversions in
557          * software which is why we don't use this value
558          */
559         int oss_mask;
560         ioctl(ossdev->fd, SNDCTL_DSP_GETFMTS, &oss_mask);
561         TRACE("OSS dsp out mask=%08x\n", oss_mask);
562     }
563
564     /* We must first set the format and the stereo mode as some sound cards
565      * may support 44kHz mono but not 44kHz stereo. Also we must
566      * systematically check the return value of these ioctls as they will
567      * always succeed (see OSS Linux) but will modify the parameter to match
568      * whatever they support. The OSS specs also say we must first set the
569      * sample size, then the stereo and then the sample rate.
570      */
571     for (f=0;f<2;f++) {
572         arg=win_std_oss_fmts[f];
573         rc=ioctl(ossdev->fd, SNDCTL_DSP_SAMPLESIZE, &arg);
574         if (rc!=0 || arg!=win_std_oss_fmts[f]) {
575             TRACE("DSP_SAMPLESIZE: rc=%d returned %d for %d\n",
576                   rc,arg,win_std_oss_fmts[f]);
577             continue;
578         }
579         if (f == 0) 
580             ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARY8BIT;
581         else if (f == 1)
582             ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARY16BIT;
583
584         for (c=0;c<2;c++) {
585             arg=c;
586             rc=ioctl(ossdev->fd, SNDCTL_DSP_STEREO, &arg);
587             if (rc!=0 || arg!=c) {
588                 TRACE("DSP_STEREO: rc=%d returned %d for %d\n",rc,arg,c);
589                 continue;
590             }
591             if (c == 0) {
592                 ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARYMONO;
593             } else if (c==1) {
594                 ossdev->out_caps.wChannels=2;
595                 ossdev->out_caps.dwSupport|=WAVECAPS_LRVOLUME;
596                 ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARYSTEREO;
597             }
598
599             for (r=0;r<sizeof(win_std_rates)/sizeof(*win_std_rates);r++) {
600                 arg=win_std_rates[r];
601                 rc=ioctl(ossdev->fd, SNDCTL_DSP_SPEED, &arg);
602                 TRACE("DSP_SPEED: rc=%d returned %d for %dx%dx%d\n",
603                       rc,arg,win_std_rates[r],win_std_oss_fmts[f],c+1);
604                 if (rc==0 && NEAR_MATCH(arg,win_std_rates[r]))
605                     ossdev->out_caps.dwFormats|=win_std_formats[f][c][r];
606             }
607         }
608     }
609
610     if (ioctl(ossdev->fd, SNDCTL_DSP_GETCAPS, &arg) == 0) {
611         TRACE("OSS dsp out caps=%08X\n", arg);
612         if (arg & DSP_CAP_TRIGGER)
613             ossdev->bTriggerSupport = TRUE;
614         if ((arg & DSP_CAP_REALTIME) && !(arg & DSP_CAP_BATCH)) {
615             ossdev->out_caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
616         }
617         /* well, might as well use the DirectSound cap flag for something */
618         if ((arg & DSP_CAP_TRIGGER) && (arg & DSP_CAP_MMAP) &&
619             !(arg & DSP_CAP_BATCH)) {
620             ossdev->out_caps.dwSupport |= WAVECAPS_DIRECTSOUND;
621         } else {
622             ossdev->ds_caps.dwFlags |= DSCAPS_EMULDRIVER;
623         }
624     }
625     OSS_CloseDevice(ossdev);
626     TRACE("out dwFormats = %08lX, dwSupport = %08lX\n",
627           ossdev->out_caps.dwFormats, ossdev->out_caps.dwSupport);
628     return TRUE;
629 }
630
631 /******************************************************************
632  *              OSS_WaveInInit
633  *
634  *
635  */
636 static BOOL OSS_WaveInInit(OSS_DEVICE* ossdev)
637 {
638     int rc,arg;
639     int f,c,r;
640     TRACE("(%p) %s\n", ossdev, ossdev->dev_name);
641
642     if (OSS_OpenDevice(ossdev, O_RDONLY, NULL, 0,-1,-1,-1) != 0) return FALSE;
643     ioctl(ossdev->fd, SNDCTL_DSP_RESET, 0);
644
645 #ifdef SOUND_MIXER_INFO
646     {
647         int mixer;
648         if ((mixer = open(ossdev->mixer_name, O_RDONLY|O_NDELAY)) >= 0) {
649             mixer_info info;
650             if (ioctl(mixer, SOUND_MIXER_INFO, &info) >= 0) {
651                 close(mixer);
652                 strncpy(ossdev->in_caps.szPname, info.name, sizeof(info.name));
653                 TRACE("%s\n", ossdev->ds_desc.szDesc);
654             } else {
655                 ERR("%s: can't read info!\n", ossdev->mixer_name);
656                 OSS_CloseDevice(ossdev);
657                 close(mixer);
658                 return FALSE;
659             }
660         } else {
661             ERR("%s: not found!\n", ossdev->mixer_name);
662             OSS_CloseDevice(ossdev);
663             return FALSE;
664         }
665     }
666 #endif /* SOUND_MIXER_INFO */
667
668     /* See comment in OSS_WaveOutInit */
669 #ifdef EMULATE_SB16
670     ossdev->in_caps.wMid = 0x0002;
671     ossdev->in_caps.wPid = 0x0004;
672     strcpy(ossdev->in_caps.szPname, "SB16 Wave In");
673 #else
674     ossdev->in_caps.wMid = 0x00FF; /* Manufac ID */
675     ossdev->in_caps.wPid = 0x0001; /* Product ID */
676 #endif
677     ossdev->in_caps.dwFormats = 0x00000000;
678     ossdev->in_caps.wChannels = 1;
679     ossdev->in_caps.wReserved1 = 0;
680
681     /* direct sound caps */
682     ossdev->dsc_caps.dwSize = sizeof(ossdev->dsc_caps);
683     ossdev->dsc_caps.dwFlags = 0;
684     ossdev->dsc_caps.dwFormats = 0x00000000;
685     ossdev->dsc_caps.dwChannels = 1;
686
687     if (WINE_TRACE_ON(wave)) {
688         /* Note that this only reports the formats supported by the hardware.
689          * The driver may support other formats and do the conversions in
690          * software which is why we don't use this value
691          */
692         int oss_mask;
693         ioctl(ossdev->fd, SNDCTL_DSP_GETFMTS, &oss_mask);
694         TRACE("OSS dsp out mask=%08x\n", oss_mask);
695     }
696
697     /* See the comment in OSS_WaveOutInit */
698     for (f=0;f<2;f++) {
699         arg=win_std_oss_fmts[f];
700         rc=ioctl(ossdev->fd, SNDCTL_DSP_SAMPLESIZE, &arg);
701         if (rc!=0 || arg!=win_std_oss_fmts[f]) {
702             TRACE("DSP_SAMPLESIZE: rc=%d returned 0x%x for 0x%x\n",
703                   rc,arg,win_std_oss_fmts[f]);
704             continue;
705         }
706
707         for (c=0;c<2;c++) {
708             arg=c;
709             rc=ioctl(ossdev->fd, SNDCTL_DSP_STEREO, &arg);
710             if (rc!=0 || arg!=c) {
711                 TRACE("DSP_STEREO: rc=%d returned %d for %d\n",rc,arg,c);
712                 continue;
713             }
714             if (c==1) {
715                 ossdev->in_caps.wChannels=2;
716                 ossdev->dsc_caps.dwChannels=2;
717             }
718
719             for (r=0;r<sizeof(win_std_rates)/sizeof(*win_std_rates);r++) {
720                 arg=win_std_rates[r];
721                 rc=ioctl(ossdev->fd, SNDCTL_DSP_SPEED, &arg);
722                 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);
723                 if (rc==0 && NEAR_MATCH(arg,win_std_rates[r]))
724                     ossdev->in_caps.dwFormats|=win_std_formats[f][c][r];
725                     ossdev->dsc_caps.dwFormats|=win_std_formats[f][c][r];
726             }
727         }
728     }
729
730     if (ioctl(ossdev->fd, SNDCTL_DSP_GETCAPS, &arg) == 0) {
731         TRACE("OSS dsp in caps=%08X\n", arg);
732         if (arg & DSP_CAP_TRIGGER)
733             ossdev->bTriggerSupport = TRUE;
734         if ((arg & DSP_CAP_TRIGGER) && (arg & DSP_CAP_MMAP) &&
735             !(arg & DSP_CAP_BATCH)) {
736             /* FIXME: enable the next statement if you want to work on the driver */
737 #if 0
738             ossdev->in_caps_support |= WAVECAPS_DIRECTSOUND;
739 #endif
740         }
741         if ((arg & DSP_CAP_REALTIME) && !(arg & DSP_CAP_BATCH))
742             ossdev->in_caps_support |= WAVECAPS_SAMPLEACCURATE;
743     }
744     OSS_CloseDevice(ossdev);
745     TRACE("in dwFormats = %08lX\n", ossdev->in_caps.dwFormats);
746     return TRUE;
747 }
748
749 /******************************************************************
750  *              OSS_WaveFullDuplexInit
751  *
752  *
753  */
754 static void OSS_WaveFullDuplexInit(OSS_DEVICE* ossdev)
755 {
756     int         caps;
757     TRACE("(%p)\n",ossdev);
758
759     if (OSS_OpenDevice(ossdev, O_RDWR, NULL, 0,-1,-1,-1) != 0) return;
760     if (ioctl(ossdev->fd, SNDCTL_DSP_GETCAPS, &caps) == 0)
761     {
762         ossdev->full_duplex = (caps & DSP_CAP_DUPLEX);
763     }
764     OSS_CloseDevice(ossdev);
765 }
766
767 #define INIT_GUID(guid, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8)      \
768         guid.Data1 = l; guid.Data2 = w1; guid.Data3 = w2;               \
769         guid.Data4[0] = b1; guid.Data4[1] = b2; guid.Data4[2] = b3;     \
770         guid.Data4[3] = b4; guid.Data4[4] = b5; guid.Data4[5] = b6;     \
771         guid.Data4[6] = b7; guid.Data4[7] = b8;
772 /******************************************************************
773  *              OSS_WaveInit
774  *
775  * Initialize internal structures from OSS information
776  */
777 LONG OSS_WaveInit(void)
778 {
779     int         i;
780     TRACE("()\n");
781
782     for (i = 0; i < MAX_WAVEDRV; ++i)
783     {
784         if (i == 0) {
785             sprintf((char *)OSS_Devices[i].dev_name, "/dev/dsp");
786             sprintf((char *)OSS_Devices[i].mixer_name, "/dev/mixer");
787         } else {
788             sprintf((char *)OSS_Devices[i].dev_name, "/dev/dsp%d", i);
789             sprintf((char *)OSS_Devices[i].mixer_name, "/dev/mixer%d", i);
790         }
791
792         INIT_GUID(OSS_Devices[i].ds_guid, 0xe437ebb6, 0x534f, 0x11ce, 0x9f, 0x53, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70 + i);
793         INIT_GUID(OSS_Devices[i].dsc_guid, 0xe437ebb6, 0x534f, 0x11ce, 0x9f, 0x53, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x80 + i);
794     }
795
796     /* start with output devices */
797     for (i = 0; i < MAX_WAVEDRV; ++i)
798     {
799         if (OSS_WaveOutInit(&OSS_Devices[i]))
800         {
801             WOutDev[numOutDev].state = WINE_WS_CLOSED;
802             WOutDev[numOutDev].ossdev = &OSS_Devices[i];
803             numOutDev++;
804         }
805     }
806
807     /* then do input devices */
808     for (i = 0; i < MAX_WAVEDRV; ++i)
809     {
810         if (OSS_WaveInInit(&OSS_Devices[i]))
811         {
812             WInDev[numInDev].state = WINE_WS_CLOSED;
813             WInDev[numInDev].ossdev = &OSS_Devices[i];
814             numInDev++;
815         }
816     }
817
818     /* finish with the full duplex bits */
819     for (i = 0; i < MAX_WAVEDRV; i++)
820         OSS_WaveFullDuplexInit(&OSS_Devices[i]);
821
822     return 0;
823 }
824
825 /******************************************************************
826  *              OSS_InitRingMessage
827  *
828  * Initialize the ring of messages for passing between driver's caller and playback/record
829  * thread
830  */
831 static int OSS_InitRingMessage(OSS_MSG_RING* omr)
832 {
833     omr->msg_toget = 0;
834     omr->msg_tosave = 0;
835 #ifdef USE_PIPE_SYNC
836     if (pipe(omr->msg_pipe) < 0) {
837         omr->msg_pipe[0] = -1;
838         omr->msg_pipe[1] = -1;
839         ERR("could not create pipe, error=%s\n", strerror(errno));
840     }
841 #else
842     omr->msg_event = CreateEventA(NULL, FALSE, FALSE, NULL);
843 #endif
844     memset(omr->messages, 0, sizeof(OSS_MSG) * OSS_RING_BUFFER_SIZE);
845     InitializeCriticalSection(&omr->msg_crst);
846     return 0;
847 }
848
849 /******************************************************************
850  *              OSS_DestroyRingMessage
851  *
852  */
853 static int OSS_DestroyRingMessage(OSS_MSG_RING* omr)
854 {
855 #ifdef USE_PIPE_SYNC
856     close(omr->msg_pipe[0]);
857     close(omr->msg_pipe[1]);
858 #else
859     CloseHandle(omr->msg_event);
860 #endif
861     DeleteCriticalSection(&omr->msg_crst);
862     return 0;
863 }
864
865 /******************************************************************
866  *              OSS_AddRingMessage
867  *
868  * Inserts a new message into the ring (should be called from DriverProc derivated routines)
869  */
870 static int OSS_AddRingMessage(OSS_MSG_RING* omr, enum win_wm_message msg, DWORD param, BOOL wait)
871 {
872     HANDLE      hEvent = INVALID_HANDLE_VALUE;
873
874     EnterCriticalSection(&omr->msg_crst);
875     if ((omr->msg_toget == ((omr->msg_tosave + 1) % OSS_RING_BUFFER_SIZE))) /* buffer overflow ? */
876     {
877         ERR("buffer overflow !?\n");
878         LeaveCriticalSection(&omr->msg_crst);
879         return 0;
880     }
881     if (wait)
882     {
883         hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
884         if (hEvent == INVALID_HANDLE_VALUE)
885         {
886             ERR("can't create event !?\n");
887             LeaveCriticalSection(&omr->msg_crst);
888             return 0;
889         }
890         if (omr->msg_toget != omr->msg_tosave && omr->messages[omr->msg_toget].msg != WINE_WM_HEADER)
891             FIXME("two fast messages in the queue!!!!\n");
892
893         /* fast messages have to be added at the start of the queue */
894         omr->msg_toget = (omr->msg_toget + OSS_RING_BUFFER_SIZE - 1) % OSS_RING_BUFFER_SIZE;
895
896         omr->messages[omr->msg_toget].msg = msg;
897         omr->messages[omr->msg_toget].param = param;
898         omr->messages[omr->msg_toget].hEvent = hEvent;
899     }
900     else
901     {
902         omr->messages[omr->msg_tosave].msg = msg;
903         omr->messages[omr->msg_tosave].param = param;
904         omr->messages[omr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
905         omr->msg_tosave = (omr->msg_tosave + 1) % OSS_RING_BUFFER_SIZE;
906     }
907     LeaveCriticalSection(&omr->msg_crst);
908     /* signal a new message */
909     SIGNAL_OMR(omr);
910     if (wait)
911     {
912         /* wait for playback/record thread to have processed the message */
913         WaitForSingleObject(hEvent, INFINITE);
914         CloseHandle(hEvent);
915     }
916     return 1;
917 }
918
919 /******************************************************************
920  *              OSS_RetrieveRingMessage
921  *
922  * Get a message from the ring. Should be called by the playback/record thread.
923  */
924 static int OSS_RetrieveRingMessage(OSS_MSG_RING* omr,
925                                    enum win_wm_message *msg, DWORD *param, HANDLE *hEvent)
926 {
927     EnterCriticalSection(&omr->msg_crst);
928
929     if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
930     {
931         LeaveCriticalSection(&omr->msg_crst);
932         return 0;
933     }
934
935     *msg = omr->messages[omr->msg_toget].msg;
936     omr->messages[omr->msg_toget].msg = 0;
937     *param = omr->messages[omr->msg_toget].param;
938     *hEvent = omr->messages[omr->msg_toget].hEvent;
939     omr->msg_toget = (omr->msg_toget + 1) % OSS_RING_BUFFER_SIZE;
940     CLEAR_OMR(omr);
941     LeaveCriticalSection(&omr->msg_crst);
942     return 1;
943 }
944
945 /******************************************************************
946  *              OSS_PeekRingMessage
947  *
948  * Peek at a message from the ring but do not remove it.
949  * Should be called by the playback/record thread.
950  */
951 static int OSS_PeekRingMessage(OSS_MSG_RING* omr,
952                                enum win_wm_message *msg,
953                                DWORD *param, HANDLE *hEvent)
954 {
955     EnterCriticalSection(&omr->msg_crst);
956
957     if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
958     {
959         LeaveCriticalSection(&omr->msg_crst);
960         return 0;
961     }
962
963     *msg = omr->messages[omr->msg_toget].msg;
964     *param = omr->messages[omr->msg_toget].param;
965     *hEvent = omr->messages[omr->msg_toget].hEvent;
966     LeaveCriticalSection(&omr->msg_crst);
967     return 1;
968 }
969
970 /*======================================================================*
971  *                  Low level WAVE OUT implementation                   *
972  *======================================================================*/
973
974 /**************************************************************************
975  *                      wodNotifyClient                 [internal]
976  */
977 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
978 {
979     TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
980
981     switch (wMsg) {
982     case WOM_OPEN:
983     case WOM_CLOSE:
984     case WOM_DONE:
985         if (wwo->wFlags != DCB_NULL &&
986             !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
987                             (HDRVR)wwo->waveDesc.hWave, wMsg,
988                             wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
989             WARN("can't notify client !\n");
990             return MMSYSERR_ERROR;
991         }
992         break;
993     default:
994         FIXME("Unknown callback message %u\n", wMsg);
995         return MMSYSERR_INVALPARAM;
996     }
997     return MMSYSERR_NOERROR;
998 }
999
1000 /**************************************************************************
1001  *                              wodUpdatePlayedTotal    [internal]
1002  *
1003  */
1004 static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo, audio_buf_info* info)
1005 {
1006     audio_buf_info dspspace;
1007     if (!info) info = &dspspace;
1008
1009     if (ioctl(wwo->ossdev->fd, SNDCTL_DSP_GETOSPACE, info) < 0) {
1010         ERR("ioctl(%s, SNDCTL_DSP_GETOSPACE) failed (%s)\n", wwo->ossdev->dev_name, strerror(errno));
1011         return FALSE;
1012     }
1013     wwo->dwPlayedTotal = wwo->dwWrittenTotal - (wwo->dwBufferSize - info->bytes);
1014     return TRUE;
1015 }
1016
1017 /**************************************************************************
1018  *                              wodPlayer_BeginWaveHdr          [internal]
1019  *
1020  * Makes the specified lpWaveHdr the currently playing wave header.
1021  * If the specified wave header is a begin loop and we're not already in
1022  * a loop, setup the loop.
1023  */
1024 static void wodPlayer_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1025 {
1026     wwo->lpPlayPtr = lpWaveHdr;
1027
1028     if (!lpWaveHdr) return;
1029
1030     if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
1031         if (wwo->lpLoopPtr) {
1032             WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1033         } else {
1034             TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1035             wwo->lpLoopPtr = lpWaveHdr;
1036             /* Windows does not touch WAVEHDR.dwLoops,
1037              * so we need to make an internal copy */
1038             wwo->dwLoops = lpWaveHdr->dwLoops;
1039         }
1040     }
1041     wwo->dwPartialOffset = 0;
1042 }
1043
1044 /**************************************************************************
1045  *                              wodPlayer_PlayPtrNext           [internal]
1046  *
1047  * Advance the play pointer to the next waveheader, looping if required.
1048  */
1049 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEOUT* wwo)
1050 {
1051     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1052
1053     wwo->dwPartialOffset = 0;
1054     if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
1055         /* We're at the end of a loop, loop if required */
1056         if (--wwo->dwLoops > 0) {
1057             wwo->lpPlayPtr = wwo->lpLoopPtr;
1058         } else {
1059             /* Handle overlapping loops correctly */
1060             if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
1061                 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
1062                 /* shall we consider the END flag for the closing loop or for
1063                  * the opening one or for both ???
1064                  * code assumes for closing loop only
1065                  */
1066             } else {
1067                 lpWaveHdr = lpWaveHdr->lpNext;
1068             }
1069             wwo->lpLoopPtr = NULL;
1070             wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
1071         }
1072     } else {
1073         /* We're not in a loop.  Advance to the next wave header */
1074         wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
1075     }
1076
1077     return lpWaveHdr;
1078 }
1079
1080 /**************************************************************************
1081  *                           wodPlayer_DSPWait                  [internal]
1082  * Returns the number of milliseconds to wait for the DSP buffer to write
1083  * one fragment.
1084  */
1085 static DWORD wodPlayer_DSPWait(const WINE_WAVEOUT *wwo)
1086 {
1087     /* time for one fragment to be played */
1088     return wwo->dwFragmentSize * 1000 / wwo->format.wf.nAvgBytesPerSec;
1089 }
1090
1091 /**************************************************************************
1092  *                           wodPlayer_NotifyWait               [internal]
1093  * Returns the number of milliseconds to wait before attempting to notify
1094  * completion of the specified wavehdr.
1095  * This is based on the number of bytes remaining to be written in the
1096  * wave.
1097  */
1098 static DWORD wodPlayer_NotifyWait(const WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1099 {
1100     DWORD dwMillis;
1101
1102     if (lpWaveHdr->reserved < wwo->dwPlayedTotal) {
1103         dwMillis = 1;
1104     } else {
1105         dwMillis = (lpWaveHdr->reserved - wwo->dwPlayedTotal) * 1000 / wwo->format.wf.nAvgBytesPerSec;
1106         if (!dwMillis) dwMillis = 1;
1107     }
1108
1109     return dwMillis;
1110 }
1111
1112
1113 /**************************************************************************
1114  *                           wodPlayer_WriteMaxFrags            [internal]
1115  * Writes the maximum number of bytes possible to the DSP and returns
1116  * TRUE iff the current playPtr has been fully played
1117  */
1118 static BOOL wodPlayer_WriteMaxFrags(WINE_WAVEOUT* wwo, DWORD* bytes)
1119 {
1120     DWORD       dwLength = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
1121     DWORD       toWrite = min(dwLength, *bytes);
1122     int         written;
1123     BOOL        ret = FALSE;
1124
1125     TRACE("Writing wavehdr %p.%lu[%lu]/%lu\n",
1126           wwo->lpPlayPtr, wwo->dwPartialOffset, wwo->lpPlayPtr->dwBufferLength, toWrite);
1127
1128     if (toWrite > 0)
1129     {
1130         written = write(wwo->ossdev->fd, wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toWrite);
1131         if (written <= 0) return FALSE;
1132     }
1133     else
1134         written = 0;
1135
1136     if (written >= dwLength) {
1137         /* If we wrote all current wavehdr, skip to the next one */
1138         wodPlayer_PlayPtrNext(wwo);
1139         ret = TRUE;
1140     } else {
1141         /* Remove the amount written */
1142         wwo->dwPartialOffset += written;
1143     }
1144     *bytes -= written;
1145     wwo->dwWrittenTotal += written;
1146
1147     return ret;
1148 }
1149
1150
1151 /**************************************************************************
1152  *                              wodPlayer_NotifyCompletions     [internal]
1153  *
1154  * Notifies and remove from queue all wavehdrs which have been played to
1155  * the speaker (ie. they have cleared the OSS buffer).  If force is true,
1156  * we notify all wavehdrs and remove them all from the queue even if they
1157  * are unplayed or part of a loop.
1158  */
1159 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1160 {
1161     LPWAVEHDR           lpWaveHdr;
1162
1163     /* Start from lpQueuePtr and keep notifying until:
1164      * - we hit an unwritten wavehdr
1165      * - we hit the beginning of a running loop
1166      * - we hit a wavehdr which hasn't finished playing
1167      */
1168     while ((lpWaveHdr = wwo->lpQueuePtr) &&
1169            (force ||
1170             (lpWaveHdr != wwo->lpPlayPtr &&
1171              lpWaveHdr != wwo->lpLoopPtr &&
1172              lpWaveHdr->reserved <= wwo->dwPlayedTotal))) {
1173
1174         wwo->lpQueuePtr = lpWaveHdr->lpNext;
1175
1176         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1177         lpWaveHdr->dwFlags |= WHDR_DONE;
1178
1179         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1180     }
1181     return  (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
1182         wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
1183 }
1184
1185 /**************************************************************************
1186  *                              wodPlayer_Reset                 [internal]
1187  *
1188  * wodPlayer helper. Resets current output stream.
1189  */
1190 static  void    wodPlayer_Reset(WINE_WAVEOUT* wwo, BOOL reset)
1191 {
1192     wodUpdatePlayedTotal(wwo, NULL);
1193     /* updates current notify list */
1194     wodPlayer_NotifyCompletions(wwo, FALSE);
1195
1196     /* flush all possible output */
1197     if (OSS_ResetDevice(wwo->ossdev) != MMSYSERR_NOERROR)
1198     {
1199         wwo->hThread = 0;
1200         wwo->state = WINE_WS_STOPPED;
1201         ExitThread(-1);
1202     }
1203
1204     if (reset) {
1205         enum win_wm_message     msg;
1206         DWORD                   param;
1207         HANDLE                  ev;
1208
1209         /* remove any buffer */
1210         wodPlayer_NotifyCompletions(wwo, TRUE);
1211
1212         wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1213         wwo->state = WINE_WS_STOPPED;
1214         wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1215         /* Clear partial wavehdr */
1216         wwo->dwPartialOffset = 0;
1217
1218         /* remove any existing message in the ring */
1219         EnterCriticalSection(&wwo->msgRing.msg_crst);
1220         /* return all pending headers in queue */
1221         while (OSS_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
1222         {
1223             if (msg != WINE_WM_HEADER)
1224             {
1225                 FIXME("shouldn't have headers left\n");
1226                 SetEvent(ev);
1227                 continue;
1228             }
1229             ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
1230             ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
1231
1232             wodNotifyClient(wwo, WOM_DONE, param, 0);
1233         }
1234         RESET_OMR(&wwo->msgRing);
1235         LeaveCriticalSection(&wwo->msgRing.msg_crst);
1236     } else {
1237         if (wwo->lpLoopPtr) {
1238             /* complicated case, not handled yet (could imply modifying the loop counter */
1239             FIXME("Pausing while in loop isn't correctly handled yet, except strange results\n");
1240             wwo->lpPlayPtr = wwo->lpLoopPtr;
1241             wwo->dwPartialOffset = 0;
1242             wwo->dwWrittenTotal = wwo->dwPlayedTotal; /* this is wrong !!! */
1243         } else {
1244             LPWAVEHDR   ptr;
1245             DWORD       sz = wwo->dwPartialOffset;
1246
1247             /* reset all the data as if we had written only up to lpPlayedTotal bytes */
1248             /* compute the max size playable from lpQueuePtr */
1249             for (ptr = wwo->lpQueuePtr; ptr != wwo->lpPlayPtr; ptr = ptr->lpNext) {
1250                 sz += ptr->dwBufferLength;
1251             }
1252             /* because the reset lpPlayPtr will be lpQueuePtr */
1253             if (wwo->dwWrittenTotal > wwo->dwPlayedTotal + sz) ERR("grin\n");
1254             wwo->dwPartialOffset = sz - (wwo->dwWrittenTotal - wwo->dwPlayedTotal);
1255             wwo->dwWrittenTotal = wwo->dwPlayedTotal;
1256             wwo->lpPlayPtr = wwo->lpQueuePtr;
1257         }
1258         wwo->state = WINE_WS_PAUSED;
1259     }
1260 }
1261
1262 /**************************************************************************
1263  *                    wodPlayer_ProcessMessages                 [internal]
1264  */
1265 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
1266 {
1267     LPWAVEHDR           lpWaveHdr;
1268     enum win_wm_message msg;
1269     DWORD               param;
1270     HANDLE              ev;
1271
1272     while (OSS_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
1273         TRACE("Received %s %lx\n", wodPlayerCmdString[msg - WM_USER - 1], param);
1274         switch (msg) {
1275         case WINE_WM_PAUSING:
1276             wodPlayer_Reset(wwo, FALSE);
1277             SetEvent(ev);
1278             break;
1279         case WINE_WM_RESTARTING:
1280             if (wwo->state == WINE_WS_PAUSED)
1281             {
1282                 wwo->state = WINE_WS_PLAYING;
1283             }
1284             SetEvent(ev);
1285             break;
1286         case WINE_WM_HEADER:
1287             lpWaveHdr = (LPWAVEHDR)param;
1288
1289             /* insert buffer at the end of queue */
1290             {
1291                 LPWAVEHDR*      wh;
1292                 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1293                 *wh = lpWaveHdr;
1294             }
1295             if (!wwo->lpPlayPtr)
1296                 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
1297             if (wwo->state == WINE_WS_STOPPED)
1298                 wwo->state = WINE_WS_PLAYING;
1299             break;
1300         case WINE_WM_RESETTING:
1301             wodPlayer_Reset(wwo, TRUE);
1302             SetEvent(ev);
1303             break;
1304         case WINE_WM_UPDATE:
1305             wodUpdatePlayedTotal(wwo, NULL);
1306             SetEvent(ev);
1307             break;
1308         case WINE_WM_BREAKLOOP:
1309             if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
1310                 /* ensure exit at end of current loop */
1311                 wwo->dwLoops = 1;
1312             }
1313             SetEvent(ev);
1314             break;
1315         case WINE_WM_CLOSING:
1316             /* sanity check: this should not happen since the device must have been reset before */
1317             if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1318             wwo->hThread = 0;
1319             wwo->state = WINE_WS_CLOSED;
1320             SetEvent(ev);
1321             ExitThread(0);
1322             /* shouldn't go here */
1323         default:
1324             FIXME("unknown message %d\n", msg);
1325             break;
1326         }
1327     }
1328 }
1329
1330 /**************************************************************************
1331  *                           wodPlayer_FeedDSP                  [internal]
1332  * Feed as much sound data as we can into the DSP and return the number of
1333  * milliseconds before it will be necessary to feed the DSP again.
1334  */
1335 static DWORD wodPlayer_FeedDSP(WINE_WAVEOUT* wwo)
1336 {
1337     audio_buf_info dspspace;
1338     DWORD       availInQ;
1339
1340     wodUpdatePlayedTotal(wwo, &dspspace);
1341     availInQ = dspspace.bytes;
1342     TRACE("fragments=%d/%d, fragsize=%d, bytes=%d\n",
1343           dspspace.fragments, dspspace.fragstotal, dspspace.fragsize, dspspace.bytes);
1344
1345     /* input queue empty and output buffer with less than one fragment to play 
1346      * actually some cards do not play the fragment before the last if this one is partially feed
1347      * so we need to test for full the availability of 2 fragments
1348      */
1349     if (!wwo->lpPlayPtr && wwo->dwBufferSize < availInQ + 2 * wwo->dwFragmentSize && 
1350         !wwo->bNeedPost) {
1351         TRACE("Run out of wavehdr:s...\n");
1352         return INFINITE;
1353     }
1354
1355     /* no more room... no need to try to feed */
1356     if (dspspace.fragments != 0) {
1357         /* Feed from partial wavehdr */
1358         if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0) {
1359             wodPlayer_WriteMaxFrags(wwo, &availInQ);
1360         }
1361
1362         /* Feed wavehdrs until we run out of wavehdrs or DSP space */
1363         if (wwo->dwPartialOffset == 0 && wwo->lpPlayPtr) {
1364             do {
1365                 TRACE("Setting time to elapse for %p to %lu\n",
1366                       wwo->lpPlayPtr, wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength);
1367                 /* note the value that dwPlayedTotal will return when this wave finishes playing */
1368                 wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
1369             } while (wodPlayer_WriteMaxFrags(wwo, &availInQ) && wwo->lpPlayPtr && availInQ > 0);
1370         }
1371
1372         if (wwo->bNeedPost) {
1373             /* OSS doesn't start before it gets either 2 fragments or a SNDCTL_DSP_POST;
1374              * if it didn't get one, we give it the other */
1375             if (wwo->dwBufferSize < availInQ + 2 * wwo->dwFragmentSize)
1376                 ioctl(wwo->ossdev->fd, SNDCTL_DSP_POST, 0);
1377             wwo->bNeedPost = FALSE;
1378         }
1379     }
1380
1381     return wodPlayer_DSPWait(wwo);
1382 }
1383
1384
1385 /**************************************************************************
1386  *                              wodPlayer                       [internal]
1387  */
1388 static  DWORD   CALLBACK        wodPlayer(LPVOID pmt)
1389 {
1390     WORD          uDevID = (DWORD)pmt;
1391     WINE_WAVEOUT* wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
1392     DWORD         dwNextFeedTime = INFINITE;   /* Time before DSP needs feeding */
1393     DWORD         dwNextNotifyTime = INFINITE; /* Time before next wave completion */
1394     DWORD         dwSleepTime;
1395
1396     wwo->state = WINE_WS_STOPPED;
1397     SetEvent(wwo->hStartUpEvent);
1398
1399     for (;;) {
1400         /** Wait for the shortest time before an action is required.  If there
1401          *  are no pending actions, wait forever for a command.
1402          */
1403         dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
1404         TRACE("waiting %lums (%lu,%lu)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
1405         WAIT_OMR(&wwo->msgRing, dwSleepTime);
1406         wodPlayer_ProcessMessages(wwo);
1407         if (wwo->state == WINE_WS_PLAYING) {
1408             dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1409             dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1410             if (dwNextFeedTime == INFINITE) {
1411                 /* FeedDSP ran out of data, but before flushing, */
1412                 /* check that a notification didn't give us more */
1413                 wodPlayer_ProcessMessages(wwo);
1414                 if (!wwo->lpPlayPtr) {
1415                     TRACE("flushing\n");
1416                     ioctl(wwo->ossdev->fd, SNDCTL_DSP_SYNC, 0);
1417                     wwo->dwPlayedTotal = wwo->dwWrittenTotal;
1418                     dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1419                 } else {
1420                     TRACE("recovering\n");
1421                     dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1422                 }
1423             }
1424         } else {
1425             dwNextFeedTime = dwNextNotifyTime = INFINITE;
1426         }
1427     }
1428 }
1429
1430 /**************************************************************************
1431  *                      wodGetDevCaps                           [internal]
1432  */
1433 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSA lpCaps, DWORD dwSize)
1434 {
1435     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1436
1437     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1438
1439     if (wDevID >= numOutDev) {
1440         TRACE("numOutDev reached !\n");
1441         return MMSYSERR_BADDEVICEID;
1442     }
1443
1444     memcpy(lpCaps, &WOutDev[wDevID].ossdev->out_caps, min(dwSize, sizeof(*lpCaps)));
1445     return MMSYSERR_NOERROR;
1446 }
1447
1448 /**************************************************************************
1449  *                              wodOpen                         [internal]
1450  */
1451 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1452 {
1453     int                 audio_fragment;
1454     WINE_WAVEOUT*       wwo;
1455     audio_buf_info      info;
1456     DWORD               ret;
1457
1458     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
1459     if (lpDesc == NULL) {
1460         WARN("Invalid Parameter !\n");
1461         return MMSYSERR_INVALPARAM;
1462     }
1463     if (wDevID >= numOutDev) {
1464         TRACE("MAX_WAVOUTDRV reached !\n");
1465         return MMSYSERR_BADDEVICEID;
1466     }
1467
1468     /* only PCM format is supported so far... */
1469     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1470         lpDesc->lpFormat->nChannels == 0 ||
1471         lpDesc->lpFormat->nSamplesPerSec == 0) {
1472         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1473              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1474              lpDesc->lpFormat->nSamplesPerSec);
1475         return WAVERR_BADFORMAT;
1476     }
1477
1478     if (dwFlags & WAVE_FORMAT_QUERY) {
1479         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1480              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1481              lpDesc->lpFormat->nSamplesPerSec);
1482         return MMSYSERR_NOERROR;
1483     }
1484
1485     wwo = &WOutDev[wDevID];
1486
1487     if ((dwFlags & WAVE_DIRECTSOUND) && 
1488         !(wwo->ossdev->out_caps.dwSupport & WAVECAPS_DIRECTSOUND))
1489         /* not supported, ignore it */
1490         dwFlags &= ~WAVE_DIRECTSOUND;
1491
1492     if (dwFlags & WAVE_DIRECTSOUND) {
1493         if (wwo->ossdev->out_caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
1494             /* we have realtime DirectSound, fragments just waste our time,
1495              * but a large buffer is good, so choose 64KB (32 * 2^11) */
1496             audio_fragment = 0x0020000B;
1497         else
1498             /* to approximate realtime, we must use small fragments,
1499              * let's try to fragment the above 64KB (256 * 2^8) */
1500             audio_fragment = 0x01000008;
1501     } else {
1502         /* shockwave player uses only 4 1k-fragments at a rate of 22050 bytes/sec
1503          * thus leading to 46ms per fragment, and a turnaround time of 185ms
1504          */
1505         /* 16 fragments max, 2^10=1024 bytes per fragment */
1506         audio_fragment = 0x000F000A;
1507     }
1508     if (wwo->state != WINE_WS_CLOSED) return MMSYSERR_ALLOCATED;
1509     /* we want to be able to mmap() the device, which means it must be opened readable,
1510      * otherwise mmap() will fail (at least under Linux) */
1511     ret = OSS_OpenDevice(wwo->ossdev,
1512                          (dwFlags & WAVE_DIRECTSOUND) ? O_RDWR : O_WRONLY,
1513                          &audio_fragment,
1514                          (dwFlags & WAVE_DIRECTSOUND) ? 0 : 1,
1515                          lpDesc->lpFormat->nSamplesPerSec,
1516                          (lpDesc->lpFormat->nChannels > 1) ? 1 : 0,
1517                          (lpDesc->lpFormat->wBitsPerSample == 16)
1518                              ? AFMT_S16_LE : AFMT_U8);
1519     if ((ret==MMSYSERR_NOERROR) && (dwFlags & WAVE_DIRECTSOUND)) {
1520         lpDesc->lpFormat->nSamplesPerSec=wwo->ossdev->sample_rate;
1521         lpDesc->lpFormat->nChannels=(wwo->ossdev->stereo ? 2 : 1);
1522         lpDesc->lpFormat->wBitsPerSample=(wwo->ossdev->format == AFMT_U8 ? 8 : 16);
1523         lpDesc->lpFormat->nBlockAlign=lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
1524         lpDesc->lpFormat->nAvgBytesPerSec=lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
1525         TRACE("OSS_OpenDevice returned this format: %ldx%dx%d\n",
1526               lpDesc->lpFormat->nSamplesPerSec,
1527               lpDesc->lpFormat->wBitsPerSample,
1528               lpDesc->lpFormat->nChannels);
1529     }
1530     if (ret != 0) return ret;
1531     wwo->state = WINE_WS_STOPPED;
1532
1533     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1534
1535     memcpy(&wwo->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
1536     memcpy(&wwo->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1537
1538     if (wwo->format.wBitsPerSample == 0) {
1539         WARN("Resetting zeroed wBitsPerSample\n");
1540         wwo->format.wBitsPerSample = 8 *
1541             (wwo->format.wf.nAvgBytesPerSec /
1542              wwo->format.wf.nSamplesPerSec) /
1543             wwo->format.wf.nChannels;
1544     }
1545     /* Read output space info for future reference */
1546     if (ioctl(wwo->ossdev->fd, SNDCTL_DSP_GETOSPACE, &info) < 0) {
1547         ERR("ioctl(%s, SNDCTL_DSP_GETOSPACE) failed (%s)\n", wwo->ossdev->dev_name, strerror(errno));
1548         OSS_CloseDevice(wwo->ossdev);
1549         wwo->state = WINE_WS_CLOSED;
1550         return MMSYSERR_NOTENABLED;
1551     }
1552
1553     /* Check that fragsize is correct per our settings above */
1554     if ((info.fragsize > 1024) && (LOWORD(audio_fragment) <= 10)) {
1555         /* we've tried to set 1K fragments or less, but it didn't work */
1556         ERR("fragment size set failed, size is now %d\n", info.fragsize);
1557         MESSAGE("Your Open Sound System driver did not let us configure small enough sound fragments.\n");
1558         MESSAGE("This may cause delays and other problems in audio playback with certain applications.\n");
1559     }
1560
1561     /* Remember fragsize and total buffer size for future use */
1562     wwo->dwFragmentSize = info.fragsize;
1563     wwo->dwBufferSize = info.fragstotal * info.fragsize;
1564     wwo->dwPlayedTotal = 0;
1565     wwo->dwWrittenTotal = 0;
1566     wwo->bNeedPost = TRUE;
1567
1568     OSS_InitRingMessage(&wwo->msgRing);
1569
1570     wwo->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
1571     wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
1572     WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
1573     CloseHandle(wwo->hStartUpEvent);
1574     wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
1575
1576     TRACE("fd=%d fragmentSize=%ld\n",
1577           wwo->ossdev->fd, wwo->dwFragmentSize);
1578     if (wwo->dwFragmentSize % wwo->format.wf.nBlockAlign)
1579         ERR("Fragment doesn't contain an integral number of data blocks\n");
1580
1581     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
1582           wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec,
1583           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
1584           wwo->format.wf.nBlockAlign);
1585
1586     return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
1587 }
1588
1589 /**************************************************************************
1590  *                              wodClose                        [internal]
1591  */
1592 static DWORD wodClose(WORD wDevID)
1593 {
1594     DWORD               ret = MMSYSERR_NOERROR;
1595     WINE_WAVEOUT*       wwo;
1596
1597     TRACE("(%u);\n", wDevID);
1598
1599     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
1600         WARN("bad device ID !\n");
1601         return MMSYSERR_BADDEVICEID;
1602     }
1603
1604     wwo = &WOutDev[wDevID];
1605     if (wwo->lpQueuePtr) {
1606         WARN("buffers still playing !\n");
1607         ret = WAVERR_STILLPLAYING;
1608     } else {
1609         if (wwo->hThread != INVALID_HANDLE_VALUE) {
1610             OSS_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1611         }
1612         if (wwo->mapping) {
1613             munmap(wwo->mapping, wwo->maplen);
1614             wwo->mapping = NULL;
1615         }
1616
1617         OSS_DestroyRingMessage(&wwo->msgRing);
1618
1619         OSS_CloseDevice(wwo->ossdev);
1620         wwo->state = WINE_WS_CLOSED;
1621         wwo->dwFragmentSize = 0;
1622         ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1623     }
1624     return ret;
1625 }
1626
1627 /**************************************************************************
1628  *                              wodWrite                        [internal]
1629  *
1630  */
1631 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1632 {
1633     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1634
1635     /* first, do the sanity checks... */
1636     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
1637         WARN("bad dev ID !\n");
1638         return MMSYSERR_BADDEVICEID;
1639     }
1640
1641     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1642         return WAVERR_UNPREPARED;
1643
1644     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1645         return WAVERR_STILLPLAYING;
1646
1647     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1648     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1649     lpWaveHdr->lpNext = 0;
1650
1651     if ((lpWaveHdr->dwBufferLength & (WOutDev[wDevID].format.wf.nBlockAlign - 1)) != 0)
1652     {
1653         WARN("WaveHdr length isn't a multiple of the PCM block size: %ld %% %d\n",lpWaveHdr->dwBufferLength,WOutDev[wDevID].format.wf.nBlockAlign);
1654         lpWaveHdr->dwBufferLength &= ~(WOutDev[wDevID].format.wf.nBlockAlign - 1);
1655     }
1656
1657     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1658
1659     return MMSYSERR_NOERROR;
1660 }
1661
1662 /**************************************************************************
1663  *                              wodPrepare                      [internal]
1664  */
1665 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1666 {
1667     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1668
1669     if (wDevID >= numOutDev) {
1670         WARN("bad device ID !\n");
1671         return MMSYSERR_BADDEVICEID;
1672     }
1673
1674     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1675         return WAVERR_STILLPLAYING;
1676
1677     lpWaveHdr->dwFlags |= WHDR_PREPARED;
1678     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1679     return MMSYSERR_NOERROR;
1680 }
1681
1682 /**************************************************************************
1683  *                              wodUnprepare                    [internal]
1684  */
1685 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1686 {
1687     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1688
1689     if (wDevID >= numOutDev) {
1690         WARN("bad device ID !\n");
1691         return MMSYSERR_BADDEVICEID;
1692     }
1693
1694     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1695         return WAVERR_STILLPLAYING;
1696
1697     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1698     lpWaveHdr->dwFlags |= WHDR_DONE;
1699
1700     return MMSYSERR_NOERROR;
1701 }
1702
1703 /**************************************************************************
1704  *                      wodPause                                [internal]
1705  */
1706 static DWORD wodPause(WORD wDevID)
1707 {
1708     TRACE("(%u);!\n", wDevID);
1709
1710     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
1711         WARN("bad device ID !\n");
1712         return MMSYSERR_BADDEVICEID;
1713     }
1714
1715     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1716
1717     return MMSYSERR_NOERROR;
1718 }
1719
1720 /**************************************************************************
1721  *                      wodRestart                              [internal]
1722  */
1723 static DWORD wodRestart(WORD wDevID)
1724 {
1725     TRACE("(%u);\n", wDevID);
1726
1727     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
1728         WARN("bad device ID !\n");
1729         return MMSYSERR_BADDEVICEID;
1730     }
1731
1732     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1733
1734     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1735     /* FIXME: Myst crashes with this ... hmm -MM
1736        return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1737     */
1738
1739     return MMSYSERR_NOERROR;
1740 }
1741
1742 /**************************************************************************
1743  *                      wodReset                                [internal]
1744  */
1745 static DWORD wodReset(WORD wDevID)
1746 {
1747     TRACE("(%u);\n", wDevID);
1748
1749     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
1750         WARN("bad device ID !\n");
1751         return MMSYSERR_BADDEVICEID;
1752     }
1753
1754     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1755
1756     return MMSYSERR_NOERROR;
1757 }
1758
1759 /**************************************************************************
1760  *                              wodGetPosition                  [internal]
1761  */
1762 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1763 {
1764     int                 time;
1765     DWORD               val;
1766     WINE_WAVEOUT*       wwo;
1767
1768     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1769
1770     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
1771         WARN("bad device ID !\n");
1772         return MMSYSERR_BADDEVICEID;
1773     }
1774
1775     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1776
1777     wwo = &WOutDev[wDevID];
1778 #ifdef EXACT_WODPOSITION
1779     OSS_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1780 #endif
1781     val = wwo->dwPlayedTotal;
1782
1783     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
1784           lpTime->wType, wwo->format.wBitsPerSample,
1785           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
1786           wwo->format.wf.nAvgBytesPerSec);
1787     TRACE("dwPlayedTotal=%lu\n", val);
1788
1789     switch (lpTime->wType) {
1790     case TIME_BYTES:
1791         lpTime->u.cb = val;
1792         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
1793         break;
1794     case TIME_SAMPLES:
1795         lpTime->u.sample = val * 8 / wwo->format.wBitsPerSample /wwo->format.wf.nChannels;
1796         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
1797         break;
1798     case TIME_SMPTE:
1799         time = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1800         lpTime->u.smpte.hour = time / 108000;
1801         time -= lpTime->u.smpte.hour * 108000;
1802         lpTime->u.smpte.min = time / 1800;
1803         time -= lpTime->u.smpte.min * 1800;
1804         lpTime->u.smpte.sec = time / 30;
1805         time -= lpTime->u.smpte.sec * 30;
1806         lpTime->u.smpte.frame = time;
1807         lpTime->u.smpte.fps = 30;
1808         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
1809               lpTime->u.smpte.hour, lpTime->u.smpte.min,
1810               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
1811         break;
1812     default:
1813         FIXME("Format %d not supported ! use TIME_MS !\n", lpTime->wType);
1814         lpTime->wType = TIME_MS;
1815     case TIME_MS:
1816         lpTime->u.ms = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1817         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
1818         break;
1819     }
1820     return MMSYSERR_NOERROR;
1821 }
1822
1823 /**************************************************************************
1824  *                              wodBreakLoop                    [internal]
1825  */
1826 static DWORD wodBreakLoop(WORD wDevID)
1827 {
1828     TRACE("(%u);\n", wDevID);
1829
1830     if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
1831         WARN("bad device ID !\n");
1832         return MMSYSERR_BADDEVICEID;
1833     }
1834     OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
1835     return MMSYSERR_NOERROR;
1836 }
1837
1838 /**************************************************************************
1839  *                              wodGetVolume                    [internal]
1840  */
1841 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1842 {
1843     int         mixer;
1844     int         volume;
1845     DWORD       left, right;
1846
1847     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1848
1849     if (lpdwVol == NULL)
1850         return MMSYSERR_NOTENABLED;
1851     if (wDevID >= numOutDev) 
1852         return MMSYSERR_INVALPARAM;
1853
1854     if ((mixer = open(WOutDev[wDevID].ossdev->mixer_name, O_RDONLY|O_NDELAY)) < 0) {
1855         WARN("mixer device not available !\n");
1856         return MMSYSERR_NOTENABLED;
1857     }
1858     if (ioctl(mixer, SOUND_MIXER_READ_PCM, &volume) == -1) {
1859         WARN("ioctl(%s, SOUND_MIXER_READ_PCM) failed (%s)n", WOutDev[wDevID].ossdev->mixer_name, strerror(errno));
1860         return MMSYSERR_NOTENABLED;
1861     }
1862     close(mixer);
1863     left = LOBYTE(volume);
1864     right = HIBYTE(volume);
1865     TRACE("left=%ld right=%ld !\n", left, right);
1866     *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) << 16);
1867     return MMSYSERR_NOERROR;
1868 }
1869
1870 /**************************************************************************
1871  *                              wodSetVolume                    [internal]
1872  */
1873 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1874 {
1875     int         mixer;
1876     int         volume;
1877     DWORD       left, right;
1878
1879     TRACE("(%u, %08lX);\n", wDevID, dwParam);
1880
1881     left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
1882     right = (HIWORD(dwParam) * 100) / 0xFFFFl;
1883     volume = left + (right << 8);
1884
1885     if (wDevID >= numOutDev) return MMSYSERR_INVALPARAM;
1886
1887     if ((mixer = open(WOutDev[wDevID].ossdev->mixer_name, O_WRONLY|O_NDELAY)) < 0) {
1888         WARN("mixer device not available !\n");
1889         return MMSYSERR_NOTENABLED;
1890     }
1891     if (ioctl(mixer, SOUND_MIXER_WRITE_PCM, &volume) == -1) {
1892         WARN("ioctl(%s, SOUND_MIXER_WRITE_PCM) failed (%s)\n", WOutDev[wDevID].ossdev->mixer_name, strerror(errno));
1893         return MMSYSERR_NOTENABLED;
1894     } else {
1895         TRACE("volume=%04x\n", (unsigned)volume);
1896     }
1897     close(mixer);
1898     return MMSYSERR_NOERROR;
1899 }
1900
1901 /**************************************************************************
1902  *                              wodMessage (WINEOSS.7)
1903  */
1904 DWORD WINAPI OSS_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1905                             DWORD dwParam1, DWORD dwParam2)
1906 {
1907     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
1908           wDevID, wMsg, dwUser, dwParam1, dwParam2);
1909
1910     switch (wMsg) {
1911     case DRVM_INIT:
1912     case DRVM_EXIT:
1913     case DRVM_ENABLE:
1914     case DRVM_DISABLE:
1915         /* FIXME: Pretend this is supported */
1916         return 0;
1917     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1918     case WODM_CLOSE:            return wodClose         (wDevID);
1919     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1920     case WODM_PAUSE:            return wodPause         (wDevID);
1921     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
1922     case WODM_BREAKLOOP:        return wodBreakLoop     (wDevID);
1923     case WODM_PREPARE:          return wodPrepare       (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1924     case WODM_UNPREPARE:        return wodUnprepare     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1925     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSA)dwParam1,      dwParam2);
1926     case WODM_GETNUMDEVS:       return numOutDev;
1927     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1928     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1929     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1930     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1931     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
1932     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
1933     case WODM_RESTART:          return wodRestart       (wDevID);
1934     case WODM_RESET:            return wodReset         (wDevID);
1935
1936     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate      (wDevID, (PIDSDRIVER*)dwParam1);
1937     case DRV_QUERYDSOUNDDESC:   return wodDsDesc        (wDevID, (PDSDRIVERDESC)dwParam1);
1938     case DRV_QUERYDSOUNDGUID:   return wodDsGuid        (wDevID, (LPGUID)dwParam1);
1939     default:
1940         FIXME("unknown message %d!\n", wMsg);
1941     }
1942     return MMSYSERR_NOTSUPPORTED;
1943 }
1944
1945 /*======================================================================*
1946  *                  Low level DSOUND implementation                     *
1947  *======================================================================*/
1948
1949 typedef struct IDsDriverImpl IDsDriverImpl;
1950 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1951
1952 struct IDsDriverImpl
1953 {
1954     /* IUnknown fields */
1955     ICOM_VFIELD(IDsDriver);
1956     DWORD               ref;
1957     /* IDsDriverImpl fields */
1958     UINT                wDevID;
1959     IDsDriverBufferImpl*primary;
1960 };
1961
1962 struct IDsDriverBufferImpl
1963 {
1964     /* IUnknown fields */
1965     ICOM_VFIELD(IDsDriverBuffer);
1966     DWORD               ref;
1967     /* IDsDriverBufferImpl fields */
1968     IDsDriverImpl*      drv;
1969     DWORD               buflen;
1970 };
1971
1972 static HRESULT DSDB_MapPrimary(IDsDriverBufferImpl *dsdb)
1973 {
1974     WINE_WAVEOUT *wwo = &(WOutDev[dsdb->drv->wDevID]);
1975     TRACE("(%p)\n",dsdb);
1976     if (!wwo->mapping) {
1977         wwo->mapping = mmap(NULL, wwo->maplen, PROT_WRITE, MAP_SHARED,
1978                             wwo->ossdev->fd, 0);
1979         if (wwo->mapping == (LPBYTE)-1) {
1980             TRACE("(%p): Could not map sound device for direct access (%s)\n", dsdb, strerror(errno));
1981             return DSERR_GENERIC;
1982         }
1983         TRACE("(%p): sound device has been mapped for direct access at %p, size=%ld\n", dsdb, wwo->mapping, wwo->maplen);
1984
1985         /* for some reason, es1371 and sblive! sometimes have junk in here.
1986          * clear it, or we get junk noise */
1987         /* some libc implementations are buggy: their memset reads from the buffer...
1988          * to work around it, we have to zero the block by hand. We don't do the expected:
1989          * memset(wwo->mapping,0, wwo->maplen);
1990          */
1991         {
1992             char*       p1 = wwo->mapping;
1993             unsigned    len = wwo->maplen;
1994
1995             if (len >= 16) /* so we can have at least a 4 long area to store... */
1996             {
1997                 /* the mmap:ed value is (at least) dword aligned
1998                  * so, start filling the complete unsigned long:s
1999                  */
2000                 int             b = len >> 2;
2001                 unsigned long*  p4 = (unsigned long*)p1;
2002
2003                 while (b--) *p4++ = 0;
2004                 /* prepare for filling the rest */
2005                 len &= 3;
2006                 p1 = (unsigned char*)p4;
2007             }
2008             /* in all cases, fill the remaining bytes */
2009             while (len-- != 0) *p1++ = 0;
2010         }
2011     }
2012     return DS_OK;
2013 }
2014
2015 static HRESULT DSDB_UnmapPrimary(IDsDriverBufferImpl *dsdb)
2016 {
2017     WINE_WAVEOUT *wwo = &(WOutDev[dsdb->drv->wDevID]);
2018     TRACE("(%p)\n",dsdb);
2019     if (wwo->mapping) {
2020         if (munmap(wwo->mapping, wwo->maplen) < 0) {
2021             ERR("(%p): Could not unmap sound device (%s)\n", dsdb, strerror(errno));
2022             return DSERR_GENERIC;
2023         }
2024         wwo->mapping = NULL;
2025         TRACE("(%p): sound device unmapped\n", dsdb);
2026     }
2027     return DS_OK;
2028 }
2029
2030 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
2031 {
2032     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2033     FIXME("(): stub!\n");
2034     return DSERR_UNSUPPORTED;
2035 }
2036
2037 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
2038 {
2039     ICOM_THIS(IDsDriverBufferImpl,iface);
2040     TRACE("(%p)\n",This);
2041     This->ref++;
2042     TRACE("ref=%ld\n",This->ref);
2043     return This->ref;
2044 }
2045
2046 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
2047 {
2048     ICOM_THIS(IDsDriverBufferImpl,iface);
2049     TRACE("(%p)\n",This);
2050     if (--This->ref) {
2051         TRACE("ref=%ld\n",This->ref);
2052         return This->ref;
2053     }
2054     if (This == This->drv->primary)
2055         This->drv->primary = NULL;
2056     DSDB_UnmapPrimary(This);
2057     HeapFree(GetProcessHeap(),0,This);
2058     TRACE("ref=0\n");
2059     return 0;
2060 }
2061
2062 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
2063                                                LPVOID*ppvAudio1,LPDWORD pdwLen1,
2064                                                LPVOID*ppvAudio2,LPDWORD pdwLen2,
2065                                                DWORD dwWritePosition,DWORD dwWriteLen,
2066                                                DWORD dwFlags)
2067 {
2068     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2069     /* since we (GetDriverDesc flags) have specified DSDDESC_DONTNEEDPRIMARYLOCK,
2070      * and that we don't support secondary buffers, this method will never be called */
2071     TRACE("(%p): stub\n",iface);
2072     return DSERR_UNSUPPORTED;
2073 }
2074
2075 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
2076                                                  LPVOID pvAudio1,DWORD dwLen1,
2077                                                  LPVOID pvAudio2,DWORD dwLen2)
2078 {
2079     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2080     TRACE("(%p): stub\n",iface);
2081     return DSERR_UNSUPPORTED;
2082 }
2083
2084 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
2085                                                     LPWAVEFORMATEX pwfx)
2086 {
2087     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2088
2089     TRACE("(%p,%p)\n",iface,pwfx);
2090     /* On our request (GetDriverDesc flags), DirectSound has by now used
2091      * waveOutClose/waveOutOpen to set the format...
2092      * unfortunately, this means our mmap() is now gone...
2093      * so we need to somehow signal to our DirectSound implementation
2094      * that it should completely recreate this HW buffer...
2095      * this unexpected error code should do the trick... */
2096     return DSERR_BUFFERLOST;
2097 }
2098
2099 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
2100 {
2101     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2102     TRACE("(%p,%ld): stub\n",iface,dwFreq);
2103     return DSERR_UNSUPPORTED;
2104 }
2105
2106 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
2107 {
2108     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2109     FIXME("(%p,%p): stub!\n",iface,pVolPan);
2110     return DSERR_UNSUPPORTED;
2111 }
2112
2113 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
2114 {
2115     /* ICOM_THIS(IDsDriverImpl,iface); */
2116     TRACE("(%p,%ld): stub\n",iface,dwNewPos);
2117     return DSERR_UNSUPPORTED;
2118 }
2119
2120 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
2121                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
2122 {
2123     ICOM_THIS(IDsDriverBufferImpl,iface);
2124     count_info info;
2125     DWORD ptr;
2126
2127     TRACE("(%p)\n",iface);
2128     if (WOutDev[This->drv->wDevID].state == WINE_WS_CLOSED) {
2129         ERR("device not open, but accessing?\n");
2130         return DSERR_UNINITIALIZED;
2131     }
2132     if (ioctl(WOutDev[This->drv->wDevID].ossdev->fd, SNDCTL_DSP_GETOPTR, &info) < 0) {
2133         ERR("ioctl(%s, SNDCTL_DSP_GETOPTR) failed (%s)\n", WOutDev[This->drv->wDevID].ossdev->dev_name, strerror(errno));
2134         return DSERR_GENERIC;
2135     }
2136     ptr = info.ptr & ~3; /* align the pointer, just in case */
2137     if (lpdwPlay) *lpdwPlay = ptr;
2138     if (lpdwWrite) {
2139         /* add some safety margin (not strictly necessary, but...) */
2140         if (WOutDev[This->drv->wDevID].ossdev->out_caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
2141             *lpdwWrite = ptr + 32;
2142         else
2143             *lpdwWrite = ptr + WOutDev[This->drv->wDevID].dwFragmentSize;
2144         while (*lpdwWrite > This->buflen)
2145             *lpdwWrite -= This->buflen;
2146     }
2147     TRACE("playpos=%ld, writepos=%ld\n", lpdwPlay?*lpdwPlay:0, lpdwWrite?*lpdwWrite:0);
2148     return DS_OK;
2149 }
2150
2151 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
2152 {
2153     ICOM_THIS(IDsDriverBufferImpl,iface);
2154     int enable;
2155     TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
2156     WOutDev[This->drv->wDevID].ossdev->bOutputEnabled = TRUE;
2157     enable = getEnables(WOutDev[This->drv->wDevID].ossdev);
2158     if (ioctl(WOutDev[This->drv->wDevID].ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
2159         if (errno == EINVAL) {
2160             /* Don't give up yet. OSS trigger support is inconsistent. */
2161             if (WOutDev[This->drv->wDevID].ossdev->open_count == 1) {
2162                 /* try the opposite input enable */
2163                 if (WOutDev[This->drv->wDevID].ossdev->bInputEnabled == FALSE)
2164                     WOutDev[This->drv->wDevID].ossdev->bInputEnabled = TRUE;
2165                 else
2166                     WOutDev[This->drv->wDevID].ossdev->bInputEnabled = FALSE;
2167                 /* try it again */
2168                 enable = getEnables(WOutDev[This->drv->wDevID].ossdev);
2169                 if (ioctl(WOutDev[This->drv->wDevID].ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) >= 0)
2170                     return DS_OK;
2171             }    
2172         }
2173         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n",WOutDev[This->drv->wDevID].ossdev->dev_name, strerror(errno));
2174         WOutDev[This->drv->wDevID].ossdev->bOutputEnabled = FALSE;
2175         return DSERR_GENERIC;
2176     }
2177     return DS_OK;
2178 }
2179
2180 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
2181 {
2182     ICOM_THIS(IDsDriverBufferImpl,iface);
2183     int enable;
2184     TRACE("(%p)\n",iface);
2185     /* no more playing */
2186     WOutDev[This->drv->wDevID].ossdev->bOutputEnabled = FALSE;
2187     enable = getEnables(WOutDev[This->drv->wDevID].ossdev);
2188     if (ioctl(WOutDev[This->drv->wDevID].ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
2189         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", WOutDev[This->drv->wDevID].ossdev->dev_name, strerror(errno));
2190         return DSERR_GENERIC;
2191     }
2192 #if 0
2193     /* the play position must be reset to the beginning of the buffer */
2194     if (ioctl(WOutDev[This->drv->wDevID].ossdev->fd, SNDCTL_DSP_RESET, 0) < 0) {
2195         ERR("ioctl(%s, SNDCTL_DSP_RESET) failed (%s)\n", WOutDev[This->drv->wDevID].ossdev->dev_name, strerror(errno));
2196         return DSERR_GENERIC;
2197     }
2198 #endif
2199     /* Most OSS drivers just can't stop the playback without closing the device...
2200      * so we need to somehow signal to our DirectSound implementation
2201      * that it should completely recreate this HW buffer...
2202      * this unexpected error code should do the trick... */
2203     return DSERR_BUFFERLOST;
2204 }
2205
2206 static ICOM_VTABLE(IDsDriverBuffer) dsdbvt =
2207 {
2208     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
2209     IDsDriverBufferImpl_QueryInterface,
2210     IDsDriverBufferImpl_AddRef,
2211     IDsDriverBufferImpl_Release,
2212     IDsDriverBufferImpl_Lock,
2213     IDsDriverBufferImpl_Unlock,
2214     IDsDriverBufferImpl_SetFormat,
2215     IDsDriverBufferImpl_SetFrequency,
2216     IDsDriverBufferImpl_SetVolumePan,
2217     IDsDriverBufferImpl_SetPosition,
2218     IDsDriverBufferImpl_GetPosition,
2219     IDsDriverBufferImpl_Play,
2220     IDsDriverBufferImpl_Stop
2221 };
2222
2223 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
2224 {
2225     /* ICOM_THIS(IDsDriverImpl,iface); */
2226     FIXME("(%p): stub!\n",iface);
2227     return DSERR_UNSUPPORTED;
2228 }
2229
2230 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
2231 {
2232     ICOM_THIS(IDsDriverImpl,iface);
2233     TRACE("(%p)\n",This);
2234     This->ref++;
2235     TRACE("ref=%ld\n",This->ref);
2236     return This->ref;
2237 }
2238
2239 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
2240 {
2241     ICOM_THIS(IDsDriverImpl,iface);
2242     TRACE("(%p)\n",This);
2243     if (--This->ref) {
2244         TRACE("ref=%ld\n",This->ref);
2245         return This->ref;
2246     }
2247     HeapFree(GetProcessHeap(),0,This);
2248     TRACE("ref=0\n");
2249     return 0;
2250 }
2251
2252 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
2253 {
2254     ICOM_THIS(IDsDriverImpl,iface);
2255     TRACE("(%p,%p)\n",iface,pDesc);
2256
2257     /* copy version from driver */
2258     memcpy(pDesc, &(WOutDev[This->wDevID].ossdev->ds_desc), sizeof(DSDRIVERDESC));
2259
2260     pDesc->dwFlags |= DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
2261         DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK;
2262     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
2263     pDesc->wVxdId               = 0;
2264     pDesc->wReserved            = 0;
2265     pDesc->ulDeviceNum          = This->wDevID;
2266     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
2267     pDesc->pvDirectDrawHeap     = NULL;
2268     pDesc->dwMemStartAddress    = 0;
2269     pDesc->dwMemEndAddress      = 0;
2270     pDesc->dwMemAllocExtra      = 0;
2271     pDesc->pvReserved1          = NULL;
2272     pDesc->pvReserved2          = NULL;
2273     return DS_OK;
2274 }
2275
2276 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
2277 {
2278     ICOM_THIS(IDsDriverImpl,iface);
2279     int enable;
2280     TRACE("(%p)\n",iface);
2281
2282     /* make sure the card doesn't start playing before we want it to */
2283     WOutDev[This->wDevID].ossdev->bOutputEnabled = FALSE;
2284     enable = getEnables(WOutDev[This->wDevID].ossdev);
2285     if (ioctl(WOutDev[This->wDevID].ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
2286         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n",WOutDev[This->wDevID].ossdev->dev_name, strerror(errno));
2287         return DSERR_GENERIC;
2288     }
2289     return DS_OK;
2290 }
2291
2292 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
2293 {
2294     ICOM_THIS(IDsDriverImpl,iface);
2295     TRACE("(%p)\n",iface);
2296     if (This->primary) {
2297         ERR("problem with DirectSound: primary not released\n");
2298         return DSERR_GENERIC;
2299     }
2300     return DS_OK;
2301 }
2302
2303 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
2304 {
2305     ICOM_THIS(IDsDriverImpl,iface);
2306     TRACE("(%p,%p)\n",iface,pCaps);
2307     memcpy(pCaps, &(WOutDev[This->wDevID].ossdev->ds_caps), sizeof(DSDRIVERCAPS));
2308     return DS_OK;
2309 }
2310
2311 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
2312                                                       LPWAVEFORMATEX pwfx,
2313                                                       DWORD dwFlags, DWORD dwCardAddress,
2314                                                       LPDWORD pdwcbBufferSize,
2315                                                       LPBYTE *ppbBuffer,
2316                                                       LPVOID *ppvObj)
2317 {
2318     ICOM_THIS(IDsDriverImpl,iface);
2319     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
2320     HRESULT err;
2321     audio_buf_info info;
2322     int enable = 0;
2323     TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
2324
2325     /* we only support primary buffers */
2326     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
2327         return DSERR_UNSUPPORTED;
2328     if (This->primary)
2329         return DSERR_ALLOCATED;
2330     if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
2331         return DSERR_CONTROLUNAVAIL;
2332
2333     *ippdsdb = (IDsDriverBufferImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDsDriverBufferImpl));
2334     if (*ippdsdb == NULL)
2335         return DSERR_OUTOFMEMORY;
2336     (*ippdsdb)->lpVtbl  = &dsdbvt;
2337     (*ippdsdb)->ref     = 1;
2338     (*ippdsdb)->drv     = This;
2339
2340     /* check how big the DMA buffer is now */
2341     if (ioctl(WOutDev[This->wDevID].ossdev->fd, SNDCTL_DSP_GETOSPACE, &info) < 0) {
2342         ERR("ioctl(%s, SNDCTL_DSP_GETOSPACE) failed (%s)\n", WOutDev[This->wDevID].ossdev->dev_name, strerror(errno));
2343         HeapFree(GetProcessHeap(),0,*ippdsdb);
2344         *ippdsdb = NULL;
2345         return DSERR_GENERIC;
2346     }
2347     WOutDev[This->wDevID].maplen = (*ippdsdb)->buflen = info.fragstotal * info.fragsize;
2348
2349     /* map the DMA buffer */
2350     err = DSDB_MapPrimary(*ippdsdb);
2351     if (err != DS_OK) {
2352         HeapFree(GetProcessHeap(),0,*ippdsdb);
2353         *ippdsdb = NULL;
2354         return err;
2355     }
2356
2357     /* primary buffer is ready to go */
2358     *pdwcbBufferSize    = WOutDev[This->wDevID].maplen;
2359     *ppbBuffer          = WOutDev[This->wDevID].mapping;
2360
2361     /* some drivers need some extra nudging after mapping */
2362     WOutDev[This->wDevID].ossdev->bOutputEnabled = FALSE;
2363     enable = getEnables(WOutDev[This->wDevID].ossdev);
2364     if (ioctl(WOutDev[This->wDevID].ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
2365         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", WOutDev[This->wDevID].ossdev->dev_name, strerror(errno));
2366         return DSERR_GENERIC;
2367     }
2368
2369     This->primary = *ippdsdb;
2370
2371     return DS_OK;
2372 }
2373
2374 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
2375                                                          PIDSDRIVERBUFFER pBuffer,
2376                                                          LPVOID *ppvObj)
2377 {
2378     /* ICOM_THIS(IDsDriverImpl,iface); */
2379     TRACE("(%p,%p): stub\n",iface,pBuffer);
2380     return DSERR_INVALIDCALL;
2381 }
2382
2383 static ICOM_VTABLE(IDsDriver) dsdvt =
2384 {
2385     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
2386     IDsDriverImpl_QueryInterface,
2387     IDsDriverImpl_AddRef,
2388     IDsDriverImpl_Release,
2389     IDsDriverImpl_GetDriverDesc,
2390     IDsDriverImpl_Open,
2391     IDsDriverImpl_Close,
2392     IDsDriverImpl_GetCaps,
2393     IDsDriverImpl_CreateSoundBuffer,
2394     IDsDriverImpl_DuplicateSoundBuffer
2395 };
2396
2397 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
2398 {
2399     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
2400     TRACE("(%d,%p)\n",wDevID,drv);
2401
2402     /* the HAL isn't much better than the HEL if we can't do mmap() */
2403     if (!(WOutDev[wDevID].ossdev->out_caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
2404         ERR("DirectSound flag not set\n");
2405         MESSAGE("This sound card's driver does not support direct access\n");
2406         MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
2407         return MMSYSERR_NOTSUPPORTED;
2408     }
2409
2410     *idrv = (IDsDriverImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDsDriverImpl));
2411     if (!*idrv)
2412         return MMSYSERR_NOMEM;
2413     (*idrv)->lpVtbl     = &dsdvt;
2414     (*idrv)->ref        = 1;
2415
2416     (*idrv)->wDevID     = wDevID;
2417     (*idrv)->primary    = NULL;
2418     return MMSYSERR_NOERROR;
2419 }
2420
2421 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2422 {
2423     TRACE("(%d,%p)\n",wDevID,desc);
2424     memcpy(desc, &(WOutDev[wDevID].ossdev->ds_desc), sizeof(DSDRIVERDESC));
2425     return MMSYSERR_NOERROR;
2426 }
2427
2428 static DWORD wodDsGuid(UINT wDevID, LPGUID pGuid)
2429 {
2430     TRACE("(%d,%p)\n",wDevID,pGuid);
2431     memcpy(pGuid, &(WOutDev[wDevID].ossdev->ds_guid), sizeof(GUID));
2432     return MMSYSERR_NOERROR;
2433 }
2434
2435 /*======================================================================*
2436  *                  Low level WAVE IN implementation                    *
2437  *======================================================================*/
2438
2439 /**************************************************************************
2440  *                      widNotifyClient                 [internal]
2441  */
2442 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
2443 {
2444     TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
2445
2446     switch (wMsg) {
2447     case WIM_OPEN:
2448     case WIM_CLOSE:
2449     case WIM_DATA:
2450         if (wwi->wFlags != DCB_NULL &&
2451             !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
2452                             (HDRVR)wwi->waveDesc.hWave, wMsg,
2453                             wwi->waveDesc.dwInstance, dwParam1, dwParam2)) {
2454             WARN("can't notify client !\n");
2455             return MMSYSERR_ERROR;
2456         }
2457         break;
2458     default:
2459         FIXME("Unknown callback message %u\n", wMsg);
2460         return MMSYSERR_INVALPARAM;
2461     }
2462     return MMSYSERR_NOERROR;
2463 }
2464
2465 /**************************************************************************
2466  *                      widGetDevCaps                           [internal]
2467  */
2468 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSA lpCaps, DWORD dwSize)
2469 {
2470     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
2471
2472     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
2473
2474     if (wDevID >= numInDev) {
2475         TRACE("numOutDev reached !\n");
2476         return MMSYSERR_BADDEVICEID;
2477     }
2478
2479     memcpy(lpCaps, &WInDev[wDevID].ossdev->in_caps, min(dwSize, sizeof(*lpCaps)));
2480     return MMSYSERR_NOERROR;
2481 }
2482
2483 /**************************************************************************
2484  *                              widRecorder                     [internal]
2485  */
2486 static  DWORD   CALLBACK        widRecorder(LPVOID pmt)
2487 {
2488     WORD                uDevID = (DWORD)pmt;
2489     WINE_WAVEIN*        wwi = (WINE_WAVEIN*)&WInDev[uDevID];
2490     WAVEHDR*            lpWaveHdr;
2491     DWORD               dwSleepTime;
2492     DWORD               bytesRead;
2493     LPVOID              buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, wwi->dwFragmentSize);
2494     char               *pOffset = buffer;
2495     audio_buf_info      info;
2496     int                 xs;
2497     enum win_wm_message msg;
2498     DWORD               param;
2499     HANDLE              ev;
2500     int                 enable;
2501
2502     wwi->state = WINE_WS_STOPPED;
2503     wwi->dwTotalRecorded = 0;
2504     wwi->lpQueuePtr = NULL;
2505
2506     SetEvent(wwi->hStartUpEvent);
2507
2508     /* disable input so capture will begin when triggered */
2509     wwi->ossdev->bInputEnabled = FALSE;
2510     enable = getEnables(wwi->ossdev);
2511     if (ioctl(wwi->ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0)
2512         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", wwi->ossdev->dev_name, strerror(errno));
2513
2514     /* the soundblaster live needs a micro wake to get its recording started
2515      * (or GETISPACE will have 0 frags all the time)
2516      */
2517     read(wwi->ossdev->fd, &xs, 4);
2518
2519     /* make sleep time to be # of ms to output a fragment */
2520     dwSleepTime = (wwi->dwFragmentSize * 1000) / wwi->format.wf.nAvgBytesPerSec;
2521     TRACE("sleeptime=%ld ms\n", dwSleepTime);
2522
2523     for (;;) {
2524         /* wait for dwSleepTime or an event in thread's queue */
2525         /* FIXME: could improve wait time depending on queue state,
2526          * ie, number of queued fragments
2527          */
2528
2529         if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
2530         {
2531             lpWaveHdr = wwi->lpQueuePtr;
2532
2533             ioctl(wwi->ossdev->fd, SNDCTL_DSP_GETISPACE, &info);
2534             TRACE("info={frag=%d fsize=%d ftotal=%d bytes=%d}\n", info.fragments, info.fragsize, info.fragstotal, info.bytes);
2535
2536             /* read all the fragments accumulated so far */
2537             while ((info.fragments > 0) && (wwi->lpQueuePtr))
2538             {
2539                 info.fragments --;
2540
2541                 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwFragmentSize)
2542                 {
2543                     /* directly read fragment in wavehdr */
2544                     bytesRead = read(wwi->ossdev->fd,
2545                                      lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2546                                      wwi->dwFragmentSize);
2547
2548                     TRACE("bytesRead=%ld (direct)\n", bytesRead);
2549                     if (bytesRead != (DWORD) -1)
2550                     {
2551                         /* update number of bytes recorded in current buffer and by this device */
2552                         lpWaveHdr->dwBytesRecorded += bytesRead;
2553                         wwi->dwTotalRecorded       += bytesRead;
2554
2555                         /* buffer is full. notify client */
2556                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2557                         {
2558                             /* must copy the value of next waveHdr, because we have no idea of what
2559                              * will be done with the content of lpWaveHdr in callback
2560                              */
2561                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
2562
2563                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2564                             lpWaveHdr->dwFlags |=  WHDR_DONE;
2565
2566                             widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2567                             lpWaveHdr = wwi->lpQueuePtr = lpNext;
2568                         }
2569                     }
2570                 }
2571                 else
2572                 {
2573                     /* read the fragment in a local buffer */
2574                     bytesRead = read(wwi->ossdev->fd, buffer, wwi->dwFragmentSize);
2575                     pOffset = buffer;
2576
2577                     TRACE("bytesRead=%ld (local)\n", bytesRead);
2578
2579                     /* copy data in client buffers */
2580                     while (bytesRead != (DWORD) -1 && bytesRead > 0)
2581                     {
2582                         DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
2583
2584                         memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2585                                pOffset,
2586                                dwToCopy);
2587
2588                         /* update number of bytes recorded in current buffer and by this device */
2589                         lpWaveHdr->dwBytesRecorded += dwToCopy;
2590                         wwi->dwTotalRecorded += dwToCopy;
2591                         bytesRead -= dwToCopy;
2592                         pOffset   += dwToCopy;
2593
2594                         /* client buffer is full. notify client */
2595                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2596                         {
2597                             /* must copy the value of next waveHdr, because we have no idea of what
2598                              * will be done with the content of lpWaveHdr in callback
2599                              */
2600                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
2601                             TRACE("lpNext=%p\n", lpNext);
2602
2603                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2604                             lpWaveHdr->dwFlags |=  WHDR_DONE;
2605
2606                             widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2607
2608                             wwi->lpQueuePtr = lpWaveHdr = lpNext;
2609                             if (!lpNext && bytesRead) {
2610                                 /* before we give up, check for more header messages */
2611                                 while (OSS_PeekRingMessage(&wwi->msgRing, &msg, &param, &ev))
2612                                 {
2613                                     if (msg == WINE_WM_HEADER) {
2614                                         LPWAVEHDR hdr;
2615                                         OSS_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev);
2616                                         hdr = ((LPWAVEHDR)param);
2617                                         TRACE("msg = %s, hdr = %p, ev = %p\n", wodPlayerCmdString[msg - WM_USER - 1], hdr, ev);
2618                                         hdr->lpNext = 0;
2619                                         if (lpWaveHdr == 0) {
2620                                             /* new head of queue */
2621                                             wwi->lpQueuePtr = lpWaveHdr = hdr;
2622                                         } else {
2623                                             /* insert buffer at the end of queue */
2624                                             LPWAVEHDR*  wh;
2625                                             for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2626                                             *wh = hdr;
2627                                         }
2628                                     } else
2629                                         break;
2630                                 }
2631
2632                                 if (lpWaveHdr == 0) {
2633                                     /* no more buffer to copy data to, but we did read more.
2634                                      * what hasn't been copied will be dropped
2635                                      */
2636                                     WARN("buffer under run! %lu bytes dropped.\n", bytesRead);
2637                                     wwi->lpQueuePtr = NULL;
2638                                     break;
2639                                 }
2640                             }
2641                         }
2642                     }
2643                 }
2644             }
2645         }
2646
2647         WAIT_OMR(&wwi->msgRing, dwSleepTime);
2648
2649         while (OSS_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev))
2650         {
2651             TRACE("msg=%s param=0x%lx\n", wodPlayerCmdString[msg - WM_USER - 1], param);
2652             switch (msg) {
2653             case WINE_WM_PAUSING:
2654                 wwi->state = WINE_WS_PAUSED;
2655                 /*FIXME("Device should stop recording\n");*/
2656                 SetEvent(ev);
2657                 break;
2658             case WINE_WM_STARTING:
2659                 wwi->state = WINE_WS_PLAYING;
2660
2661                 if (wwi->ossdev->bTriggerSupport)
2662                 {
2663                     /* start the recording */
2664                     wwi->ossdev->bInputEnabled = TRUE;
2665                     enable = getEnables(wwi->ossdev);
2666                     if (ioctl(wwi->ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
2667                         wwi->ossdev->bInputEnabled = FALSE;
2668                         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", wwi->ossdev->dev_name, strerror(errno));
2669                     }
2670                 }
2671                 else
2672                 {
2673                     unsigned char data[4];
2674                     /* read 4 bytes to start the recording */
2675                     read(wwi->ossdev->fd, data, 4);
2676                 }
2677
2678                 SetEvent(ev);
2679                 break;
2680             case WINE_WM_HEADER:
2681                 lpWaveHdr = (LPWAVEHDR)param;
2682                 lpWaveHdr->lpNext = 0;
2683
2684                 /* insert buffer at the end of queue */
2685                 {
2686                     LPWAVEHDR*  wh;
2687                     for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2688                     *wh = lpWaveHdr;
2689                 }
2690                 break;
2691             case WINE_WM_STOPPING:
2692             case WINE_WM_RESETTING:
2693                 wwi->state = WINE_WS_STOPPED;
2694                 /* return all buffers to the app */
2695                 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
2696                     TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
2697                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2698                     lpWaveHdr->dwFlags |= WHDR_DONE;
2699
2700                     widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2701                 }
2702                 wwi->lpQueuePtr = NULL;
2703                 SetEvent(ev);
2704                 break;
2705             case WINE_WM_CLOSING:
2706                 wwi->hThread = 0;
2707                 wwi->state = WINE_WS_CLOSED;
2708                 SetEvent(ev);
2709                 HeapFree(GetProcessHeap(), 0, buffer);
2710                 ExitThread(0);
2711                 /* shouldn't go here */
2712             default:
2713                 FIXME("unknown message %d\n", msg);
2714                 break;
2715             }
2716         }
2717     }
2718     ExitThread(0);
2719     /* just for not generating compilation warnings... should never be executed */
2720     return 0;
2721 }
2722
2723
2724 /**************************************************************************
2725  *                              widOpen                         [internal]
2726  */
2727 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
2728 {
2729     WINE_WAVEIN*        wwi;
2730     int                 fragment_size;
2731     int                 audio_fragment;
2732     DWORD               ret;
2733
2734     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
2735     if (lpDesc == NULL) {
2736         WARN("Invalid Parameter !\n");
2737         return MMSYSERR_INVALPARAM;
2738     }
2739     if (wDevID >= numInDev) return MMSYSERR_BADDEVICEID;
2740
2741     /* only PCM format is supported so far... */
2742     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
2743         lpDesc->lpFormat->nChannels == 0 ||
2744         lpDesc->lpFormat->nSamplesPerSec == 0) {
2745         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
2746              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
2747              lpDesc->lpFormat->nSamplesPerSec);
2748         return WAVERR_BADFORMAT;
2749     }
2750
2751     if (dwFlags & WAVE_FORMAT_QUERY) {
2752         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
2753              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
2754              lpDesc->lpFormat->nSamplesPerSec);
2755         return MMSYSERR_NOERROR;
2756     }
2757
2758     wwi = &WInDev[wDevID];
2759
2760     if (wwi->state != WINE_WS_CLOSED) return MMSYSERR_ALLOCATED;
2761
2762     if ((dwFlags & WAVE_DIRECTSOUND) && 
2763         !(wwi->ossdev->in_caps_support & WAVECAPS_DIRECTSOUND))
2764         /* not supported, ignore it */
2765         dwFlags &= ~WAVE_DIRECTSOUND;
2766
2767     if (dwFlags & WAVE_DIRECTSOUND) {
2768         TRACE("has DirectSoundCapture driver\n");
2769         if (wwi->ossdev->in_caps_support & WAVECAPS_SAMPLEACCURATE)
2770             /* we have realtime DirectSound, fragments just waste our time,
2771              * but a large buffer is good, so choose 64KB (32 * 2^11) */
2772             audio_fragment = 0x0020000B;
2773         else
2774             /* to approximate realtime, we must use small fragments,
2775              * let's try to fragment the above 64KB (256 * 2^8) */
2776             audio_fragment = 0x01000008;
2777     } else {
2778         TRACE("doesn't have DirectSoundCapture driver\n");
2779         /* This is actually hand tuned to work so that my SB Live:
2780          * - does not skip
2781          * - does not buffer too much
2782          * when sending with the Shoutcast winamp plugin
2783          */
2784         /* 15 fragments max, 2^10 = 1024 bytes per fragment */
2785         audio_fragment = 0x000F000A;
2786     }
2787
2788     TRACE("using %d %d byte fragments\n", audio_fragment >> 16, 1 << (audio_fragment & 0xffff));
2789
2790     ret = OSS_OpenDevice(wwi->ossdev, O_RDONLY, &audio_fragment,
2791                          1,
2792                          lpDesc->lpFormat->nSamplesPerSec,
2793                          (lpDesc->lpFormat->nChannels > 1) ? 1 : 0,
2794                          (lpDesc->lpFormat->wBitsPerSample == 16)
2795                          ? AFMT_S16_LE : AFMT_U8);
2796     if (ret != 0) return ret;
2797     wwi->state = WINE_WS_STOPPED;
2798
2799     if (wwi->lpQueuePtr) {
2800         WARN("Should have an empty queue (%p)\n", wwi->lpQueuePtr);
2801         wwi->lpQueuePtr = NULL;
2802     }
2803     wwi->dwTotalRecorded = 0;
2804     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
2805
2806     memcpy(&wwi->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
2807     memcpy(&wwi->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
2808
2809     if (wwi->format.wBitsPerSample == 0) {
2810         WARN("Resetting zeroed wBitsPerSample\n");
2811         wwi->format.wBitsPerSample = 8 *
2812             (wwi->format.wf.nAvgBytesPerSec /
2813              wwi->format.wf.nSamplesPerSec) /
2814             wwi->format.wf.nChannels;
2815     }
2816
2817     ioctl(wwi->ossdev->fd, SNDCTL_DSP_GETBLKSIZE, &fragment_size);
2818     if (fragment_size == -1) {
2819         WARN("ioctl(%s, SNDCTL_DSP_GETBLKSIZE) failed (%s)\n", wwi->ossdev->dev_name, strerror(errno));
2820         OSS_CloseDevice(wwi->ossdev);
2821         wwi->state = WINE_WS_CLOSED;
2822         return MMSYSERR_NOTENABLED;
2823     }
2824     wwi->dwFragmentSize = fragment_size;
2825
2826     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
2827           wwi->format.wBitsPerSample, wwi->format.wf.nAvgBytesPerSec,
2828           wwi->format.wf.nSamplesPerSec, wwi->format.wf.nChannels,
2829           wwi->format.wf.nBlockAlign);
2830
2831     OSS_InitRingMessage(&wwi->msgRing);
2832
2833     wwi->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
2834     wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
2835     WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
2836     CloseHandle(wwi->hStartUpEvent);
2837     wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
2838
2839     return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
2840 }
2841
2842 /**************************************************************************
2843  *                              widClose                        [internal]
2844  */
2845 static DWORD widClose(WORD wDevID)
2846 {
2847     WINE_WAVEIN*        wwi;
2848
2849     TRACE("(%u);\n", wDevID);
2850     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2851         WARN("can't close !\n");
2852         return MMSYSERR_INVALHANDLE;
2853     }
2854
2855     wwi = &WInDev[wDevID];
2856
2857     if (wwi->lpQueuePtr != NULL) {
2858         WARN("still buffers open !\n");
2859         return WAVERR_STILLPLAYING;
2860     }
2861
2862     OSS_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
2863     OSS_CloseDevice(wwi->ossdev);
2864     wwi->state = WINE_WS_CLOSED;
2865     wwi->dwFragmentSize = 0;
2866     OSS_DestroyRingMessage(&wwi->msgRing);
2867     return widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
2868 }
2869
2870 /**************************************************************************
2871  *                              widAddBuffer            [internal]
2872  */
2873 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2874 {
2875     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2876
2877     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2878         WARN("can't do it !\n");
2879         return MMSYSERR_INVALHANDLE;
2880     }
2881     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED)) {
2882         TRACE("never been prepared !\n");
2883         return WAVERR_UNPREPARED;
2884     }
2885     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) {
2886         TRACE("header already in use !\n");
2887         return WAVERR_STILLPLAYING;
2888     }
2889
2890     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2891     lpWaveHdr->dwFlags &= ~WHDR_DONE;
2892     lpWaveHdr->dwBytesRecorded = 0;
2893     lpWaveHdr->lpNext = NULL;
2894
2895     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
2896     return MMSYSERR_NOERROR;
2897 }
2898
2899 /**************************************************************************
2900  *                              widPrepare                      [internal]
2901  */
2902 static DWORD widPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2903 {
2904     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2905
2906     if (wDevID >= numInDev) return MMSYSERR_INVALHANDLE;
2907
2908     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2909         return WAVERR_STILLPLAYING;
2910
2911     lpWaveHdr->dwFlags |= WHDR_PREPARED;
2912     lpWaveHdr->dwFlags &= ~WHDR_DONE;
2913     lpWaveHdr->dwBytesRecorded = 0;
2914     TRACE("header prepared !\n");
2915     return MMSYSERR_NOERROR;
2916 }
2917
2918 /**************************************************************************
2919  *                              widUnprepare                    [internal]
2920  */
2921 static DWORD widUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2922 {
2923     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2924     if (wDevID >= numInDev) return MMSYSERR_INVALHANDLE;
2925
2926     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2927         return WAVERR_STILLPLAYING;
2928
2929     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
2930     lpWaveHdr->dwFlags |= WHDR_DONE;
2931
2932     return MMSYSERR_NOERROR;
2933 }
2934
2935 /**************************************************************************
2936  *                      widStart                                [internal]
2937  */
2938 static DWORD widStart(WORD wDevID)
2939 {
2940     TRACE("(%u);\n", wDevID);
2941     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2942         WARN("can't start recording !\n");
2943         return MMSYSERR_INVALHANDLE;
2944     }
2945
2946     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
2947     return MMSYSERR_NOERROR;
2948 }
2949
2950 /**************************************************************************
2951  *                      widStop                                 [internal]
2952  */
2953 static DWORD widStop(WORD wDevID)
2954 {
2955     TRACE("(%u);\n", wDevID);
2956     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2957         WARN("can't stop !\n");
2958         return MMSYSERR_INVALHANDLE;
2959     }
2960
2961     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
2962
2963     return MMSYSERR_NOERROR;
2964 }
2965
2966 /**************************************************************************
2967  *                      widReset                                [internal]
2968  */
2969 static DWORD widReset(WORD wDevID)
2970 {
2971     TRACE("(%u);\n", wDevID);
2972     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2973         WARN("can't reset !\n");
2974         return MMSYSERR_INVALHANDLE;
2975     }
2976     OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
2977     return MMSYSERR_NOERROR;
2978 }
2979
2980 /**************************************************************************
2981  *                              widGetPosition                  [internal]
2982  */
2983 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
2984 {
2985     int                 time;
2986     WINE_WAVEIN*        wwi;
2987
2988     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
2989
2990     if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
2991         WARN("can't get pos !\n");
2992         return MMSYSERR_INVALHANDLE;
2993     }
2994     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
2995
2996     wwi = &WInDev[wDevID];
2997
2998     TRACE("wType=%04X !\n", lpTime->wType);
2999     TRACE("wBitsPerSample=%u\n", wwi->format.wBitsPerSample);
3000     TRACE("nSamplesPerSec=%lu\n", wwi->format.wf.nSamplesPerSec);
3001     TRACE("nChannels=%u\n", wwi->format.wf.nChannels);
3002     TRACE("nAvgBytesPerSec=%lu\n", wwi->format.wf.nAvgBytesPerSec);
3003     switch (lpTime->wType) {
3004     case TIME_BYTES:
3005         lpTime->u.cb = wwi->dwTotalRecorded;
3006         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
3007         break;
3008     case TIME_SAMPLES:
3009         lpTime->u.sample = wwi->dwTotalRecorded * 8 /
3010             wwi->format.wBitsPerSample / wwi->format.wf.nChannels;
3011         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
3012         break;
3013     case TIME_SMPTE:
3014         time = wwi->dwTotalRecorded /
3015             (wwi->format.wf.nAvgBytesPerSec / 1000);
3016         lpTime->u.smpte.hour = time / 108000;
3017         time -= lpTime->u.smpte.hour * 108000;
3018         lpTime->u.smpte.min = time / 1800;
3019         time -= lpTime->u.smpte.min * 1800;
3020         lpTime->u.smpte.sec = time / 30;
3021         time -= lpTime->u.smpte.sec * 30;
3022         lpTime->u.smpte.frame = time;
3023         lpTime->u.smpte.fps = 30;
3024         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
3025               lpTime->u.smpte.hour, lpTime->u.smpte.min,
3026               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
3027         break;
3028     case TIME_MS:
3029         lpTime->u.ms = wwi->dwTotalRecorded /
3030             (wwi->format.wf.nAvgBytesPerSec / 1000);
3031         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
3032         break;
3033     default:
3034         FIXME("format not supported (%u) ! use TIME_MS !\n", lpTime->wType);
3035         lpTime->wType = TIME_MS;
3036     }
3037     return MMSYSERR_NOERROR;
3038 }
3039
3040 /**************************************************************************
3041  *                              widMessage (WINEOSS.6)
3042  */
3043 DWORD WINAPI OSS_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3044                             DWORD dwParam1, DWORD dwParam2)
3045 {
3046     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
3047           wDevID, wMsg, dwUser, dwParam1, dwParam2);
3048
3049     switch (wMsg) {
3050     case DRVM_INIT:
3051     case DRVM_EXIT:
3052     case DRVM_ENABLE:
3053     case DRVM_DISABLE:
3054         /* FIXME: Pretend this is supported */
3055         return 0;
3056     case WIDM_OPEN:             return widOpen       (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
3057     case WIDM_CLOSE:            return widClose      (wDevID);
3058     case WIDM_ADDBUFFER:        return widAddBuffer  (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3059     case WIDM_PREPARE:          return widPrepare    (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3060     case WIDM_UNPREPARE:        return widUnprepare  (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3061     case WIDM_GETDEVCAPS:       return widGetDevCaps (wDevID, (LPWAVEINCAPSA)dwParam1, dwParam2);
3062     case WIDM_GETNUMDEVS:       return numInDev;
3063     case WIDM_GETPOS:           return widGetPosition(wDevID, (LPMMTIME)dwParam1, dwParam2);
3064     case WIDM_RESET:            return widReset      (wDevID);
3065     case WIDM_START:            return widStart      (wDevID);
3066     case WIDM_STOP:             return widStop       (wDevID);
3067     case DRV_QUERYDSOUNDIFACE:  return widDsCreate   (wDevID, (PIDSCDRIVER*)dwParam1);
3068     case DRV_QUERYDSOUNDDESC:   return widDsDesc     (wDevID, (PDSDRIVERDESC)dwParam1);
3069     case DRV_QUERYDSOUNDGUID:   return widDsGuid     (wDevID, (LPGUID)dwParam1);
3070     default:
3071         FIXME("unknown message %u!\n", wMsg);
3072     }
3073     return MMSYSERR_NOTSUPPORTED;
3074 }
3075
3076 /*======================================================================*
3077  *                  Low level DSOUND notify implementation              *
3078  *======================================================================*/
3079
3080 typedef struct IDsDriverNotifyImpl IDsDriverNotifyImpl;
3081
3082 struct IDsDriverNotifyImpl
3083 {
3084     /* IUnknown fields */
3085     ICOM_VFIELD(IDsDriverNotify);
3086     DWORD                            ref;
3087     /* IDsDriverNotifyImpl fields */
3088     LPDSBPOSITIONNOTIFY              notifies;
3089     int                              nrofnotifies;
3090 };
3091
3092 static HRESULT WINAPI IDsDriverNotifyImpl_QueryInterface(
3093     PIDSDRIVERNOTIFY iface,
3094     REFIID riid,
3095     LPVOID *ppobj) 
3096 {
3097     ICOM_THIS(IDsDriverNotifyImpl,iface);
3098     TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
3099
3100     if ( IsEqualGUID(riid, &IID_IUnknown) ||
3101          IsEqualGUID(riid, &IID_IDsDriverNotify) ) {
3102         IDsDriverNotify_AddRef(iface);
3103         *ppobj = This;
3104         return DS_OK;
3105     }
3106
3107     FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
3108
3109     *ppobj = 0;
3110
3111     return E_NOINTERFACE;
3112 }
3113
3114 static ULONG WINAPI IDsDriverNotifyImpl_AddRef(PIDSDRIVERNOTIFY iface) 
3115 {
3116     ICOM_THIS(IDsDriverNotifyImpl,iface);
3117     DWORD ref;
3118     TRACE("(%p) ref was %ld\n", This, This->ref);
3119
3120     ref = InterlockedIncrement(&(This->ref));
3121     return ref;
3122 }
3123
3124 static ULONG WINAPI IDsDriverNotifyImpl_Release(PIDSDRIVERNOTIFY iface) 
3125 {
3126     ICOM_THIS(IDsDriverNotifyImpl,iface);
3127     DWORD ref;
3128     TRACE("(%p) ref was %ld\n", This, This->ref);
3129
3130     ref = InterlockedDecrement(&(This->ref));
3131     /* FIXME: A notification should be a part of a buffer rather than pointed
3132      * to from a buffer. Hence the -1 ref count */
3133     if (ref == -1) {
3134         if (This->notifies != NULL)
3135             HeapFree(GetProcessHeap(), 0, This->notifies);
3136
3137         HeapFree(GetProcessHeap(),0,This);
3138         return 0;
3139     }
3140
3141     return ref;
3142 }
3143
3144 static HRESULT WINAPI IDsDriverNotifyImpl_SetNotificationPositions(
3145     PIDSDRIVERNOTIFY iface,
3146     DWORD howmuch,
3147     LPCDSBPOSITIONNOTIFY notify) 
3148 {
3149     ICOM_THIS(IDsDriverNotifyImpl,iface);
3150     TRACE("(%p,0x%08lx,%p)\n",This,howmuch,notify);
3151
3152     if (!notify) {
3153         WARN("invalid parameter\n");
3154         return DSERR_INVALIDPARAM;
3155     }
3156
3157     if (TRACE_ON(wave)) {
3158         int i;
3159         for (i=0;i<howmuch;i++)
3160             TRACE("notify at %ld to 0x%08lx\n",
3161                 notify[i].dwOffset,(DWORD)notify[i].hEventNotify);
3162     }
3163
3164     /* Make an internal copy of the caller-supplied array.
3165      * Replace the existing copy if one is already present. */
3166     This->notifies = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
3167     This->notifies, howmuch * sizeof(DSBPOSITIONNOTIFY));
3168     memcpy(This->notifies, notify, howmuch * sizeof(DSBPOSITIONNOTIFY));
3169     This->nrofnotifies = howmuch;
3170
3171     return S_OK;
3172 }
3173
3174 ICOM_VTABLE(IDsDriverNotify) dsdnvt =
3175 {
3176     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
3177     IDsDriverNotifyImpl_QueryInterface,
3178     IDsDriverNotifyImpl_AddRef,
3179     IDsDriverNotifyImpl_Release,
3180     IDsDriverNotifyImpl_SetNotificationPositions,
3181 };
3182
3183 /*======================================================================*
3184  *                  Low level DSOUND capture implementation             *
3185  *======================================================================*/
3186
3187 typedef struct IDsCaptureDriverImpl IDsCaptureDriverImpl;
3188 typedef struct IDsCaptureDriverBufferImpl IDsCaptureDriverBufferImpl;
3189
3190 struct IDsCaptureDriverImpl
3191 {
3192     /* IUnknown fields */
3193     ICOM_VFIELD(IDsCaptureDriver);
3194     DWORD                       ref;
3195     /* IDsCaptureDriverImpl fields */
3196     UINT                        wDevID;
3197     IDsCaptureDriverBufferImpl* capture_buffer;
3198 };
3199
3200 struct IDsCaptureDriverBufferImpl
3201 {
3202     /* IUnknown fields */
3203     ICOM_VFIELD(IDsCaptureDriverBuffer);
3204     DWORD                       ref;
3205     /* IDsCaptureDriverBufferImpl fields */
3206     IDsCaptureDriverImpl*       drv;
3207     DWORD                       buflen;
3208
3209     /* IDsDriverNotifyImpl fields */
3210     IDsDriverNotifyImpl*        notify;
3211     int                         notify_index;
3212 };
3213
3214 static HRESULT DSDB_MapCapture(IDsCaptureDriverBufferImpl *dscdb)
3215 {
3216     WINE_WAVEIN *wwi = &(WInDev[dscdb->drv->wDevID]);
3217     if (!wwi->mapping) {
3218         wwi->mapping = mmap(NULL, wwi->maplen, PROT_WRITE, MAP_SHARED,
3219                             wwi->ossdev->fd, 0);
3220         if (wwi->mapping == (LPBYTE)-1) {
3221             TRACE("(%p): Could not map sound device for direct access (%s)\n", dscdb, strerror(errno));
3222             return DSERR_GENERIC;
3223         }
3224         TRACE("(%p): sound device has been mapped for direct access at %p, size=%ld\n", dscdb, wwi->mapping, wwi->maplen);
3225
3226         /* for some reason, es1371 and sblive! sometimes have junk in here.
3227          * clear it, or we get junk noise */
3228         /* some libc implementations are buggy: their memset reads from the buffer...
3229          * to work around it, we have to zero the block by hand. We don't do the expected:
3230          * memset(wwo->mapping,0, wwo->maplen);
3231          */
3232         {
3233             char*       p1 = wwi->mapping;
3234             unsigned    len = wwi->maplen;
3235
3236             if (len >= 16) /* so we can have at least a 4 long area to store... */
3237             {
3238                 /* the mmap:ed value is (at least) dword aligned
3239                  * so, start filling the complete unsigned long:s
3240                  */
3241                 int             b = len >> 2;
3242                 unsigned long*  p4 = (unsigned long*)p1;
3243
3244                 while (b--) *p4++ = 0;
3245                 /* prepare for filling the rest */
3246                 len &= 3;
3247                 p1 = (unsigned char*)p4;
3248             }
3249             /* in all cases, fill the remaining bytes */
3250             while (len-- != 0) *p1++ = 0;
3251         }
3252     }
3253     return DS_OK;
3254 }
3255
3256 static HRESULT DSDB_UnmapCapture(IDsCaptureDriverBufferImpl *dscdb)
3257 {
3258     WINE_WAVEIN *wwi = &(WInDev[dscdb->drv->wDevID]);
3259     if (wwi->mapping) {
3260         if (munmap(wwi->mapping, wwi->maplen) < 0) {
3261             ERR("(%p): Could not unmap sound device (%s)\n", dscdb, strerror(errno));
3262             return DSERR_GENERIC;
3263         }
3264         wwi->mapping = NULL;
3265         TRACE("(%p): sound device unmapped\n", dscdb);
3266     }
3267     return DS_OK;
3268 }
3269
3270 static HRESULT WINAPI IDsCaptureDriverBufferImpl_QueryInterface(PIDSCDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
3271 {
3272     ICOM_THIS(IDsCaptureDriverBufferImpl,iface);
3273     TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
3274
3275     if ( IsEqualGUID( &IID_IDsDriverNotify, riid ) ) {
3276         if (!This->notify) {
3277             This->notify = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*This->notify));
3278             if (This->notify) {
3279                 This->notify->ref = 0;  /* release when ref = -1 */
3280                 This->notify->lpVtbl = &dsdnvt;
3281             }
3282         }
3283         if (This->notify) {
3284             IDsDriverNotify_AddRef((PIDSDRIVERNOTIFY)This->notify);
3285             *ppobj = (LPVOID)This->notify;
3286             return DS_OK;
3287         }
3288         *ppobj = 0;
3289         return E_FAIL;
3290     }
3291
3292     FIXME("(%p,%s,%p) unsupported GUID\n", This, debugstr_guid(riid), ppobj);
3293
3294     *ppobj = 0;
3295
3296     return DSERR_UNSUPPORTED;
3297 }
3298
3299 static ULONG WINAPI IDsCaptureDriverBufferImpl_AddRef(PIDSCDRIVERBUFFER iface)
3300 {
3301     ICOM_THIS(IDsCaptureDriverBufferImpl,iface);
3302     This->ref++;
3303     return This->ref;
3304 }
3305
3306 static ULONG WINAPI IDsCaptureDriverBufferImpl_Release(PIDSCDRIVERBUFFER iface)
3307 {
3308     ICOM_THIS(IDsCaptureDriverBufferImpl,iface);
3309     if (--This->ref)
3310         return This->ref;
3311     DSDB_UnmapCapture(This);
3312     if (This->notify)
3313         IDirectSoundNotify_Release((LPDIRECTSOUNDNOTIFY)This->notify);
3314     HeapFree(GetProcessHeap(),0,This);
3315     return 0;
3316 }
3317
3318 static HRESULT WINAPI IDsCaptureDriverBufferImpl_Lock(PIDSCDRIVERBUFFER iface,
3319                                                       LPVOID*ppvAudio1,LPDWORD pdwLen1,
3320                                                       LPVOID*ppvAudio2,LPDWORD pdwLen2,
3321                                                       DWORD dwWritePosition,DWORD dwWriteLen,
3322                                                       DWORD dwFlags)
3323 {
3324     ICOM_THIS(IDsCaptureDriverBufferImpl,iface);
3325     FIXME("(%p,%p,%p,%p,%p,%ld,%ld,0x%08lx): stub!\n",This,ppvAudio1,pdwLen1,ppvAudio2,pdwLen2,
3326         dwWritePosition,dwWriteLen,dwFlags);
3327     return DS_OK;
3328 }
3329
3330 static HRESULT WINAPI IDsCaptureDriverBufferImpl_Unlock(PIDSCDRIVERBUFFER iface,
3331                                                         LPVOID pvAudio1,DWORD dwLen1,
3332                                                         LPVOID pvAudio2,DWORD dwLen2)
3333 {
3334     ICOM_THIS(IDsCaptureDriverBufferImpl,iface);
3335     FIXME("(%p,%p,%ld,%p,%ld): stub!\n",This,pvAudio1,dwLen1,pvAudio2,dwLen2);
3336     return DS_OK;
3337 }
3338
3339 static HRESULT WINAPI IDsCaptureDriverBufferImpl_GetPosition(PIDSCDRIVERBUFFER iface,
3340                                                              LPDWORD lpdwCapture, 
3341                                                              LPDWORD lpdwRead)
3342 {
3343     ICOM_THIS(IDsCaptureDriverBufferImpl,iface);
3344     count_info info;
3345     DWORD ptr;
3346     TRACE("(%p,%p,%p)\n",This,lpdwCapture,lpdwRead);
3347
3348     if (WInDev[This->drv->wDevID].state == WINE_WS_CLOSED) {
3349         ERR("device not open, but accessing?\n");
3350         return DSERR_UNINITIALIZED;
3351     }
3352     if (ioctl(WInDev[This->drv->wDevID].ossdev->fd, SNDCTL_DSP_GETIPTR, &info) < 0) {
3353         ERR("ioctl(%s, SNDCTL_DSP_GETIPTR) failed (%s)\n", WInDev[This->drv->wDevID].ossdev->dev_name, strerror(errno));
3354         return DSERR_GENERIC;
3355     }
3356     ptr = info.ptr & ~3; /* align the pointer, just in case */
3357     if (lpdwCapture) *lpdwCapture = ptr;
3358     if (lpdwRead) {
3359         /* add some safety margin (not strictly necessary, but...) */
3360         if (WInDev[This->drv->wDevID].ossdev->in_caps_support & WAVECAPS_SAMPLEACCURATE)
3361             *lpdwRead = ptr + 32;
3362         else
3363             *lpdwRead = ptr + WInDev[This->drv->wDevID].dwFragmentSize;
3364         while (*lpdwRead > This->buflen)
3365             *lpdwRead -= This->buflen;
3366     }
3367     TRACE("capturepos=%ld, readpos=%ld\n", lpdwCapture?*lpdwCapture:0, lpdwRead?*lpdwRead:0);
3368     return DS_OK;
3369 }
3370
3371 static HRESULT WINAPI IDsCaptureDriverBufferImpl_GetStatus(PIDSCDRIVERBUFFER iface, LPDWORD lpdwStatus)
3372 {
3373     ICOM_THIS(IDsCaptureDriverBufferImpl,iface);
3374     FIXME("(%p,%p): stub!\n",This,lpdwStatus);
3375     return DSERR_UNSUPPORTED;
3376 }
3377
3378 static HRESULT WINAPI IDsCaptureDriverBufferImpl_Start(PIDSCDRIVERBUFFER iface, DWORD dwFlags)
3379 {
3380     ICOM_THIS(IDsCaptureDriverBufferImpl,iface);
3381     int enable;
3382     TRACE("(%p,%lx)\n",This,dwFlags);
3383     WInDev[This->drv->wDevID].ossdev->bInputEnabled = TRUE;
3384     enable = getEnables(WInDev[This->drv->wDevID].ossdev);
3385     if (ioctl(WInDev[This->drv->wDevID].ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
3386         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", WInDev[This->drv->wDevID].ossdev->dev_name, strerror(errno));
3387         WInDev[This->drv->wDevID].ossdev->bInputEnabled = FALSE;
3388         return DSERR_GENERIC;
3389     }
3390     return DS_OK;
3391 }
3392
3393 static HRESULT WINAPI IDsCaptureDriverBufferImpl_Stop(PIDSCDRIVERBUFFER iface)
3394 {
3395     ICOM_THIS(IDsCaptureDriverBufferImpl,iface);
3396     int enable;
3397     TRACE("(%p)\n",This);
3398     /* no more captureing */
3399     WInDev[This->drv->wDevID].ossdev->bInputEnabled = FALSE;
3400     enable = getEnables(WInDev[This->drv->wDevID].ossdev);
3401     if (ioctl(WInDev[This->drv->wDevID].ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
3402         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", WInDev[This->drv->wDevID].ossdev->dev_name,  strerror(errno));
3403         return DSERR_GENERIC;
3404     }
3405
3406     /* Most OSS drivers just can't stop capturing without closing the device...
3407      * so we need to somehow signal to our DirectSound implementation
3408      * that it should completely recreate this HW buffer...
3409      * this unexpected error code should do the trick... */
3410     return DSERR_BUFFERLOST;
3411 }
3412
3413 static HRESULT WINAPI IDsCaptureDriverBufferImpl_SetFormat(PIDSCDRIVERBUFFER iface, LPWAVEFORMATEX pwfx)
3414 {
3415     ICOM_THIS(IDsCaptureDriverBufferImpl,iface);
3416     FIXME("(%p): stub!\n",This);
3417     return DSERR_UNSUPPORTED;
3418 }
3419
3420 static ICOM_VTABLE(IDsCaptureDriverBuffer) dscdbvt =
3421 {
3422     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
3423     IDsCaptureDriverBufferImpl_QueryInterface,
3424     IDsCaptureDriverBufferImpl_AddRef,
3425     IDsCaptureDriverBufferImpl_Release,
3426     IDsCaptureDriverBufferImpl_Lock,
3427     IDsCaptureDriverBufferImpl_Unlock,
3428     IDsCaptureDriverBufferImpl_SetFormat,
3429     IDsCaptureDriverBufferImpl_GetPosition,
3430     IDsCaptureDriverBufferImpl_GetStatus,
3431     IDsCaptureDriverBufferImpl_Start,
3432     IDsCaptureDriverBufferImpl_Stop
3433 };
3434
3435 static HRESULT WINAPI IDsCaptureDriverImpl_QueryInterface(PIDSCDRIVER iface, REFIID riid, LPVOID *ppobj)
3436 {
3437     ICOM_THIS(IDsCaptureDriverImpl,iface);
3438     FIXME("(%p,%p,%p): stub!\n",This,riid,ppobj);
3439     return DSERR_UNSUPPORTED;
3440 }
3441
3442 static ULONG WINAPI IDsCaptureDriverImpl_AddRef(PIDSCDRIVER iface)
3443 {
3444     ICOM_THIS(IDsCaptureDriverImpl,iface);
3445     TRACE("(%p)\n",This);
3446     This->ref++;
3447     TRACE("ref=%ld\n",This->ref);
3448     return This->ref;
3449 }
3450
3451 static ULONG WINAPI IDsCaptureDriverImpl_Release(PIDSCDRIVER iface)
3452 {
3453     ICOM_THIS(IDsCaptureDriverImpl,iface);
3454     TRACE("(%p)\n",This);
3455     if (--This->ref) {
3456         TRACE("ref=%ld\n",This->ref);
3457         return This->ref;
3458     }
3459     HeapFree(GetProcessHeap(),0,This);
3460     TRACE("ref=0\n");
3461     return 0;
3462 }
3463
3464 static HRESULT WINAPI IDsCaptureDriverImpl_GetDriverDesc(PIDSCDRIVER iface, PDSDRIVERDESC pDesc)
3465 {
3466     ICOM_THIS(IDsCaptureDriverImpl,iface);
3467     TRACE("(%p,%p)\n",This,pDesc);
3468
3469     if (!pDesc) {
3470         TRACE("invalid parameter\n");
3471         return DSERR_INVALIDPARAM;
3472     }
3473
3474     /* copy version from driver */
3475     memcpy(pDesc, &(WInDev[This->wDevID].ossdev->ds_desc), sizeof(DSDRIVERDESC));
3476
3477     pDesc->dwFlags |= DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
3478         DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK | 
3479         DSDDESC_DONTNEEDSECONDARYLOCK;
3480     pDesc->dnDevNode            = WInDev[This->wDevID].waveDesc.dnDevNode;
3481     pDesc->wVxdId               = 0;
3482     pDesc->wReserved            = 0;
3483     pDesc->ulDeviceNum          = This->wDevID;
3484     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
3485     pDesc->pvDirectDrawHeap     = NULL;
3486     pDesc->dwMemStartAddress    = 0;
3487     pDesc->dwMemEndAddress      = 0;
3488     pDesc->dwMemAllocExtra      = 0;
3489     pDesc->pvReserved1          = NULL;
3490     pDesc->pvReserved2          = NULL;
3491     return DS_OK;
3492 }
3493
3494 static HRESULT WINAPI IDsCaptureDriverImpl_Open(PIDSCDRIVER iface)
3495 {
3496     ICOM_THIS(IDsCaptureDriverImpl,iface);
3497     TRACE("(%p)\n",This);
3498     return DS_OK;
3499 }
3500
3501 static HRESULT WINAPI IDsCaptureDriverImpl_Close(PIDSCDRIVER iface)
3502 {
3503     ICOM_THIS(IDsCaptureDriverImpl,iface);
3504     TRACE("(%p)\n",This);
3505     if (This->capture_buffer) {
3506         ERR("problem with DirectSound: capture buffer not released\n");
3507         return DSERR_GENERIC;
3508     }
3509     return DS_OK;
3510 }
3511
3512 static HRESULT WINAPI IDsCaptureDriverImpl_GetCaps(PIDSCDRIVER iface, PDSCDRIVERCAPS pCaps)
3513 {
3514     ICOM_THIS(IDsCaptureDriverImpl,iface);
3515     TRACE("(%p,%p)\n",This,pCaps);
3516     memcpy(pCaps, &(WInDev[This->wDevID].ossdev->dsc_caps), sizeof(DSCDRIVERCAPS)); 
3517     return DS_OK;
3518 }
3519
3520 static HRESULT WINAPI IDsCaptureDriverImpl_CreateCaptureBuffer(PIDSCDRIVER iface,
3521                                                                LPWAVEFORMATEX pwfx,
3522                                                                DWORD dwFlags, 
3523                                                                DWORD dwCardAddress,
3524                                                                LPDWORD pdwcbBufferSize,
3525                                                                LPBYTE *ppbBuffer,
3526                                                                LPVOID *ppvObj)
3527 {
3528     ICOM_THIS(IDsCaptureDriverImpl,iface);
3529     IDsCaptureDriverBufferImpl** ippdscdb = (IDsCaptureDriverBufferImpl**)ppvObj;
3530     HRESULT err;
3531     audio_buf_info info;
3532     int enable;
3533     TRACE("(%p,%p,%lx,%lx,%p,%p,%p)\n",This,pwfx,dwFlags,dwCardAddress,pdwcbBufferSize,ppbBuffer,ppvObj);
3534
3535     if (This->capture_buffer) {
3536         TRACE("already allocated\n");
3537         return DSERR_ALLOCATED;
3538     }
3539
3540     *ippdscdb = (IDsCaptureDriverBufferImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDsCaptureDriverBufferImpl));
3541     if (*ippdscdb == NULL) {
3542         TRACE("out of memory\n");
3543         return DSERR_OUTOFMEMORY;
3544     }
3545
3546     (*ippdscdb)->lpVtbl = &dscdbvt;
3547     (*ippdscdb)->ref          = 1;
3548     (*ippdscdb)->drv          = This;
3549     (*ippdscdb)->notify       = 0;
3550     (*ippdscdb)->notify_index = 0;
3551
3552     if (WInDev[This->wDevID].state == WINE_WS_CLOSED) {
3553         WAVEOPENDESC desc;
3554         desc.hWave = 0;
3555         desc.lpFormat = pwfx; 
3556         desc.dwCallback = 0;
3557         desc.dwInstance = 0;
3558         desc.uMappedDeviceID = 0;
3559         desc.dnDevNode = 0;
3560         err = widOpen(This->wDevID, &desc, dwFlags | WAVE_DIRECTSOUND);
3561         if (err != MMSYSERR_NOERROR) {
3562             TRACE("widOpen failed\n");
3563             return err;
3564         }
3565     }
3566
3567     /* check how big the DMA buffer is now */
3568     if (ioctl(WInDev[This->wDevID].ossdev->fd, SNDCTL_DSP_GETISPACE, &info) < 0) {
3569         ERR("ioctl(%s, SNDCTL_DSP_GETISPACE) failed (%s)\n", WInDev[This->wDevID].ossdev->dev_name, strerror(errno));
3570         HeapFree(GetProcessHeap(),0,*ippdscdb);
3571         *ippdscdb = NULL;
3572         return DSERR_GENERIC;
3573     }
3574     WInDev[This->wDevID].maplen = (*ippdscdb)->buflen = info.fragstotal * info.fragsize;
3575
3576     /* map the DMA buffer */
3577     err = DSDB_MapCapture(*ippdscdb);
3578     if (err != DS_OK) {
3579         HeapFree(GetProcessHeap(),0,*ippdscdb);
3580         *ippdscdb = NULL;
3581         return err;
3582     }
3583
3584     /* capture buffer is ready to go */
3585     *pdwcbBufferSize    = WInDev[This->wDevID].maplen;
3586     *ppbBuffer          = WInDev[This->wDevID].mapping;
3587
3588     /* some drivers need some extra nudging after mapping */
3589     WInDev[This->wDevID].ossdev->bInputEnabled = FALSE;
3590     enable = getEnables(WInDev[This->wDevID].ossdev);
3591     if (ioctl(WInDev[This->wDevID].ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
3592         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", WInDev[This->wDevID].ossdev->dev_name, strerror(errno));
3593         return DSERR_GENERIC;
3594     }
3595
3596     This->capture_buffer = *ippdscdb;
3597
3598     return DS_OK;
3599 }
3600
3601 static ICOM_VTABLE(IDsCaptureDriver) dscdvt =
3602 {
3603     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
3604     IDsCaptureDriverImpl_QueryInterface,
3605     IDsCaptureDriverImpl_AddRef,
3606     IDsCaptureDriverImpl_Release,
3607     IDsCaptureDriverImpl_GetDriverDesc,
3608     IDsCaptureDriverImpl_Open,
3609     IDsCaptureDriverImpl_Close,
3610     IDsCaptureDriverImpl_GetCaps,
3611     IDsCaptureDriverImpl_CreateCaptureBuffer
3612 };
3613
3614 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
3615 {
3616     IDsCaptureDriverImpl** idrv = (IDsCaptureDriverImpl**)drv;
3617     TRACE("(%d,%p)\n",wDevID,drv);
3618
3619     /* the HAL isn't much better than the HEL if we can't do mmap() */
3620     if (!(WInDev[wDevID].ossdev->in_caps_support & WAVECAPS_DIRECTSOUND)) {
3621         ERR("DirectSoundCapture flag not set\n");
3622         MESSAGE("This sound card's driver does not support direct access\n");
3623         MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
3624         return MMSYSERR_NOTSUPPORTED;
3625     }
3626
3627     *idrv = (IDsCaptureDriverImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDsCaptureDriverImpl));
3628     if (!*idrv)
3629         return MMSYSERR_NOMEM;
3630     (*idrv)->lpVtbl     = &dscdvt;
3631     (*idrv)->ref        = 1;
3632
3633     (*idrv)->wDevID     = wDevID;
3634     (*idrv)->capture_buffer = NULL;
3635     return MMSYSERR_NOERROR;
3636 }
3637
3638 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
3639 {
3640     memcpy(desc, &(WInDev[wDevID].ossdev->ds_desc), sizeof(DSDRIVERDESC));
3641     return MMSYSERR_NOERROR;
3642 }
3643
3644 static DWORD widDsGuid(UINT wDevID, LPGUID pGuid)
3645 {
3646     TRACE("(%d,%p)\n",wDevID,pGuid);
3647
3648     memcpy(pGuid, &(WInDev[wDevID].ossdev->dsc_guid), sizeof(GUID));
3649
3650     return MMSYSERR_NOERROR;
3651 }
3652
3653 #else /* !HAVE_OSS */
3654
3655 /**************************************************************************
3656  *                              wodMessage (WINEOSS.7)
3657  */
3658 DWORD WINAPI OSS_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3659                             DWORD dwParam1, DWORD dwParam2)
3660 {
3661     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3662     return MMSYSERR_NOTENABLED;
3663 }
3664
3665 /**************************************************************************
3666  *                              widMessage (WINEOSS.6)
3667  */
3668 DWORD WINAPI OSS_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3669                             DWORD dwParam1, DWORD dwParam2)
3670 {
3671     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3672     return MMSYSERR_NOTENABLED;
3673 }
3674
3675 #endif /* HAVE_OSS */