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