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