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