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