Apply Jeremy White's SMPTE calculation fix to each audio driver.
[wine] / dlls / winmm / winealsa / audio.c
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
2 /*
3  * Sample Wine Driver for Advanced Linux Sound System (ALSA)
4  *      Based on version <final> of the ALSA API
5  *
6  * Copyright    2002 Eric Pouech
7  *              2002 Marco Pietrobono
8  *              2003 Christian Costa : WaveIn support
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 /* unless someone makes a wineserver kernel module, Unix pipes are faster than win32 events */
26 #define USE_PIPE_SYNC
27
28 #include "config.h"
29 #include "wine/port.h"
30
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <string.h>
35 #ifdef HAVE_UNISTD_H
36 # include <unistd.h>
37 #endif
38 #include <errno.h>
39 #include <limits.h>
40 #include <fcntl.h>
41 #ifdef HAVE_SYS_IOCTL_H
42 # include <sys/ioctl.h>
43 #endif
44 #ifdef HAVE_SYS_MMAN_H
45 # include <sys/mman.h>
46 #endif
47 #include "windef.h"
48 #include "winbase.h"
49 #include "wingdi.h"
50 #include "winerror.h"
51 #include "winuser.h"
52 #include "winnls.h"
53 #include "winreg.h"
54 #include "mmddk.h"
55 #include "mmreg.h"
56 #include "dsound.h"
57 #include "dsdriver.h"
58 #include "ks.h"
59 #include "ksguid.h"
60 #include "ksmedia.h"
61 #define ALSA_PCM_NEW_HW_PARAMS_API
62 #define ALSA_PCM_NEW_SW_PARAMS_API
63 #include "alsa.h"
64 #include "wine/library.h"
65 #include "wine/unicode.h"
66 #include "wine/debug.h"
67
68 WINE_DEFAULT_DEBUG_CHANNEL(wave);
69
70
71 #ifdef HAVE_ALSA
72
73 /* internal ALSALIB functions */
74 snd_pcm_uframes_t _snd_pcm_mmap_hw_ptr(snd_pcm_t *pcm);
75
76
77 #define MAX_WAVEOUTDRV  (1)
78 #define MAX_WAVEINDRV   (1)
79
80 /* state diagram for waveOut writing:
81  *
82  * +---------+-------------+---------------+---------------------------------+
83  * |  state  |  function   |     event     |            new state            |
84  * +---------+-------------+---------------+---------------------------------+
85  * |         | open()      |               | STOPPED                         |
86  * | PAUSED  | write()     |               | PAUSED                          |
87  * | STOPPED | write()     | <thrd create> | PLAYING                         |
88  * | PLAYING | write()     | HEADER        | PLAYING                         |
89  * | (other) | write()     | <error>       |                                 |
90  * | (any)   | pause()     | PAUSING       | PAUSED                          |
91  * | PAUSED  | restart()   | RESTARTING    | PLAYING (if no thrd => STOPPED) |
92  * | (any)   | reset()     | RESETTING     | STOPPED                         |
93  * | (any)   | close()     | CLOSING       | CLOSED                          |
94  * +---------+-------------+---------------+---------------------------------+
95  */
96
97 /* states of the playing device */
98 #define WINE_WS_PLAYING         0
99 #define WINE_WS_PAUSED          1
100 #define WINE_WS_STOPPED         2
101 #define WINE_WS_CLOSED          3
102
103 /* events to be send to device */
104 enum win_wm_message {
105     WINE_WM_PAUSING = WM_USER + 1, WINE_WM_RESTARTING, WINE_WM_RESETTING, WINE_WM_HEADER,
106     WINE_WM_UPDATE, WINE_WM_BREAKLOOP, WINE_WM_CLOSING, WINE_WM_STARTING, WINE_WM_STOPPING
107 };
108
109 #ifdef USE_PIPE_SYNC
110 #define SIGNAL_OMR(omr) do { int x = 0; write((omr)->msg_pipe[1], &x, sizeof(x)); } while (0)
111 #define CLEAR_OMR(omr) do { int x = 0; read((omr)->msg_pipe[0], &x, sizeof(x)); } while (0)
112 #define RESET_OMR(omr) do { } while (0)
113 #define WAIT_OMR(omr, sleep) \
114   do { struct pollfd pfd; pfd.fd = (omr)->msg_pipe[0]; \
115        pfd.events = POLLIN; poll(&pfd, 1, sleep); } while (0)
116 #else
117 #define SIGNAL_OMR(omr) do { SetEvent((omr)->msg_event); } while (0)
118 #define CLEAR_OMR(omr) do { } while (0)
119 #define RESET_OMR(omr) do { ResetEvent((omr)->msg_event); } while (0)
120 #define WAIT_OMR(omr, sleep) \
121   do { WaitForSingleObject((omr)->msg_event, sleep); } while (0)
122 #endif
123
124 typedef struct {
125     enum win_wm_message         msg;    /* message identifier */
126     DWORD                       param;  /* parameter for this message */
127     HANDLE                      hEvent; /* if message is synchronous, handle of event for synchro */
128 } ALSA_MSG;
129
130 /* implement an in-process message ring for better performance
131  * (compared to passing thru the server)
132  * this ring will be used by the input (resp output) record (resp playback) routine
133  */
134 #define ALSA_RING_BUFFER_INCREMENT      64
135 typedef struct {
136     ALSA_MSG                    * messages;
137     int                         ring_buffer_size;
138     int                         msg_tosave;
139     int                         msg_toget;
140 #ifdef USE_PIPE_SYNC
141     int                         msg_pipe[2];
142 #else
143     HANDLE                      msg_event;
144 #endif
145     CRITICAL_SECTION            msg_crst;
146 } ALSA_MSG_RING;
147
148 typedef struct {
149     /* Windows information */
150     volatile int                state;                  /* one of the WINE_WS_ manifest constants */
151     WAVEOPENDESC                waveDesc;
152     WORD                        wFlags;
153     WAVEFORMATPCMEX             format;
154     WAVEOUTCAPSW                caps;
155
156     /* ALSA information (ALSA 0.9/1.x uses two different devices for playback/capture) */
157     char*                       device;
158     char                        interface_name[64];
159     snd_pcm_t*                  p_handle;                 /* handle to ALSA playback device */
160     snd_pcm_t*                  c_handle;                 /* handle to ALSA capture device */
161     snd_pcm_hw_params_t *       hw_params;              /* ALSA Hw params */
162
163     snd_ctl_t *                 ctl;                    /* control handle for the playback volume */
164     snd_ctl_elem_id_t *         playback_eid;           /* element id of the playback volume control */
165     snd_ctl_elem_value_t *      playback_evalue;        /* element value of the playback volume control */
166     snd_ctl_elem_info_t *       playback_einfo;         /* element info of the playback volume control */
167
168     snd_pcm_sframes_t           (*write)(snd_pcm_t *, const void *, snd_pcm_uframes_t );
169
170     struct pollfd               *ufds;
171     int                         count;
172
173     DWORD                       dwBufferSize;           /* size of whole ALSA buffer in bytes */
174     LPWAVEHDR                   lpQueuePtr;             /* start of queued WAVEHDRs (waiting to be notified) */
175     LPWAVEHDR                   lpPlayPtr;              /* start of not yet fully played buffers */
176     DWORD                       dwPartialOffset;        /* Offset of not yet written bytes in lpPlayPtr */
177
178     LPWAVEHDR                   lpLoopPtr;              /* pointer of first buffer in loop, if any */
179     DWORD                       dwLoops;                /* private copy of loop counter */
180
181     DWORD                       dwPlayedTotal;          /* number of bytes actually played since opening */
182     DWORD                       dwWrittenTotal;         /* number of bytes written to ALSA buffer since opening */
183
184     /* synchronization stuff */
185     HANDLE                      hStartUpEvent;
186     HANDLE                      hThread;
187     DWORD                       dwThreadID;
188     ALSA_MSG_RING               msgRing;
189
190     /* DirectSound stuff */
191     DSDRIVERDESC                ds_desc;
192 } WINE_WAVEOUT;
193
194 typedef struct {
195     /* Windows information */
196     volatile int                state;                  /* one of the WINE_WS_ manifest constants */
197     WAVEOPENDESC                waveDesc;
198     WORD                        wFlags;
199     WAVEFORMATPCMEX             format;
200     WAVEOUTCAPSW                caps;
201
202     /* ALSA information (ALSA 0.9/1.x uses two different devices for playback/capture) */
203     char*                       device;
204     char                        interface_name[64];
205     snd_pcm_t*                  p_handle;                 /* handle to ALSA playback device */
206     snd_pcm_t*                  c_handle;                 /* handle to ALSA capture device */
207     snd_pcm_hw_params_t *       hw_params;              /* ALSA Hw params */
208
209     snd_ctl_t *                 ctl;                    /* control handle for the playback volume */
210     snd_ctl_elem_id_t *         playback_eid;           /* element id of the playback volume control */
211     snd_ctl_elem_value_t *      playback_evalue;        /* element value of the playback volume control */
212     snd_ctl_elem_info_t *       playback_einfo;         /* element info of the playback volume control */
213
214     snd_pcm_sframes_t           (*read)(snd_pcm_t *, void *, snd_pcm_uframes_t );
215
216     struct pollfd               *ufds;
217     int                         count;
218
219     DWORD                       dwPeriodSize;           /* size of OSS buffer period */
220     DWORD                       dwBufferSize;           /* size of whole ALSA buffer in bytes */
221     LPWAVEHDR                   lpQueuePtr;             /* start of queued WAVEHDRs (waiting to be notified) */
222     LPWAVEHDR                   lpPlayPtr;              /* start of not yet fully played buffers */
223
224     LPWAVEHDR                   lpLoopPtr;              /* pointer of first buffer in loop, if any */
225     DWORD                       dwLoops;                /* private copy of loop counter */
226
227     /*DWORD                     dwPlayedTotal; */
228     DWORD                       dwTotalRecorded;
229
230     /* synchronization stuff */
231     HANDLE                      hStartUpEvent;
232     HANDLE                      hThread;
233     DWORD                       dwThreadID;
234     ALSA_MSG_RING               msgRing;
235
236     /* DirectSound stuff */
237     DSDRIVERDESC                ds_desc;
238 } WINE_WAVEIN;
239
240 static WINE_WAVEOUT     WOutDev   [MAX_WAVEOUTDRV];
241 static DWORD            ALSA_WodNumDevs;
242 static WINE_WAVEIN      WInDev   [MAX_WAVEINDRV];
243 static DWORD            ALSA_WidNumDevs;
244
245 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
246 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
247
248 /* These strings used only for tracing */
249 static const char * getCmdString(enum win_wm_message msg)
250 {
251     static char unknown[32];
252 #define MSG_TO_STR(x) case x: return #x
253     switch(msg) {
254     MSG_TO_STR(WINE_WM_PAUSING);
255     MSG_TO_STR(WINE_WM_RESTARTING);
256     MSG_TO_STR(WINE_WM_RESETTING);
257     MSG_TO_STR(WINE_WM_HEADER);
258     MSG_TO_STR(WINE_WM_UPDATE);
259     MSG_TO_STR(WINE_WM_BREAKLOOP);
260     MSG_TO_STR(WINE_WM_CLOSING);
261     MSG_TO_STR(WINE_WM_STARTING);
262     MSG_TO_STR(WINE_WM_STOPPING);
263     }
264 #undef MSG_TO_STR
265     sprintf(unknown, "UNKNOWN(0x%08x)", msg);
266     return unknown;
267 }
268
269 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
270                              WAVEFORMATPCMEX* format)
271 {
272     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
273           lpTime->wType, format->Format.wBitsPerSample, format->Format.nSamplesPerSec,
274           format->Format.nChannels, format->Format.nAvgBytesPerSec);
275     TRACE("Position in bytes=%lu\n", position);
276
277     switch (lpTime->wType) {
278     case TIME_SAMPLES:
279         lpTime->u.sample = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
280         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
281         break;
282     case TIME_MS:
283         lpTime->u.ms = 1000.0 * position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels * format->Format.nSamplesPerSec);
284         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
285         break;
286     case TIME_SMPTE:
287         lpTime->u.smpte.fps = 30;
288         position = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
289         position += (format->Format.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
290         lpTime->u.smpte.sec = position / format->Format.nSamplesPerSec;
291         position -= lpTime->u.smpte.sec * format->Format.nSamplesPerSec;
292         lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
293         lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
294         lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
295         lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
296         lpTime->u.smpte.fps = 30;
297         lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->Format.nSamplesPerSec;
298         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
299               lpTime->u.smpte.hour, lpTime->u.smpte.min,
300               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
301         break;
302     default:
303         WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
304         lpTime->wType = TIME_BYTES;
305         /* fall through */
306     case TIME_BYTES:
307         lpTime->u.cb = position;
308         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
309         break;
310     }
311     return MMSYSERR_NOERROR;
312 }
313
314 static BOOL supportedFormat(LPWAVEFORMATEX wf)
315 {
316     TRACE("(%p)\n",wf);
317
318     if (wf->nSamplesPerSec<DSBFREQUENCY_MIN||wf->nSamplesPerSec>DSBFREQUENCY_MAX)
319         return FALSE;
320
321     if (wf->wFormatTag == WAVE_FORMAT_PCM) {
322         if (wf->nChannels==1||wf->nChannels==2) {
323             if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
324                 return TRUE;
325         }
326     } else if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
327         WAVEFORMATEXTENSIBLE    * wfex = (WAVEFORMATEXTENSIBLE *)wf;
328
329         if (wf->cbSize == 22 &&
330             (IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM) ||
331              IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))) {
332             if (wf->nChannels>=1 && wf->nChannels<=6) {
333                 if (wf->wBitsPerSample==wfex->Samples.wValidBitsPerSample) {
334                     if (wf->wBitsPerSample==8||wf->wBitsPerSample==16||
335                         wf->wBitsPerSample==24||wf->wBitsPerSample==32) {
336                         return TRUE;
337                     }
338                 } else
339                     WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
340             }
341         } else
342             WARN("only KSDATAFORMAT_SUBTYPE_PCM and KSDATAFORMAT_SUBTYPE_IEEE_FLOAT "
343                  "supported\n");
344     } else if (wf->wFormatTag == WAVE_FORMAT_MULAW || wf->wFormatTag == WAVE_FORMAT_ALAW) {
345         if (wf->wBitsPerSample==8)
346             return TRUE;
347         else
348             ERR("WAVE_FORMAT_MULAW and WAVE_FORMAT_ALAW wBitsPerSample must = 8\n");
349
350     } else if (wf->wFormatTag == WAVE_FORMAT_ADPCM) {
351         if (wf->wBitsPerSample==4)
352             return TRUE;
353         else
354             ERR("WAVE_FORMAT_ADPCM wBitsPerSample must = 4\n");
355     } else
356         WARN("only WAVE_FORMAT_PCM and WAVE_FORMAT_EXTENSIBLE supported\n");
357
358     return FALSE;
359 }
360
361 static void copy_format(LPWAVEFORMATEX wf1, LPWAVEFORMATPCMEX wf2)
362 {
363     ZeroMemory(wf2, sizeof(wf2));
364     if (wf1->wFormatTag == WAVE_FORMAT_PCM)
365         memcpy(wf2, wf1, sizeof(PCMWAVEFORMAT));
366     else if (wf1->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
367         memcpy(wf2, wf1, sizeof(WAVEFORMATPCMEX));
368     else
369         memcpy(wf2, wf1, sizeof(WAVEFORMATEX) + wf1->cbSize);
370 }
371
372 /*======================================================================*
373  *                  Low level WAVE implementation                       *
374  *======================================================================*/
375
376 /**************************************************************************
377  *                      ALSA_InitializeVolumeCtl                [internal]
378  *
379  * used to initialize the PCM Volume Control
380  */
381 static int ALSA_InitializeVolumeCtl(WINE_WAVEOUT * wwo)
382 {
383     snd_ctl_t *                 ctl = NULL;
384     snd_ctl_card_info_t *       cardinfo;
385     snd_ctl_elem_list_t *       elemlist;
386     snd_ctl_elem_id_t *         e_id;
387     snd_ctl_elem_info_t *       einfo;
388     snd_hctl_t *                hctl = NULL;
389     snd_hctl_elem_t *           elem;
390     int                         nCtrls;
391     int                         i;
392
393     snd_ctl_card_info_alloca(&cardinfo);
394     memset(cardinfo,0,snd_ctl_card_info_sizeof());
395
396     snd_ctl_elem_list_alloca(&elemlist);
397     memset(elemlist,0,snd_ctl_elem_list_sizeof());
398
399     snd_ctl_elem_id_alloca(&e_id);
400     memset(e_id,0,snd_ctl_elem_id_sizeof());
401
402     snd_ctl_elem_info_alloca(&einfo);
403     memset(einfo,0,snd_ctl_elem_info_sizeof());
404
405 #define EXIT_ON_ERROR(f,txt) do \
406 { \
407     int err; \
408     if ( (err = (f) ) < 0) \
409     { \
410         ERR(txt ": %s\n", snd_strerror(err)); \
411         if (hctl) \
412             snd_hctl_close(hctl); \
413         if (ctl) \
414             snd_ctl_close(ctl); \
415         return -1; \
416     } \
417 } while(0)
418
419     EXIT_ON_ERROR( snd_ctl_open(&ctl,"hw",0) , "ctl open failed" );
420     EXIT_ON_ERROR( snd_ctl_card_info(ctl, cardinfo), "card info failed");
421     EXIT_ON_ERROR( snd_ctl_elem_list(ctl, elemlist), "elem list failed");
422
423     nCtrls = snd_ctl_elem_list_get_count(elemlist);
424
425     EXIT_ON_ERROR( snd_hctl_open(&hctl,"hw",0), "hctl open failed");
426     EXIT_ON_ERROR( snd_hctl_load(hctl), "hctl load failed" );
427
428     elem=snd_hctl_first_elem(hctl);
429     for ( i= 0; i<nCtrls; i++) {
430
431         memset(e_id,0,snd_ctl_elem_id_sizeof());
432
433         snd_hctl_elem_get_id(elem,e_id);
434 /*
435         TRACE("ctl: #%d '%s'%d\n",
436                                    snd_ctl_elem_id_get_numid(e_id),
437                                    snd_ctl_elem_id_get_name(e_id),
438                                    snd_ctl_elem_id_get_index(e_id));
439 */
440         if ( !strcmp("PCM Playback Volume", snd_ctl_elem_id_get_name(e_id)) )
441         {
442             EXIT_ON_ERROR( snd_hctl_elem_info(elem,einfo), "hctl elem info failed" );
443
444             /* few sanity checks... you'll never know... */
445             if ( snd_ctl_elem_info_get_type(einfo) != SND_CTL_ELEM_TYPE_INTEGER )
446                 WARN("playback volume control is not an integer\n");
447             if ( !snd_ctl_elem_info_is_readable(einfo) )
448                 WARN("playback volume control is readable\n");
449             if ( !snd_ctl_elem_info_is_writable(einfo) )
450                 WARN("playback volume control is readable\n");
451
452             TRACE("   ctrl range: min=%ld  max=%ld  step=%ld\n",
453                  snd_ctl_elem_info_get_min(einfo),
454                  snd_ctl_elem_info_get_max(einfo),
455                  snd_ctl_elem_info_get_step(einfo));
456
457             EXIT_ON_ERROR( snd_ctl_elem_id_malloc(&wwo->playback_eid), "elem id malloc failed" );
458             EXIT_ON_ERROR( snd_ctl_elem_info_malloc(&wwo->playback_einfo), "elem info malloc failed" );
459             EXIT_ON_ERROR( snd_ctl_elem_value_malloc(&wwo->playback_evalue), "elem value malloc failed" );
460
461             /* ok, now we can safely save these objects for later */
462             snd_ctl_elem_id_copy(wwo->playback_eid, e_id);
463             snd_ctl_elem_info_copy(wwo->playback_einfo, einfo);
464             snd_ctl_elem_value_set_id(wwo->playback_evalue, wwo->playback_eid);
465             wwo->ctl = ctl;
466         }
467
468         elem=snd_hctl_elem_next(elem);
469     }
470     snd_hctl_close(hctl);
471 #undef EXIT_ON_ERROR
472     return 0;
473 }
474
475 /**************************************************************************
476  *                      ALSA_XRUNRecovery               [internal]
477  *
478  * used to recovery from XRUN errors (buffer underflow/overflow)
479  */
480 static int ALSA_XRUNRecovery(WINE_WAVEOUT * wwo, int err)
481 {
482     if (err == -EPIPE) {    /* under-run */
483         err = snd_pcm_prepare(wwo->p_handle);
484         if (err < 0)
485              ERR( "underrun recovery failed. prepare failed: %s\n", snd_strerror(err));
486         return 0;
487     } else if (err == -ESTRPIPE) {
488         while ((err = snd_pcm_resume(wwo->p_handle)) == -EAGAIN)
489             sleep(1);       /* wait until the suspend flag is released */
490         if (err < 0) {
491             err = snd_pcm_prepare(wwo->p_handle);
492             if (err < 0)
493                 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
494         }
495         return 0;
496     }
497     return err;
498 }
499
500 /**************************************************************************
501  *                      ALSA_TraceParameters            [internal]
502  *
503  * used to trace format changes, hw and sw parameters
504  */
505 static void ALSA_TraceParameters(snd_pcm_hw_params_t * hw_params, snd_pcm_sw_params_t * sw, int full)
506 {
507     int err;
508     snd_pcm_format_t   format;
509     snd_pcm_access_t   access;
510
511     err = snd_pcm_hw_params_get_access(hw_params, &access);
512     err = snd_pcm_hw_params_get_format(hw_params, &format);
513
514 #define X(x) ((x)? "true" : "false")
515     if (full)
516         TRACE("FLAGS: sampleres=%s overrng=%s pause=%s resume=%s syncstart=%s batch=%s block=%s double=%s "
517               "halfd=%s joint=%s \n",
518               X(snd_pcm_hw_params_can_mmap_sample_resolution(hw_params)),
519               X(snd_pcm_hw_params_can_overrange(hw_params)),
520               X(snd_pcm_hw_params_can_pause(hw_params)),
521               X(snd_pcm_hw_params_can_resume(hw_params)),
522               X(snd_pcm_hw_params_can_sync_start(hw_params)),
523               X(snd_pcm_hw_params_is_batch(hw_params)),
524               X(snd_pcm_hw_params_is_block_transfer(hw_params)),
525               X(snd_pcm_hw_params_is_double(hw_params)),
526               X(snd_pcm_hw_params_is_half_duplex(hw_params)),
527               X(snd_pcm_hw_params_is_joint_duplex(hw_params)));
528 #undef X
529
530     if (access >= 0)
531         TRACE("access=%s\n", snd_pcm_access_name(access));
532     else
533     {
534         snd_pcm_access_mask_t * acmask;
535         snd_pcm_access_mask_alloca(&acmask);
536         snd_pcm_hw_params_get_access_mask(hw_params, acmask);
537         for ( access = SND_PCM_ACCESS_MMAP_INTERLEAVED; access <= SND_PCM_ACCESS_LAST; access++)
538             if (snd_pcm_access_mask_test(acmask, access))
539                 TRACE("access=%s\n", snd_pcm_access_name(access));
540     }
541
542     if (format >= 0)
543     {
544         TRACE("format=%s\n", snd_pcm_format_name(format));
545
546     }
547     else
548     {
549         snd_pcm_format_mask_t *     fmask;
550
551         snd_pcm_format_mask_alloca(&fmask);
552         snd_pcm_hw_params_get_format_mask(hw_params, fmask);
553         for ( format = SND_PCM_FORMAT_S8; format <= SND_PCM_FORMAT_LAST ; format++)
554             if ( snd_pcm_format_mask_test(fmask, format) )
555                 TRACE("format=%s\n", snd_pcm_format_name(format));
556     }
557
558     do {
559       int err=0;
560       unsigned int val=0;
561       err = snd_pcm_hw_params_get_channels(hw_params, &val); 
562       if (err<0) {
563         unsigned int min = 0;
564         unsigned int max = 0;
565         err = snd_pcm_hw_params_get_channels_min(hw_params, &min), 
566         err = snd_pcm_hw_params_get_channels_max(hw_params, &max); 
567         TRACE("channels_min=%u, channels_min_max=%u\n", min, max);
568       } else {
569         TRACE("channels_min=%d\n", val);
570       }
571     } while(0);
572     do {
573       int err=0;
574       snd_pcm_uframes_t val=0;
575       err = snd_pcm_hw_params_get_buffer_size(hw_params, &val); 
576       if (err<0) {
577         snd_pcm_uframes_t min = 0;
578         snd_pcm_uframes_t max = 0;
579         err = snd_pcm_hw_params_get_buffer_size_min(hw_params, &min), 
580         err = snd_pcm_hw_params_get_buffer_size_max(hw_params, &max); 
581         TRACE("buffer_size_min=%lu, buffer_size_min_max=%lu\n", min, max);
582       } else {
583         TRACE("buffer_size_min=%lu\n", val);
584       }
585     } while(0);
586
587 #define X(x) do { \
588 int err=0; \
589 int dir=0; \
590 unsigned int val=0; \
591 err = snd_pcm_hw_params_get_##x(hw_params,&val, &dir); \
592 if (err<0) { \
593   unsigned int min = 0; \
594   unsigned int max = 0; \
595   err = snd_pcm_hw_params_get_##x##_min(hw_params, &min, &dir); \
596   err = snd_pcm_hw_params_get_##x##_max(hw_params, &max, &dir); \
597   TRACE(#x "_min=%u " #x "_max=%u\n", min, max); \
598 } else \
599     TRACE(#x "=%d\n", val); \
600 } while(0)
601
602     X(rate);
603     X(buffer_time);
604     X(periods);
605     do {
606       int err=0;
607       int dir=0;
608       snd_pcm_uframes_t val=0;
609       err = snd_pcm_hw_params_get_period_size(hw_params, &val, &dir); 
610       if (err<0) {
611         snd_pcm_uframes_t min = 0;
612         snd_pcm_uframes_t max = 0;
613         err = snd_pcm_hw_params_get_period_size_min(hw_params, &min, &dir), 
614         err = snd_pcm_hw_params_get_period_size_max(hw_params, &max, &dir); 
615         TRACE("period_size_min=%lu, period_size_min_max=%lu\n", min, max);
616       } else {
617         TRACE("period_size_min=%lu\n", val);
618       }
619     } while(0);
620
621     X(period_time);
622     X(tick_time);
623 #undef X
624
625     if (!sw)
626         return;
627 }
628
629 /* return a string duplicated on the win32 process heap, free with HeapFree */
630 static char* ALSA_strdup(char *s) {
631     char *result = HeapAlloc(GetProcessHeap(), 0, strlen(s)+1);
632     strcpy(result, s);
633     return result;
634 }
635
636 /******************************************************************
637  *             ALSA_GetDeviceFromReg
638  *
639  * Returns either "default" or reads the registry so the user can
640  * override the playback/record device used.
641  */
642 static char *ALSA_GetDeviceFromReg(const char *value)
643 {
644     DWORD res;
645     DWORD type;
646     HKEY playbackKey = 0;
647     char *result = NULL;
648     DWORD resultSize;
649
650     res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\ALSA", 0, KEY_QUERY_VALUE, &playbackKey);
651     if (res != ERROR_SUCCESS) goto end;
652
653     res = RegQueryValueExA(playbackKey, value, NULL, &type, NULL, &resultSize);
654     if (res != ERROR_SUCCESS) goto end;
655
656     if (type != REG_SZ) {
657        ERR("Registry key [HKEY_LOCAL_MACHINE\\Software\\Wine\\Wine\\ALSA\\%s] must be a string\n", value);
658        goto end;
659     }
660
661     result = HeapAlloc(GetProcessHeap(), 0, resultSize);
662     res = RegQueryValueExA(playbackKey, value, NULL, NULL, result, &resultSize);
663
664 end:
665     if (!result) result = ALSA_strdup("default");
666     if (playbackKey) RegCloseKey(playbackKey);
667     return result;
668 }
669
670 /******************************************************************
671  *              ALSA_WaveInit
672  *
673  * Initialize internal structures from ALSA information
674  */
675 LONG ALSA_WaveInit(void)
676 {
677     snd_pcm_t*                  h;
678     snd_pcm_info_t *            info;
679     snd_pcm_hw_params_t *       hw_params;
680     unsigned int ratemin=0;
681     unsigned int ratemax=0;
682     unsigned int chmin=0;
683     unsigned int chmax=0;
684     int dir=0;
685     int err=0;
686     WINE_WAVEOUT*               wwo;
687     WINE_WAVEIN*                wwi;
688     static const WCHAR init_out[] = {'S','B','1','6',' ','W','a','v','e',' ','O','u','t',0};
689     static const WCHAR init_in [] = {'S','B','1','6',' ','W','a','v','e',' ','I','n',0};
690
691     wwo = &WOutDev[0];
692
693     /* FIXME: use better values */
694     wwo->device = ALSA_GetDeviceFromReg("PlaybackDevice");
695     TRACE("using waveout device \"%s\"\n", wwo->device);
696
697     snprintf(wwo->interface_name, sizeof(wwo->interface_name), "winealsa: %s", wwo->device);
698
699     wwo->caps.wMid = 0x0002;
700     wwo->caps.wPid = 0x0104;
701     strcpyW(wwo->caps.szPname, init_out);
702     wwo->caps.vDriverVersion = 0x0100;
703     wwo->caps.dwFormats = 0x00000000;
704     wwo->caps.dwSupport = WAVECAPS_VOLUME;
705     strcpy(wwo->ds_desc.szDesc, "WineALSA DirectSound Driver");
706     strcpy(wwo->ds_desc.szDrvname, "winealsa.drv");
707
708     if (!wine_dlopen("libasound.so.2", RTLD_LAZY|RTLD_GLOBAL, NULL, 0))
709     {
710         ERR("Error: ALSA lib needs to be loaded with flags RTLD_LAZY and RTLD_GLOBAL.\n");
711         return -1;
712     }
713
714     snd_pcm_info_alloca(&info);
715     snd_pcm_hw_params_alloca(&hw_params);
716
717 #define EXIT_ON_ERROR(f,txt) do { int err; if ( (err = (f) ) < 0) { ERR(txt ": %s\n", snd_strerror(err)); if (h) snd_pcm_close(h); return -1; } } while(0)
718
719     h = NULL;
720     ALSA_WodNumDevs = 0;
721     EXIT_ON_ERROR( snd_pcm_open(&h, wwo->device, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK) , "open pcm" );
722     if (!h) return -1;
723     ALSA_WodNumDevs++;
724
725     EXIT_ON_ERROR( snd_pcm_info(h, info) , "pcm info" );
726
727     TRACE("dev=%d id=%s name=%s subdev=%d subdev_name=%s subdev_avail=%d subdev_num=%d stream=%s subclass=%s \n",
728        snd_pcm_info_get_device(info),
729        snd_pcm_info_get_id(info),
730        snd_pcm_info_get_name(info),
731        snd_pcm_info_get_subdevice(info),
732        snd_pcm_info_get_subdevice_name(info),
733        snd_pcm_info_get_subdevices_avail(info),
734        snd_pcm_info_get_subdevices_count(info),
735        snd_pcm_stream_name(snd_pcm_info_get_stream(info)),
736        (snd_pcm_info_get_subclass(info) == SND_PCM_SUBCLASS_GENERIC_MIX ? "GENERIC MIX": "MULTI MIX"));
737
738     EXIT_ON_ERROR( snd_pcm_hw_params_any(h, hw_params) , "pcm hw params" );
739 #undef EXIT_ON_ERROR
740
741     err = snd_pcm_hw_params_get_rate_min(hw_params, &ratemin, &dir);
742     err = snd_pcm_hw_params_get_rate_max(hw_params, &ratemax, &dir);
743     err = snd_pcm_hw_params_get_channels_min(hw_params, &chmin);
744     err = snd_pcm_hw_params_get_channels_max(hw_params, &chmax);
745     if (TRACE_ON(wave))
746         ALSA_TraceParameters(hw_params, NULL, TRUE);
747
748     {
749         snd_pcm_format_mask_t *     fmask;
750
751         snd_pcm_format_mask_alloca(&fmask);
752         snd_pcm_hw_params_get_format_mask(hw_params, fmask);
753
754 #define X(r,v) \
755        if ( (r) >= ratemin && ( (r) <= ratemax || ratemax == -1) ) \
756        { \
757           if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_U8)) \
758           { \
759               if (chmin <= 1 && 1 <= chmax) \
760                   wwo->caps.dwFormats |= WAVE_FORMAT_##v##M08; \
761               if (chmin <= 2 && 2 <= chmax) \
762                   wwo->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
763           } \
764           if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_S16_LE)) \
765           { \
766               if (chmin <= 1 && 1 <= chmax) \
767                   wwo->caps.dwFormats |= WAVE_FORMAT_##v##M16; \
768               if (chmin <= 2 && 2 <= chmax) \
769                   wwo->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
770           } \
771        }
772        X(11025,1);
773        X(22050,2);
774        X(44100,4);
775        X(48000,48);
776        X(96000,96);
777 #undef X
778     }
779
780     if ( chmin > 1) FIXME("-\n");
781     wwo->caps.wChannels = chmax;
782     if (chmin <= 2 && 2 <= chmax)
783         wwo->caps.dwSupport |= WAVECAPS_LRVOLUME;
784
785     /* FIXME: always true ? */
786     wwo->caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
787
788     {
789         snd_pcm_access_mask_t *     acmask;
790         snd_pcm_access_mask_alloca(&acmask);
791         snd_pcm_hw_params_get_access_mask(hw_params, acmask);
792
793         /* FIXME: NONITERLEAVED and COMPLEX are not supported right now */
794         if ( snd_pcm_access_mask_test( acmask, SND_PCM_ACCESS_MMAP_INTERLEAVED ) )
795             wwo->caps.dwSupport |= WAVECAPS_DIRECTSOUND;
796     }
797
798     TRACE("Configured with dwFmts=%08lx dwSupport=%08lx\n",
799           wwo->caps.dwFormats, wwo->caps.dwSupport);
800
801     snd_pcm_close(h);
802
803     ALSA_InitializeVolumeCtl(wwo);
804
805     wwi = &WInDev[0];
806
807     /* FIXME: use better values */
808     wwi->device = ALSA_GetDeviceFromReg("RecordDevice");
809     TRACE("using wavein device \"%s\"\n", wwi->device);
810
811     snprintf(wwi->interface_name, sizeof(wwi->interface_name), "winealsa: %s", wwi->device);
812
813     wwi->caps.wMid = 0x0002;
814     wwi->caps.wPid = 0x0104;
815     strcpyW(wwi->caps.szPname, init_in);
816     wwi->caps.vDriverVersion = 0x0100;
817     wwi->caps.dwFormats = 0x00000000;
818     wwi->caps.dwSupport = WAVECAPS_VOLUME;
819     strcpy(wwi->ds_desc.szDesc, "WineALSA DirectSound Driver");
820     strcpy(wwi->ds_desc.szDrvname, "winealsa.drv");
821
822     snd_pcm_info_alloca(&info);
823     snd_pcm_hw_params_alloca(&hw_params);
824
825 #define EXIT_ON_ERROR(f,txt) do { int err; if ( (err = (f) ) < 0) { ERR(txt ": %s\n", snd_strerror(err)); if (h) snd_pcm_close(h); return -1; } } while(0)
826
827     h = NULL;
828     ALSA_WidNumDevs = 0;
829     EXIT_ON_ERROR( snd_pcm_open(&h, wwi->device, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK) , "open pcm" );
830     if (!h) return -1;
831     ALSA_WidNumDevs++;
832
833     EXIT_ON_ERROR( snd_pcm_info(h, info) , "pcm info" );
834
835     TRACE("dev=%d id=%s name=%s subdev=%d subdev_name=%s subdev_avail=%d subdev_num=%d stream=%s subclass=%s \n",
836        snd_pcm_info_get_device(info),
837        snd_pcm_info_get_id(info),
838        snd_pcm_info_get_name(info),
839        snd_pcm_info_get_subdevice(info),
840        snd_pcm_info_get_subdevice_name(info),
841        snd_pcm_info_get_subdevices_avail(info),
842        snd_pcm_info_get_subdevices_count(info),
843        snd_pcm_stream_name(snd_pcm_info_get_stream(info)),
844        (snd_pcm_info_get_subclass(info) == SND_PCM_SUBCLASS_GENERIC_MIX ? "GENERIC MIX": "MULTI MIX"));
845
846     EXIT_ON_ERROR( snd_pcm_hw_params_any(h, hw_params) , "pcm hw params" );
847 #undef EXIT_ON_ERROR
848     err = snd_pcm_hw_params_get_rate_min(hw_params, &ratemin, &dir);
849     err = snd_pcm_hw_params_get_rate_max(hw_params, &ratemax, &dir);
850     err = snd_pcm_hw_params_get_channels_min(hw_params, &chmin);
851     err = snd_pcm_hw_params_get_channels_max(hw_params, &chmax);
852
853     if (TRACE_ON(wave))
854         ALSA_TraceParameters(hw_params, NULL, TRUE);
855
856     {
857         snd_pcm_format_mask_t *     fmask;
858
859         snd_pcm_format_mask_alloca(&fmask);
860         snd_pcm_hw_params_get_format_mask(hw_params, fmask);
861
862 #define X(r,v) \
863        if ( (r) >= ratemin && ( (r) <= ratemax || ratemax == -1) ) \
864        { \
865           if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_U8)) \
866           { \
867               if (chmin <= 1 && 1 <= chmax) \
868                   wwi->caps.dwFormats |= WAVE_FORMAT_##v##M08; \
869               if (chmin <= 2 && 2 <= chmax) \
870                   wwi->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
871           } \
872           if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_S16_LE)) \
873           { \
874               if (chmin <= 1 && 1 <= chmax) \
875                   wwi->caps.dwFormats |= WAVE_FORMAT_##v##M16; \
876               if (chmin <= 2 && 2 <= chmax) \
877                   wwi->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
878           } \
879        }
880        X(11025,1);
881        X(22050,2);
882        X(44100,4);
883        X(48000,48);
884        X(96000,96);
885 #undef X
886     }
887
888     if ( chmin > 1) FIXME("-\n");
889     wwi->caps.wChannels = chmax;
890     if (chmin <= 2 && 2 <= chmax)
891         wwi->caps.dwSupport |= WAVECAPS_LRVOLUME;
892
893     /* FIXME: always true ? */
894     wwi->caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
895
896     {
897         snd_pcm_access_mask_t *     acmask;
898         snd_pcm_access_mask_alloca(&acmask);
899         snd_pcm_hw_params_get_access_mask(hw_params, acmask);
900
901         /* FIXME: NONITERLEAVED and COMPLEX are not supported right now */
902         if ( snd_pcm_access_mask_test( acmask, SND_PCM_ACCESS_MMAP_INTERLEAVED ) ) {
903 #if 0
904             wwi->caps.dwSupport |= WAVECAPS_DIRECTSOUND;
905 #endif
906         }
907     }
908
909     TRACE("Configured with dwFmts=%08lx dwSupport=%08lx\n",
910           wwi->caps.dwFormats, wwi->caps.dwSupport);
911
912     snd_pcm_close(h);
913     
914     return 0;
915 }
916
917 /******************************************************************
918  *              ALSA_InitRingMessage
919  *
920  * Initialize the ring of messages for passing between driver's caller and playback/record
921  * thread
922  */
923 static int ALSA_InitRingMessage(ALSA_MSG_RING* omr)
924 {
925     omr->msg_toget = 0;
926     omr->msg_tosave = 0;
927 #ifdef USE_PIPE_SYNC
928     if (pipe(omr->msg_pipe) < 0) {
929         omr->msg_pipe[0] = -1;
930         omr->msg_pipe[1] = -1;
931         ERR("could not create pipe, error=%s\n", strerror(errno));
932     }
933 #else
934     omr->msg_event = CreateEventW(NULL, FALSE, FALSE, NULL);
935 #endif
936     omr->ring_buffer_size = ALSA_RING_BUFFER_INCREMENT;
937     omr->messages = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,omr->ring_buffer_size * sizeof(ALSA_MSG));
938
939     InitializeCriticalSection(&omr->msg_crst);
940     return 0;
941 }
942
943 /******************************************************************
944  *              ALSA_DestroyRingMessage
945  *
946  */
947 static int ALSA_DestroyRingMessage(ALSA_MSG_RING* omr)
948 {
949 #ifdef USE_PIPE_SYNC
950     close(omr->msg_pipe[0]);
951     close(omr->msg_pipe[1]);
952 #else
953     CloseHandle(omr->msg_event);
954 #endif
955     HeapFree(GetProcessHeap(),0,omr->messages);
956     DeleteCriticalSection(&omr->msg_crst);
957     return 0;
958 }
959
960 /******************************************************************
961  *              ALSA_AddRingMessage
962  *
963  * Inserts a new message into the ring (should be called from DriverProc derivated routines)
964  */
965 static int ALSA_AddRingMessage(ALSA_MSG_RING* omr, enum win_wm_message msg, DWORD param, BOOL wait)
966 {
967     HANDLE      hEvent = INVALID_HANDLE_VALUE;
968
969     EnterCriticalSection(&omr->msg_crst);
970     if ((omr->msg_toget == ((omr->msg_tosave + 1) % omr->ring_buffer_size)))
971     {
972         int old_ring_buffer_size = omr->ring_buffer_size;
973         omr->ring_buffer_size += ALSA_RING_BUFFER_INCREMENT;
974         TRACE("omr->ring_buffer_size=%d\n",omr->ring_buffer_size);
975         omr->messages = HeapReAlloc(GetProcessHeap(),0,omr->messages, omr->ring_buffer_size * sizeof(ALSA_MSG));
976         /* Now we need to rearrange the ring buffer so that the new
977            buffers just allocated are in between omr->msg_tosave and
978            omr->msg_toget.
979         */
980         if (omr->msg_tosave < omr->msg_toget)
981         {
982             memmove(&(omr->messages[omr->msg_toget + ALSA_RING_BUFFER_INCREMENT]),
983                     &(omr->messages[omr->msg_toget]),
984                     sizeof(ALSA_MSG)*(old_ring_buffer_size - omr->msg_toget)
985                     );
986             omr->msg_toget += ALSA_RING_BUFFER_INCREMENT;
987         }
988     }
989     if (wait)
990     {
991         hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
992         if (hEvent == INVALID_HANDLE_VALUE)
993         {
994             ERR("can't create event !?\n");
995             LeaveCriticalSection(&omr->msg_crst);
996             return 0;
997         }
998         if (omr->msg_toget != omr->msg_tosave && omr->messages[omr->msg_toget].msg != WINE_WM_HEADER)
999             FIXME("two fast messages in the queue!!!! toget = %d(%s), tosave=%d(%s)\n",
1000                   omr->msg_toget,getCmdString(omr->messages[omr->msg_toget].msg),
1001                   omr->msg_tosave,getCmdString(omr->messages[omr->msg_tosave].msg));
1002
1003         /* fast messages have to be added at the start of the queue */
1004         omr->msg_toget = (omr->msg_toget + omr->ring_buffer_size - 1) % omr->ring_buffer_size;
1005
1006         omr->messages[omr->msg_toget].msg = msg;
1007         omr->messages[omr->msg_toget].param = param;
1008         omr->messages[omr->msg_toget].hEvent = hEvent;
1009     }
1010     else
1011     {
1012         omr->messages[omr->msg_tosave].msg = msg;
1013         omr->messages[omr->msg_tosave].param = param;
1014         omr->messages[omr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
1015         omr->msg_tosave = (omr->msg_tosave + 1) % omr->ring_buffer_size;
1016     }
1017     LeaveCriticalSection(&omr->msg_crst);
1018     /* signal a new message */
1019     SIGNAL_OMR(omr);
1020     if (wait)
1021     {
1022         /* wait for playback/record thread to have processed the message */
1023         WaitForSingleObject(hEvent, INFINITE);
1024         CloseHandle(hEvent);
1025     }
1026     return 1;
1027 }
1028
1029 /******************************************************************
1030  *              ALSA_RetrieveRingMessage
1031  *
1032  * Get a message from the ring. Should be called by the playback/record thread.
1033  */
1034 static int ALSA_RetrieveRingMessage(ALSA_MSG_RING* omr,
1035                                    enum win_wm_message *msg, DWORD *param, HANDLE *hEvent)
1036 {
1037     EnterCriticalSection(&omr->msg_crst);
1038
1039     if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
1040     {
1041         LeaveCriticalSection(&omr->msg_crst);
1042         return 0;
1043     }
1044
1045     *msg = omr->messages[omr->msg_toget].msg;
1046     omr->messages[omr->msg_toget].msg = 0;
1047     *param = omr->messages[omr->msg_toget].param;
1048     *hEvent = omr->messages[omr->msg_toget].hEvent;
1049     omr->msg_toget = (omr->msg_toget + 1) % omr->ring_buffer_size;
1050     CLEAR_OMR(omr);
1051     LeaveCriticalSection(&omr->msg_crst);
1052     return 1;
1053 }
1054
1055 /******************************************************************
1056  *              ALSA_PeekRingMessage
1057  *
1058  * Peek at a message from the ring but do not remove it.
1059  * Should be called by the playback/record thread.
1060  */
1061 static int ALSA_PeekRingMessage(ALSA_MSG_RING* omr,
1062                                enum win_wm_message *msg,
1063                                DWORD *param, HANDLE *hEvent)
1064 {
1065     EnterCriticalSection(&omr->msg_crst);
1066
1067     if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
1068     {
1069         LeaveCriticalSection(&omr->msg_crst);
1070         return 0;
1071     }
1072
1073     *msg = omr->messages[omr->msg_toget].msg;
1074     *param = omr->messages[omr->msg_toget].param;
1075     *hEvent = omr->messages[omr->msg_toget].hEvent;
1076     LeaveCriticalSection(&omr->msg_crst);
1077     return 1;
1078 }
1079
1080 /*======================================================================*
1081  *                  Low level WAVE OUT implementation                   *
1082  *======================================================================*/
1083
1084 /**************************************************************************
1085  *                      wodNotifyClient                 [internal]
1086  */
1087 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1088 {
1089     TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
1090
1091     switch (wMsg) {
1092     case WOM_OPEN:
1093     case WOM_CLOSE:
1094     case WOM_DONE:
1095         if (wwo->wFlags != DCB_NULL &&
1096             !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags, (HDRVR)wwo->waveDesc.hWave,
1097                             wMsg, wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
1098             WARN("can't notify client !\n");
1099             return MMSYSERR_ERROR;
1100         }
1101         break;
1102     default:
1103         FIXME("Unknown callback message %u\n", wMsg);
1104         return MMSYSERR_INVALPARAM;
1105     }
1106     return MMSYSERR_NOERROR;
1107 }
1108
1109 /**************************************************************************
1110  *                              wodUpdatePlayedTotal    [internal]
1111  *
1112  */
1113 static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo, snd_pcm_status_t* ps)
1114 {
1115     snd_pcm_sframes_t delay = 0;
1116     snd_pcm_delay(wwo->p_handle, &delay);
1117     if (snd_pcm_state(wwo->p_handle) != SND_PCM_STATE_RUNNING)
1118         delay=0;
1119     wwo->dwPlayedTotal = wwo->dwWrittenTotal - snd_pcm_frames_to_bytes(wwo->p_handle, delay);
1120     return TRUE;
1121 }
1122
1123 /**************************************************************************
1124  *                              wodPlayer_BeginWaveHdr          [internal]
1125  *
1126  * Makes the specified lpWaveHdr the currently playing wave header.
1127  * If the specified wave header is a begin loop and we're not already in
1128  * a loop, setup the loop.
1129  */
1130 static void wodPlayer_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1131 {
1132     wwo->lpPlayPtr = lpWaveHdr;
1133
1134     if (!lpWaveHdr) return;
1135
1136     if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
1137         if (wwo->lpLoopPtr) {
1138             WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1139         } else {
1140             TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1141             wwo->lpLoopPtr = lpWaveHdr;
1142             /* Windows does not touch WAVEHDR.dwLoops,
1143              * so we need to make an internal copy */
1144             wwo->dwLoops = lpWaveHdr->dwLoops;
1145         }
1146     }
1147     wwo->dwPartialOffset = 0;
1148 }
1149
1150 /**************************************************************************
1151  *                              wodPlayer_PlayPtrNext           [internal]
1152  *
1153  * Advance the play pointer to the next waveheader, looping if required.
1154  */
1155 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEOUT* wwo)
1156 {
1157     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1158
1159     wwo->dwPartialOffset = 0;
1160     if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
1161         /* We're at the end of a loop, loop if required */
1162         if (--wwo->dwLoops > 0) {
1163             wwo->lpPlayPtr = wwo->lpLoopPtr;
1164         } else {
1165             /* Handle overlapping loops correctly */
1166             if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
1167                 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
1168                 /* shall we consider the END flag for the closing loop or for
1169                  * the opening one or for both ???
1170                  * code assumes for closing loop only
1171                  */
1172             } else {
1173                 lpWaveHdr = lpWaveHdr->lpNext;
1174             }
1175             wwo->lpLoopPtr = NULL;
1176             wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
1177         }
1178     } else {
1179         /* We're not in a loop.  Advance to the next wave header */
1180         wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
1181     }
1182
1183     return lpWaveHdr;
1184 }
1185
1186 /**************************************************************************
1187  *                           wodPlayer_DSPWait                  [internal]
1188  * Returns the number of milliseconds to wait for the DSP buffer to play a
1189  * period
1190  */
1191 static DWORD wodPlayer_DSPWait(const WINE_WAVEOUT *wwo)
1192 {
1193     /* time for one period to be played */
1194     unsigned int val=0;
1195     int dir=0;
1196     int err=0;
1197     err = snd_pcm_hw_params_get_period_time(wwo->hw_params, &val, &dir);
1198     return val / 1000;
1199 }
1200
1201 /**************************************************************************
1202  *                           wodPlayer_NotifyWait               [internal]
1203  * Returns the number of milliseconds to wait before attempting to notify
1204  * completion of the specified wavehdr.
1205  * This is based on the number of bytes remaining to be written in the
1206  * wave.
1207  */
1208 static DWORD wodPlayer_NotifyWait(const WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1209 {
1210     DWORD dwMillis;
1211
1212     if (lpWaveHdr->reserved < wwo->dwPlayedTotal) {
1213         dwMillis = 1;
1214     } else {
1215         dwMillis = (lpWaveHdr->reserved - wwo->dwPlayedTotal) * 1000 / wwo->format.Format.nAvgBytesPerSec;
1216         if (!dwMillis) dwMillis = 1;
1217     }
1218
1219     return dwMillis;
1220 }
1221
1222
1223 /**************************************************************************
1224  *                           wodPlayer_WriteMaxFrags            [internal]
1225  * Writes the maximum number of frames possible to the DSP and returns
1226  * the number of frames written.
1227  */
1228 static int wodPlayer_WriteMaxFrags(WINE_WAVEOUT* wwo, DWORD* frames)
1229 {
1230     /* Only attempt to write to free frames */
1231     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1232     DWORD dwLength = snd_pcm_bytes_to_frames(wwo->p_handle, lpWaveHdr->dwBufferLength - wwo->dwPartialOffset);
1233     int toWrite = min(dwLength, *frames);
1234     int written;
1235
1236     TRACE("Writing wavehdr %p.%lu[%lu]\n", lpWaveHdr, wwo->dwPartialOffset, lpWaveHdr->dwBufferLength);
1237
1238     if (toWrite > 0) {
1239         written = (wwo->write)(wwo->p_handle, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
1240         if ( written < 0) {
1241             /* XRUN occurred. let's try to recover */
1242             ALSA_XRUNRecovery(wwo, written);
1243             written = (wwo->write)(wwo->p_handle, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
1244         }
1245         if (written <= 0) {
1246             /* still in error */
1247             ERR("Error in writing wavehdr. Reason: %s\n", snd_strerror(written));
1248             return written;
1249         }
1250     } else
1251         written = 0;
1252
1253     wwo->dwPartialOffset += snd_pcm_frames_to_bytes(wwo->p_handle, written);
1254     if ( wwo->dwPartialOffset >= lpWaveHdr->dwBufferLength) {
1255         /* this will be used to check if the given wave header has been fully played or not... */
1256         wwo->dwPartialOffset = lpWaveHdr->dwBufferLength;
1257         /* If we wrote all current wavehdr, skip to the next one */
1258         wodPlayer_PlayPtrNext(wwo);
1259     }
1260     *frames -= written;
1261     wwo->dwWrittenTotal += snd_pcm_frames_to_bytes(wwo->p_handle, written);
1262     TRACE("dwWrittenTotal=%lu\n", wwo->dwWrittenTotal);
1263
1264     return written;
1265 }
1266
1267
1268 /**************************************************************************
1269  *                              wodPlayer_NotifyCompletions     [internal]
1270  *
1271  * Notifies and remove from queue all wavehdrs which have been played to
1272  * the speaker (ie. they have cleared the ALSA buffer).  If force is true,
1273  * we notify all wavehdrs and remove them all from the queue even if they
1274  * are unplayed or part of a loop.
1275  */
1276 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1277 {
1278     LPWAVEHDR           lpWaveHdr;
1279
1280     /* Start from lpQueuePtr and keep notifying until:
1281      * - we hit an unwritten wavehdr
1282      * - we hit the beginning of a running loop
1283      * - we hit a wavehdr which hasn't finished playing
1284      */
1285 #if 0
1286     while ((lpWaveHdr = wwo->lpQueuePtr) &&
1287            (force ||
1288             (lpWaveHdr != wwo->lpPlayPtr &&
1289              lpWaveHdr != wwo->lpLoopPtr &&
1290              lpWaveHdr->reserved <= wwo->dwPlayedTotal))) {
1291
1292         wwo->lpQueuePtr = lpWaveHdr->lpNext;
1293
1294         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1295         lpWaveHdr->dwFlags |= WHDR_DONE;
1296
1297         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1298     }
1299 #else
1300     for (;;)
1301     {
1302         lpWaveHdr = wwo->lpQueuePtr;
1303         if (!lpWaveHdr) {TRACE("Empty queue\n"); break;}
1304         if (!force)
1305         {
1306             if (lpWaveHdr == wwo->lpPlayPtr) {TRACE("play %p\n", lpWaveHdr); break;}
1307             if (lpWaveHdr == wwo->lpLoopPtr) {TRACE("loop %p\n", lpWaveHdr); break;}
1308             if (lpWaveHdr->reserved > wwo->dwPlayedTotal){TRACE("still playing %p (%lu/%lu)\n", lpWaveHdr, lpWaveHdr->reserved, wwo->dwPlayedTotal);break;}
1309         }
1310         wwo->lpQueuePtr = lpWaveHdr->lpNext;
1311
1312         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1313         lpWaveHdr->dwFlags |= WHDR_DONE;
1314
1315         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1316     }
1317 #endif
1318     return  (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
1319         wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
1320 }
1321
1322
1323 static void wait_for_poll(snd_pcm_t *handle, struct pollfd *ufds, unsigned int count)
1324 {
1325     unsigned short revents;
1326
1327     if (snd_pcm_state(handle) != SND_PCM_STATE_RUNNING)
1328         return;
1329
1330     while (1) {
1331         poll(ufds, count, -1);
1332         snd_pcm_poll_descriptors_revents(handle, ufds, count, &revents);
1333
1334         if (revents & POLLERR)
1335             return;
1336
1337         /*if (revents & POLLOUT)
1338                 return 0;*/
1339     }
1340 }
1341
1342
1343 /**************************************************************************
1344  *                              wodPlayer_Reset                 [internal]
1345  *
1346  * wodPlayer helper. Resets current output stream.
1347  */
1348 static  void    wodPlayer_Reset(WINE_WAVEOUT* wwo)
1349 {
1350     enum win_wm_message msg;
1351     DWORD                       param;
1352     HANDLE                      ev;
1353     int                         err;
1354
1355     /* flush all possible output */
1356     wait_for_poll(wwo->p_handle, wwo->ufds, wwo->count);
1357
1358     wodUpdatePlayedTotal(wwo, NULL);
1359     /* updates current notify list */
1360     wodPlayer_NotifyCompletions(wwo, FALSE);
1361
1362     if ( (err = snd_pcm_drop(wwo->p_handle)) < 0) {
1363         FIXME("flush: %s\n", snd_strerror(err));
1364         wwo->hThread = 0;
1365         wwo->state = WINE_WS_STOPPED;
1366         ExitThread(-1);
1367     }
1368     if ( (err = snd_pcm_prepare(wwo->p_handle)) < 0 )
1369         ERR("pcm prepare failed: %s\n", snd_strerror(err));
1370
1371     /* remove any buffer */
1372     wodPlayer_NotifyCompletions(wwo, TRUE);
1373
1374     wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1375     wwo->state = WINE_WS_STOPPED;
1376     wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1377     /* Clear partial wavehdr */
1378     wwo->dwPartialOffset = 0;
1379
1380     /* remove any existing message in the ring */
1381     EnterCriticalSection(&wwo->msgRing.msg_crst);
1382     /* return all pending headers in queue */
1383     while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
1384     {
1385         if (msg != WINE_WM_HEADER)
1386         {
1387             FIXME("shouldn't have headers left\n");
1388             SetEvent(ev);
1389             continue;
1390         }
1391         ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
1392         ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
1393
1394         wodNotifyClient(wwo, WOM_DONE, param, 0);
1395     }
1396     RESET_OMR(&wwo->msgRing);
1397     LeaveCriticalSection(&wwo->msgRing.msg_crst);
1398 }
1399
1400 /**************************************************************************
1401  *                    wodPlayer_ProcessMessages                 [internal]
1402  */
1403 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
1404 {
1405     LPWAVEHDR           lpWaveHdr;
1406     enum win_wm_message msg;
1407     DWORD               param;
1408     HANDLE              ev;
1409     int                 err;
1410
1411     while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
1412      TRACE("Received %s %lx\n", getCmdString(msg), param); 
1413
1414         switch (msg) {
1415         case WINE_WM_PAUSING:
1416             if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_RUNNING )
1417              {
1418                 err = snd_pcm_pause(wwo->p_handle, 1);
1419                 if ( err < 0 )
1420                     ERR("pcm_pause failed: %s\n", snd_strerror(err));
1421              }
1422             wwo->state = WINE_WS_PAUSED;
1423             SetEvent(ev);
1424             break;
1425         case WINE_WM_RESTARTING:
1426             if (wwo->state == WINE_WS_PAUSED)
1427             {
1428                 if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_PAUSED )
1429                  {
1430                     err = snd_pcm_pause(wwo->p_handle, 0);
1431                     if ( err < 0 )
1432                         ERR("pcm_pause failed: %s\n", snd_strerror(err));
1433                  }
1434                 wwo->state = WINE_WS_PLAYING;
1435             }
1436             SetEvent(ev);
1437             break;
1438         case WINE_WM_HEADER:
1439             lpWaveHdr = (LPWAVEHDR)param;
1440
1441             /* insert buffer at the end of queue */
1442             {
1443                 LPWAVEHDR*      wh;
1444                 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1445                 *wh = lpWaveHdr;
1446             }
1447             if (!wwo->lpPlayPtr)
1448                 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
1449             if (wwo->state == WINE_WS_STOPPED)
1450                 wwo->state = WINE_WS_PLAYING;
1451             break;
1452         case WINE_WM_RESETTING:
1453             wodPlayer_Reset(wwo);
1454             SetEvent(ev);
1455             break;
1456         case WINE_WM_UPDATE:
1457             wodUpdatePlayedTotal(wwo, NULL);
1458             SetEvent(ev);
1459             break;
1460         case WINE_WM_BREAKLOOP:
1461             if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
1462                 /* ensure exit at end of current loop */
1463                 wwo->dwLoops = 1;
1464             }
1465             SetEvent(ev);
1466             break;
1467         case WINE_WM_CLOSING:
1468             /* sanity check: this should not happen since the device must have been reset before */
1469             if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1470             wwo->hThread = 0;
1471             wwo->state = WINE_WS_CLOSED;
1472             SetEvent(ev);
1473             ExitThread(0);
1474             /* shouldn't go here */
1475         default:
1476             FIXME("unknown message %d\n", msg);
1477             break;
1478         }
1479     }
1480 }
1481
1482 /**************************************************************************
1483  *                           wodPlayer_FeedDSP                  [internal]
1484  * Feed as much sound data as we can into the DSP and return the number of
1485  * milliseconds before it will be necessary to feed the DSP again.
1486  */
1487 static DWORD wodPlayer_FeedDSP(WINE_WAVEOUT* wwo)
1488 {
1489     DWORD               availInQ;
1490
1491     wodUpdatePlayedTotal(wwo, NULL);
1492     availInQ = snd_pcm_avail_update(wwo->p_handle);
1493
1494 #if 0
1495     /* input queue empty and output buffer with less than one fragment to play */
1496     if (!wwo->lpPlayPtr && wwo->dwBufferSize < availInQ + wwo->dwFragmentSize) {
1497         TRACE("Run out of wavehdr:s...\n");
1498         return INFINITE;
1499     }
1500 #endif
1501
1502     /* no more room... no need to try to feed */
1503     if (availInQ > 0) {
1504         /* Feed from partial wavehdr */
1505         if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0) {
1506             wodPlayer_WriteMaxFrags(wwo, &availInQ);
1507         }
1508
1509         /* Feed wavehdrs until we run out of wavehdrs or DSP space */
1510         if (wwo->dwPartialOffset == 0 && wwo->lpPlayPtr) {
1511             do {
1512                 TRACE("Setting time to elapse for %p to %lu\n",
1513                       wwo->lpPlayPtr, wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength);
1514                 /* note the value that dwPlayedTotal will return when this wave finishes playing */
1515                 wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
1516             } while (wodPlayer_WriteMaxFrags(wwo, &availInQ) && wwo->lpPlayPtr && availInQ > 0);
1517         }
1518     }
1519
1520     return wodPlayer_DSPWait(wwo);
1521 }
1522
1523 /**************************************************************************
1524  *                              wodPlayer                       [internal]
1525  */
1526 static  DWORD   CALLBACK        wodPlayer(LPVOID pmt)
1527 {
1528     WORD          uDevID = (DWORD)pmt;
1529     WINE_WAVEOUT* wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
1530     DWORD         dwNextFeedTime = INFINITE;   /* Time before DSP needs feeding */
1531     DWORD         dwNextNotifyTime = INFINITE; /* Time before next wave completion */
1532     DWORD         dwSleepTime;
1533
1534     wwo->state = WINE_WS_STOPPED;
1535     SetEvent(wwo->hStartUpEvent);
1536
1537     for (;;) {
1538         /** Wait for the shortest time before an action is required.  If there
1539          *  are no pending actions, wait forever for a command.
1540          */
1541         dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
1542         TRACE("waiting %lums (%lu,%lu)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
1543         WAIT_OMR(&wwo->msgRing, dwSleepTime);
1544         wodPlayer_ProcessMessages(wwo);
1545         if (wwo->state == WINE_WS_PLAYING) {
1546             dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1547             dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1548             if (dwNextFeedTime == INFINITE) {
1549                 /* FeedDSP ran out of data, but before giving up, */
1550                 /* check that a notification didn't give us more */
1551                 wodPlayer_ProcessMessages(wwo);
1552                 if (wwo->lpPlayPtr) {
1553                     TRACE("recovering\n");
1554                     dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1555                 }
1556             }
1557         } else {
1558             dwNextFeedTime = dwNextNotifyTime = INFINITE;
1559         }
1560     }
1561 }
1562
1563 /**************************************************************************
1564  *                      wodGetDevCaps                           [internal]
1565  */
1566 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
1567 {
1568     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1569
1570     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1571
1572     if (wDevID >= MAX_WAVEOUTDRV) {
1573         TRACE("MAX_WAVOUTDRV reached !\n");
1574         return MMSYSERR_BADDEVICEID;
1575     }
1576
1577     memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1578     return MMSYSERR_NOERROR;
1579 }
1580
1581 /**************************************************************************
1582  *                              wodOpen                         [internal]
1583  */
1584 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1585 {
1586     WINE_WAVEOUT*               wwo;
1587     snd_pcm_hw_params_t *       hw_params;
1588     snd_pcm_sw_params_t *       sw_params;
1589     snd_pcm_access_t            access;
1590     snd_pcm_format_t            format = -1;
1591     unsigned int                rate;
1592     unsigned int                buffer_time = 500000;
1593     unsigned int                period_time = 10000;
1594     snd_pcm_uframes_t           buffer_size;
1595     snd_pcm_uframes_t           period_size;
1596     int                         flags;
1597     snd_pcm_t *                 pcm;
1598     int                         err=0;
1599     int                         dir=0;
1600
1601     snd_pcm_hw_params_alloca(&hw_params);
1602     snd_pcm_sw_params_alloca(&sw_params);
1603
1604     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
1605     if (lpDesc == NULL) {
1606         WARN("Invalid Parameter !\n");
1607         return MMSYSERR_INVALPARAM;
1608     }
1609     if (wDevID >= MAX_WAVEOUTDRV) {
1610         TRACE("MAX_WAVOUTDRV reached !\n");
1611         return MMSYSERR_BADDEVICEID;
1612     }
1613
1614     /* only PCM format is supported so far... */
1615     if (!supportedFormat(lpDesc->lpFormat)) {
1616         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1617              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1618              lpDesc->lpFormat->nSamplesPerSec);
1619         return WAVERR_BADFORMAT;
1620     }
1621
1622     if (dwFlags & WAVE_FORMAT_QUERY) {
1623         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1624              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1625              lpDesc->lpFormat->nSamplesPerSec);
1626         return MMSYSERR_NOERROR;
1627     }
1628
1629     wwo = &WOutDev[wDevID];
1630
1631     if ((dwFlags & WAVE_DIRECTSOUND) && !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
1632         /* not supported, ignore it */
1633         dwFlags &= ~WAVE_DIRECTSOUND;
1634
1635     wwo->p_handle = 0;
1636     flags = SND_PCM_NONBLOCK;
1637 #if 0
1638     if ( dwFlags & WAVE_DIRECTSOUND )
1639         flags |= SND_PCM_ASYNC;
1640 #endif
1641
1642     if ( (err = snd_pcm_open(&pcm, wwo->device, SND_PCM_STREAM_PLAYBACK, flags)) < 0)
1643     {
1644         ERR("Error open: %s\n", snd_strerror(err));
1645         return MMSYSERR_NOTENABLED;
1646     }
1647
1648     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1649
1650     memcpy(&wwo->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
1651     copy_format(lpDesc->lpFormat, &wwo->format);
1652
1653     if (wwo->format.Format.wBitsPerSample == 0) {
1654         WARN("Resetting zeroed wBitsPerSample\n");
1655         wwo->format.Format.wBitsPerSample = 8 *
1656             (wwo->format.Format.nAvgBytesPerSec /
1657              wwo->format.Format.nSamplesPerSec) /
1658             wwo->format.Format.nChannels;
1659     }
1660
1661     snd_pcm_hw_params_any(pcm, hw_params);
1662
1663 #define EXIT_ON_ERROR(f,e,txt) do \
1664 { \
1665     int err; \
1666     if ( (err = (f) ) < 0) \
1667     { \
1668         ERR(txt ": %s\n", snd_strerror(err)); \
1669         snd_pcm_close(pcm); \
1670         return e; \
1671     } \
1672 } while(0)
1673
1674     access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
1675     if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
1676         WARN("mmap not available. switching to standard write.\n");
1677         access = SND_PCM_ACCESS_RW_INTERLEAVED;
1678         EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
1679         wwo->write = snd_pcm_writei;
1680     }
1681     else
1682         wwo->write = snd_pcm_mmap_writei;
1683
1684     EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwo->format.Format.nChannels), MMSYSERR_INVALPARAM, "unable to set required channels");
1685
1686     if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
1687         ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
1688         IsEqualGUID(&wwo->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
1689         format = (wwo->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
1690                  (wwo->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
1691                  (wwo->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
1692                  (wwo->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
1693     } else if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
1694         IsEqualGUID(&wwo->format.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)){
1695         format = (wwo->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_FLOAT_LE : -1;
1696     } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
1697         FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
1698         snd_pcm_close(pcm);
1699         return WAVERR_BADFORMAT;
1700     } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
1701         FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
1702         snd_pcm_close(pcm);
1703         return WAVERR_BADFORMAT;
1704     } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
1705         FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
1706         snd_pcm_close(pcm);
1707         return WAVERR_BADFORMAT;
1708     } else {
1709         ERR("invalid format: %0x04x\n", wwo->format.Format.wFormatTag);
1710         snd_pcm_close(pcm);
1711         return WAVERR_BADFORMAT;
1712     }
1713
1714     EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), MMSYSERR_INVALPARAM, "unable to set required format");
1715
1716     rate = wwo->format.Format.nSamplesPerSec;
1717     dir=0;
1718     err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
1719     if (err < 0) {
1720         ERR("Rate %ld Hz not available for playback: %s\n", wwo->format.Format.nSamplesPerSec, snd_strerror(rate));
1721         snd_pcm_close(pcm);
1722         return WAVERR_BADFORMAT;
1723     }
1724     if (rate != wwo->format.Format.nSamplesPerSec) {
1725         ERR("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwo->format.Format.nSamplesPerSec, rate);
1726         snd_pcm_close(pcm);
1727         return WAVERR_BADFORMAT;
1728     }
1729     dir=0; 
1730     EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
1731     dir=0; 
1732     EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
1733
1734     EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
1735     
1736     err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
1737     err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
1738
1739     snd_pcm_sw_params_current(pcm, sw_params);
1740     EXIT_ON_ERROR( snd_pcm_sw_params_set_start_threshold(pcm, sw_params, dwFlags & WAVE_DIRECTSOUND ? INT_MAX : 1 ), MMSYSERR_ERROR, "unable to set start threshold");
1741     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
1742     EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
1743     EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
1744     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
1745     EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
1746 #undef EXIT_ON_ERROR
1747
1748     snd_pcm_prepare(pcm);
1749
1750     if (TRACE_ON(wave))
1751         ALSA_TraceParameters(hw_params, sw_params, FALSE);
1752
1753     /* now, we can save all required data for later use... */
1754     if ( wwo->hw_params )
1755         snd_pcm_hw_params_free(wwo->hw_params);
1756     snd_pcm_hw_params_malloc(&(wwo->hw_params));
1757     snd_pcm_hw_params_copy(wwo->hw_params, hw_params);
1758
1759     wwo->dwBufferSize = buffer_size;
1760     wwo->lpQueuePtr = wwo->lpPlayPtr = wwo->lpLoopPtr = NULL;
1761     wwo->p_handle = pcm;
1762     wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1763     wwo->dwPartialOffset = 0;
1764
1765     ALSA_InitRingMessage(&wwo->msgRing);
1766
1767     wwo->count = snd_pcm_poll_descriptors_count (wwo->p_handle);
1768     if (wwo->count <= 0) {
1769         ERR("Invalid poll descriptors count\n");
1770         return MMSYSERR_ERROR;
1771     }
1772
1773     wwo->ufds = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct pollfd) * wwo->count);
1774     if (wwo->ufds == NULL) {
1775         ERR("No enough memory\n");
1776         return MMSYSERR_NOMEM;
1777     }
1778     if ((err = snd_pcm_poll_descriptors(wwo->p_handle, wwo->ufds, wwo->count)) < 0) {
1779         ERR("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
1780         return MMSYSERR_ERROR;
1781     }
1782
1783     if (!(dwFlags & WAVE_DIRECTSOUND)) {
1784         wwo->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1785         wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
1786         WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
1787         CloseHandle(wwo->hStartUpEvent);
1788     } else {
1789         wwo->hThread = INVALID_HANDLE_VALUE;
1790         wwo->dwThreadID = 0;
1791     }
1792     wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
1793
1794     TRACE("handle=%08lx \n", (DWORD)wwo->p_handle);
1795 /*    if (wwo->dwFragmentSize % wwo->format.Format.nBlockAlign)
1796         ERR("Fragment doesn't contain an integral number of data blocks\n");
1797 */
1798     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
1799           wwo->format.Format.wBitsPerSample, wwo->format.Format.nAvgBytesPerSec,
1800           wwo->format.Format.nSamplesPerSec, wwo->format.Format.nChannels,
1801           wwo->format.Format.nBlockAlign);
1802
1803     return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
1804 }
1805
1806
1807 /**************************************************************************
1808  *                              wodClose                        [internal]
1809  */
1810 static DWORD wodClose(WORD wDevID)
1811 {
1812     DWORD               ret = MMSYSERR_NOERROR;
1813     WINE_WAVEOUT*       wwo;
1814
1815     TRACE("(%u);\n", wDevID);
1816
1817     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1818         WARN("bad device ID !\n");
1819         return MMSYSERR_BADDEVICEID;
1820     }
1821
1822     wwo = &WOutDev[wDevID];
1823     if (wwo->lpQueuePtr) {
1824         WARN("buffers still playing !\n");
1825         ret = WAVERR_STILLPLAYING;
1826     } else {
1827         if (wwo->hThread != INVALID_HANDLE_VALUE) {
1828             ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1829         }
1830         ALSA_DestroyRingMessage(&wwo->msgRing);
1831
1832         snd_pcm_hw_params_free(wwo->hw_params);
1833         wwo->hw_params = NULL;
1834
1835         snd_pcm_close(wwo->p_handle);
1836         wwo->p_handle = NULL;
1837
1838         ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1839     }
1840
1841     HeapFree(GetProcessHeap(), 0, wwo->ufds);
1842     return ret;
1843 }
1844
1845
1846 /**************************************************************************
1847  *                              wodWrite                        [internal]
1848  *
1849  */
1850 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1851 {
1852     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1853
1854     /* first, do the sanity checks... */
1855     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1856         WARN("bad dev ID !\n");
1857         return MMSYSERR_BADDEVICEID;
1858     }
1859
1860     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1861         return WAVERR_UNPREPARED;
1862
1863     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1864         return WAVERR_STILLPLAYING;
1865
1866     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1867     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1868     lpWaveHdr->lpNext = 0;
1869
1870     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1871
1872     return MMSYSERR_NOERROR;
1873 }
1874
1875 /**************************************************************************
1876  *                              wodPrepare                      [internal]
1877  */
1878 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1879 {
1880     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1881
1882     if (wDevID >= MAX_WAVEOUTDRV) {
1883         WARN("bad device ID !\n");
1884         return MMSYSERR_BADDEVICEID;
1885     }
1886
1887     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1888         return WAVERR_STILLPLAYING;
1889
1890     lpWaveHdr->dwFlags |= WHDR_PREPARED;
1891     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1892     return MMSYSERR_NOERROR;
1893 }
1894
1895 /**************************************************************************
1896  *                              wodUnprepare                    [internal]
1897  */
1898 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1899 {
1900     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1901
1902     if (wDevID >= MAX_WAVEOUTDRV) {
1903         WARN("bad device ID !\n");
1904         return MMSYSERR_BADDEVICEID;
1905     }
1906
1907     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1908         return WAVERR_STILLPLAYING;
1909
1910     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1911     lpWaveHdr->dwFlags |= WHDR_DONE;
1912
1913     return MMSYSERR_NOERROR;
1914 }
1915
1916 /**************************************************************************
1917  *                      wodPause                                [internal]
1918  */
1919 static DWORD wodPause(WORD wDevID)
1920 {
1921     TRACE("(%u);!\n", wDevID);
1922
1923     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1924         WARN("bad device ID !\n");
1925         return MMSYSERR_BADDEVICEID;
1926     }
1927
1928     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1929
1930     return MMSYSERR_NOERROR;
1931 }
1932
1933 /**************************************************************************
1934  *                      wodRestart                              [internal]
1935  */
1936 static DWORD wodRestart(WORD wDevID)
1937 {
1938     TRACE("(%u);\n", wDevID);
1939
1940     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1941         WARN("bad device ID !\n");
1942         return MMSYSERR_BADDEVICEID;
1943     }
1944
1945     if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1946         ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1947     }
1948
1949     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1950     /* FIXME: Myst crashes with this ... hmm -MM
1951        return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1952     */
1953
1954     return MMSYSERR_NOERROR;
1955 }
1956
1957 /**************************************************************************
1958  *                      wodReset                                [internal]
1959  */
1960 static DWORD wodReset(WORD wDevID)
1961 {
1962     TRACE("(%u);\n", wDevID);
1963
1964     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1965         WARN("bad device ID !\n");
1966         return MMSYSERR_BADDEVICEID;
1967     }
1968
1969     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1970
1971     return MMSYSERR_NOERROR;
1972 }
1973
1974 /**************************************************************************
1975  *                              wodGetPosition                  [internal]
1976  */
1977 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1978 {
1979     WINE_WAVEOUT*       wwo;
1980
1981     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1982
1983     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1984         WARN("bad device ID !\n");
1985         return MMSYSERR_BADDEVICEID;
1986     }
1987
1988     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1989
1990     wwo = &WOutDev[wDevID];
1991     ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1992
1993     return bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->format);
1994 }
1995
1996 /**************************************************************************
1997  *                              wodBreakLoop                    [internal]
1998  */
1999 static DWORD wodBreakLoop(WORD wDevID)
2000 {
2001     TRACE("(%u);\n", wDevID);
2002
2003     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
2004         WARN("bad device ID !\n");
2005         return MMSYSERR_BADDEVICEID;
2006     }
2007     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
2008     return MMSYSERR_NOERROR;
2009 }
2010
2011 /**************************************************************************
2012  *                              wodGetVolume                    [internal]
2013  */
2014 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
2015 {
2016     WORD               left, right;
2017     WINE_WAVEOUT*      wwo;
2018     int                count;
2019     long               min, max;
2020
2021     TRACE("(%u, %p);\n", wDevID, lpdwVol);
2022     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
2023         WARN("bad device ID !\n");
2024         return MMSYSERR_BADDEVICEID;
2025     }
2026     wwo = &WOutDev[wDevID];
2027     count = snd_ctl_elem_info_get_count(wwo->playback_einfo);
2028     min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
2029     max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
2030
2031 #define VOLUME_ALSA_TO_WIN(x) (((x)-min) * 65536 /(max-min))
2032     if (lpdwVol == NULL)
2033         return MMSYSERR_NOTENABLED;
2034
2035     switch (count)
2036     {
2037         case 2:
2038             left = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
2039             right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 1));
2040             break;
2041         case 1:
2042             left = right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
2043             break;
2044         default:
2045             WARN("%d channels mixer not supported\n", count);
2046             return MMSYSERR_NOERROR;
2047      }
2048 #undef VOLUME_ALSA_TO_WIN
2049
2050     TRACE("left=%d right=%d !\n", left, right);
2051     *lpdwVol = MAKELONG( left, right );
2052     return MMSYSERR_NOERROR;
2053 }
2054
2055 /**************************************************************************
2056  *                              wodSetVolume                    [internal]
2057  */
2058 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
2059 {
2060     WORD               left, right;
2061     WINE_WAVEOUT*      wwo;
2062     int                count, err;
2063     long               min, max;
2064
2065     TRACE("(%u, %08lX);\n", wDevID, dwParam);
2066     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
2067         WARN("bad device ID !\n");
2068         return MMSYSERR_BADDEVICEID;
2069     }
2070     wwo = &WOutDev[wDevID];
2071     count=snd_ctl_elem_info_get_count(wwo->playback_einfo);
2072     min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
2073     max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
2074
2075     left  = LOWORD(dwParam);
2076     right = HIWORD(dwParam);
2077
2078 #define VOLUME_WIN_TO_ALSA(x) ( (((x) * (max-min)) / 65536) + min )
2079     switch (count)
2080     {
2081         case 2:
2082             snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
2083             snd_ctl_elem_value_set_integer(wwo->playback_evalue, 1, VOLUME_WIN_TO_ALSA(right));
2084             break;
2085         case 1:
2086             snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
2087             break;
2088         default:
2089             WARN("%d channels mixer not supported\n", count);
2090      }
2091 #undef VOLUME_WIN_TO_ALSA
2092     if ( (err = snd_ctl_elem_write(wwo->ctl, wwo->playback_evalue)) < 0)
2093     {
2094         ERR("error writing snd_ctl_elem_value: %s\n", snd_strerror(err));
2095     }
2096     return MMSYSERR_NOERROR;
2097 }
2098
2099 /**************************************************************************
2100  *                              wodGetNumDevs                   [internal]
2101  */
2102 static  DWORD   wodGetNumDevs(void)
2103 {
2104     return ALSA_WodNumDevs;
2105 }
2106
2107 /**************************************************************************
2108  *                              wodDevInterfaceSize             [internal]
2109  */
2110 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2111 {
2112     TRACE("(%u, %p)\n", wDevID, dwParam1);
2113
2114     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2115                                     NULL, 0 ) * sizeof(WCHAR);
2116     return MMSYSERR_NOERROR;
2117 }
2118
2119 /**************************************************************************
2120  *                              wodDevInterface                 [internal]
2121  */
2122 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2123 {
2124     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2125                                         NULL, 0 ) * sizeof(WCHAR))
2126     {
2127         MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2128                             dwParam1, dwParam2 / sizeof(WCHAR));
2129         return MMSYSERR_NOERROR;
2130     }
2131     return MMSYSERR_INVALPARAM;
2132 }
2133
2134 /**************************************************************************
2135  *                              wodMessage (WINEALSA.@)
2136  */
2137 DWORD WINAPI ALSA_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
2138                              DWORD dwParam1, DWORD dwParam2)
2139 {
2140     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
2141           wDevID, wMsg, dwUser, dwParam1, dwParam2);
2142
2143     switch (wMsg) {
2144     case DRVM_INIT:
2145     case DRVM_EXIT:
2146     case DRVM_ENABLE:
2147     case DRVM_DISABLE:
2148         /* FIXME: Pretend this is supported */
2149         return 0;
2150     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
2151     case WODM_CLOSE:            return wodClose         (wDevID);
2152     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSW)dwParam1,      dwParam2);
2153     case WODM_GETNUMDEVS:       return wodGetNumDevs    ();
2154     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
2155     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
2156     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
2157     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
2158     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
2159     case WODM_PAUSE:            return wodPause         (wDevID);
2160     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
2161     case WODM_BREAKLOOP:        return wodBreakLoop     (wDevID);
2162     case WODM_PREPARE:          return wodPrepare       (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
2163     case WODM_UNPREPARE:        return wodUnprepare     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
2164     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
2165     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
2166     case WODM_RESTART:          return wodRestart       (wDevID);
2167     case WODM_RESET:            return wodReset         (wDevID);
2168     case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
2169     case DRV_QUERYDEVICEINTERFACE:     return wodDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
2170     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate      (wDevID, (PIDSDRIVER*)dwParam1);
2171     case DRV_QUERYDSOUNDDESC:   return wodDsDesc        (wDevID, (PDSDRIVERDESC)dwParam1);
2172
2173     default:
2174         FIXME("unknown message %d!\n", wMsg);
2175     }
2176     return MMSYSERR_NOTSUPPORTED;
2177 }
2178
2179 /*======================================================================*
2180  *                  Low level DSOUND implementation                     *
2181  *======================================================================*/
2182
2183 typedef struct IDsDriverImpl IDsDriverImpl;
2184 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
2185
2186 struct IDsDriverImpl
2187 {
2188     /* IUnknown fields */
2189     IDsDriverVtbl      *lpVtbl;
2190     DWORD               ref;
2191     /* IDsDriverImpl fields */
2192     UINT                wDevID;
2193     IDsDriverBufferImpl*primary;
2194 };
2195
2196 struct IDsDriverBufferImpl
2197 {
2198     /* IUnknown fields */
2199     IDsDriverBufferVtbl      *lpVtbl;
2200     DWORD                     ref;
2201     /* IDsDriverBufferImpl fields */
2202     IDsDriverImpl*            drv;
2203
2204     CRITICAL_SECTION          mmap_crst;
2205     LPVOID                    mmap_buffer;
2206     DWORD                     mmap_buflen_bytes;
2207     snd_pcm_uframes_t         mmap_buflen_frames;
2208     snd_pcm_channel_area_t *  mmap_areas;
2209     snd_async_handler_t *     mmap_async_handler;
2210 };
2211
2212 static void DSDB_CheckXRUN(IDsDriverBufferImpl* pdbi)
2213 {
2214     WINE_WAVEOUT *     wwo = &(WOutDev[pdbi->drv->wDevID]);
2215     snd_pcm_state_t    state = snd_pcm_state(wwo->p_handle);
2216
2217     if ( state == SND_PCM_STATE_XRUN )
2218     {
2219         int            err = snd_pcm_prepare(wwo->p_handle);
2220         TRACE("xrun occurred\n");
2221         if ( err < 0 )
2222             ERR("recovery from xrun failed, prepare failed: %s\n", snd_strerror(err));
2223     }
2224     else if ( state == SND_PCM_STATE_SUSPENDED )
2225     {
2226         int            err = snd_pcm_resume(wwo->p_handle);
2227         TRACE("recovery from suspension occurred\n");
2228         if (err < 0 && err != -EAGAIN){
2229             err = snd_pcm_prepare(wwo->p_handle);
2230             if (err < 0)
2231                 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
2232         }
2233     }
2234 }
2235
2236 static void DSDB_MMAPCopy(IDsDriverBufferImpl* pdbi)
2237 {
2238     WINE_WAVEOUT *     wwo = &(WOutDev[pdbi->drv->wDevID]);
2239     unsigned int       channels;
2240     snd_pcm_format_t   format;
2241     snd_pcm_uframes_t  period_size;
2242     snd_pcm_sframes_t  avail;
2243     int err;
2244     int dir=0;
2245
2246     if ( !pdbi->mmap_buffer || !wwo->hw_params || !wwo->p_handle)
2247         return;
2248
2249     err = snd_pcm_hw_params_get_channels(wwo->hw_params, &channels);
2250     err = snd_pcm_hw_params_get_format(wwo->hw_params, &format);
2251     dir=0;
2252     err = snd_pcm_hw_params_get_period_size(wwo->hw_params, &period_size, &dir);
2253     avail = snd_pcm_avail_update(wwo->p_handle);
2254
2255     DSDB_CheckXRUN(pdbi);
2256
2257     TRACE("avail=%d format=%s channels=%d\n", (int)avail, snd_pcm_format_name(format), channels );
2258
2259     while (avail >= period_size)
2260     {
2261         const snd_pcm_channel_area_t *areas;
2262         snd_pcm_uframes_t     ofs;
2263         snd_pcm_uframes_t     frames;
2264         int                   err;
2265
2266         frames = avail / period_size * period_size; /* round down to a multiple of period_size */
2267
2268         EnterCriticalSection(&pdbi->mmap_crst);
2269
2270         snd_pcm_mmap_begin(wwo->p_handle, &areas, &ofs, &frames);
2271         snd_pcm_areas_copy(areas, ofs, pdbi->mmap_areas, ofs, channels, frames, format);
2272         err = snd_pcm_mmap_commit(wwo->p_handle, ofs, frames);
2273
2274         LeaveCriticalSection(&pdbi->mmap_crst);
2275
2276         if ( err != (snd_pcm_sframes_t) frames)
2277             ERR("mmap partially failed.\n");
2278
2279         avail = snd_pcm_avail_update(wwo->p_handle);
2280     }
2281  }
2282
2283 static void DSDB_PCMCallback(snd_async_handler_t *ahandler)
2284 {
2285     /* snd_pcm_t *               handle = snd_async_handler_get_pcm(ahandler); */
2286     IDsDriverBufferImpl*      pdbi = snd_async_handler_get_callback_private(ahandler);
2287     TRACE("callback called\n");
2288     DSDB_MMAPCopy(pdbi);
2289 }
2290
2291 static int DSDB_CreateMMAP(IDsDriverBufferImpl* pdbi)
2292  {
2293     WINE_WAVEOUT *            wwo = &(WOutDev[pdbi->drv->wDevID]);
2294     snd_pcm_format_t          format;
2295     snd_pcm_uframes_t         frames;
2296     unsigned int              channels;
2297     unsigned int              bits_per_sample;
2298     unsigned int              bits_per_frame;
2299     snd_pcm_channel_area_t *  a;
2300     unsigned int              c;
2301     int                       err;
2302
2303     err = snd_pcm_hw_params_get_format(wwo->hw_params, &format);
2304     err = snd_pcm_hw_params_get_buffer_size(wwo->hw_params, &frames);
2305     err = snd_pcm_hw_params_get_channels(wwo->hw_params, &channels);
2306     bits_per_sample = snd_pcm_format_physical_width(format);
2307     bits_per_frame = bits_per_sample * channels;
2308
2309
2310     if (TRACE_ON(wave))
2311         ALSA_TraceParameters(wwo->hw_params, NULL, FALSE);
2312
2313     TRACE("format=%s  frames=%ld  channels=%d  bits_per_sample=%d  bits_per_frame=%d\n",
2314           snd_pcm_format_name(format), frames, channels, bits_per_sample, bits_per_frame);
2315
2316     pdbi->mmap_buflen_frames = frames;
2317     pdbi->mmap_buflen_bytes = snd_pcm_frames_to_bytes( wwo->p_handle, frames );
2318     pdbi->mmap_buffer = HeapAlloc(GetProcessHeap(),0,pdbi->mmap_buflen_bytes);
2319     if (!pdbi->mmap_buffer)
2320         return DSERR_OUTOFMEMORY;
2321
2322     snd_pcm_format_set_silence(format, pdbi->mmap_buffer, frames );
2323
2324     TRACE("created mmap buffer of %ld frames (%ld bytes) at %p\n",
2325         frames, pdbi->mmap_buflen_bytes, pdbi->mmap_buffer);
2326
2327     pdbi->mmap_areas = HeapAlloc(GetProcessHeap(),0,channels*sizeof(snd_pcm_channel_area_t));
2328     if (!pdbi->mmap_areas)
2329         return DSERR_OUTOFMEMORY;
2330
2331     a = pdbi->mmap_areas;
2332     for (c = 0; c < channels; c++, a++)
2333     {
2334         a->addr = pdbi->mmap_buffer;
2335         a->first = bits_per_sample * c;
2336         a->step = bits_per_frame;
2337         TRACE("Area %d: addr=%p  first=%d  step=%d\n", c, a->addr, a->first, a->step);
2338     }
2339
2340     InitializeCriticalSection(&pdbi->mmap_crst);
2341
2342     err = snd_async_add_pcm_handler(&pdbi->mmap_async_handler, wwo->p_handle, DSDB_PCMCallback, pdbi);
2343     if ( err < 0 )
2344      {
2345         ERR("add_pcm_handler failed. reason: %s\n", snd_strerror(err));
2346         return DSERR_GENERIC;
2347      }
2348
2349     return DS_OK;
2350  }
2351
2352 static void DSDB_DestroyMMAP(IDsDriverBufferImpl* pdbi)
2353 {
2354     TRACE("mmap buffer %p destroyed\n", pdbi->mmap_buffer);
2355     HeapFree(GetProcessHeap(), 0, pdbi->mmap_areas);
2356     HeapFree(GetProcessHeap(), 0, pdbi->mmap_buffer);
2357     pdbi->mmap_areas = NULL;
2358     pdbi->mmap_buffer = NULL;
2359     DeleteCriticalSection(&pdbi->mmap_crst);
2360 }
2361
2362
2363 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
2364 {
2365     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2366     FIXME("(): stub!\n");
2367     return DSERR_UNSUPPORTED;
2368 }
2369
2370 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
2371 {
2372     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2373     ULONG refCount = InterlockedIncrement(&This->ref);
2374
2375     TRACE("(%p)->(ref before=%lu)\n",This, refCount - 1);
2376
2377     return refCount;
2378 }
2379
2380 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
2381 {
2382     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2383     ULONG refCount = InterlockedDecrement(&This->ref);
2384
2385     TRACE("(%p)->(ref before=%lu)\n",This, refCount + 1);
2386
2387     if (refCount)
2388         return refCount;
2389     if (This == This->drv->primary)
2390         This->drv->primary = NULL;
2391     DSDB_DestroyMMAP(This);
2392     HeapFree(GetProcessHeap(), 0, This);
2393     return 0;
2394 }
2395
2396 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
2397                                                LPVOID*ppvAudio1,LPDWORD pdwLen1,
2398                                                LPVOID*ppvAudio2,LPDWORD pdwLen2,
2399                                                DWORD dwWritePosition,DWORD dwWriteLen,
2400                                                DWORD dwFlags)
2401 {
2402     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2403     TRACE("(%p)\n",iface);
2404     return DSERR_UNSUPPORTED;
2405 }
2406
2407 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
2408                                                  LPVOID pvAudio1,DWORD dwLen1,
2409                                                  LPVOID pvAudio2,DWORD dwLen2)
2410 {
2411     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2412     TRACE("(%p)\n",iface);
2413     return DSERR_UNSUPPORTED;
2414 }
2415
2416 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
2417                                                     LPWAVEFORMATEX pwfx)
2418 {
2419     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2420     TRACE("(%p,%p)\n",iface,pwfx);
2421     return DSERR_BUFFERLOST;
2422 }
2423
2424 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
2425 {
2426     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2427     TRACE("(%p,%ld): stub\n",iface,dwFreq);
2428     return DSERR_UNSUPPORTED;
2429 }
2430
2431 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
2432 {
2433     DWORD vol;
2434     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2435     TRACE("(%p,%p)\n",iface,pVolPan);
2436     vol = pVolPan->dwTotalLeftAmpFactor | (pVolPan->dwTotalRightAmpFactor << 16);
2437                                                                                 
2438     if (wodSetVolume(This->drv->wDevID, vol) != MMSYSERR_NOERROR) {
2439         WARN("wodSetVolume failed\n");
2440         return DSERR_INVALIDPARAM;
2441     }
2442
2443     return DS_OK;
2444 }
2445
2446 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
2447 {
2448     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2449     TRACE("(%p,%ld): stub\n",iface,dwNewPos);
2450     return DSERR_UNSUPPORTED;
2451 }
2452
2453 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
2454                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
2455 {
2456     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2457     WINE_WAVEOUT *      wwo = &(WOutDev[This->drv->wDevID]);
2458     snd_pcm_uframes_t   hw_ptr;
2459     snd_pcm_uframes_t   period_size;
2460     int dir;
2461     int err;
2462
2463     if (wwo->hw_params == NULL) return DSERR_GENERIC;
2464
2465     dir=0;
2466     err = snd_pcm_hw_params_get_period_size(wwo->hw_params, &period_size, &dir);
2467
2468     if (wwo->p_handle == NULL) return DSERR_GENERIC;
2469     /** we need to track down buffer underruns */
2470     DSDB_CheckXRUN(This);
2471
2472     EnterCriticalSection(&This->mmap_crst);
2473     /* FIXME: snd_pcm_mmap_hw_ptr() should not be accessed by a user app. */
2474     /*        It will NOT return what why want anyway. */
2475     hw_ptr = _snd_pcm_mmap_hw_ptr(wwo->p_handle);
2476     if (lpdwPlay)
2477         *lpdwPlay = snd_pcm_frames_to_bytes(wwo->p_handle, hw_ptr/ period_size  * period_size) % This->mmap_buflen_bytes;
2478     if (lpdwWrite)
2479         *lpdwWrite = snd_pcm_frames_to_bytes(wwo->p_handle, (hw_ptr / period_size + 1) * period_size ) % This->mmap_buflen_bytes;
2480     LeaveCriticalSection(&This->mmap_crst);
2481
2482     TRACE("hw_ptr=0x%08x, playpos=%ld, writepos=%ld\n", (unsigned int)hw_ptr, lpdwPlay?*lpdwPlay:-1, lpdwWrite?*lpdwWrite:-1);
2483     return DS_OK;
2484 }
2485
2486 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
2487 {
2488     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2489     WINE_WAVEOUT *       wwo = &(WOutDev[This->drv->wDevID]);
2490     snd_pcm_state_t      state;
2491     int                  err;
2492
2493     TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
2494
2495     if (wwo->p_handle == NULL) return DSERR_GENERIC;
2496
2497     state = snd_pcm_state(wwo->p_handle);
2498     if ( state == SND_PCM_STATE_SETUP )
2499     {
2500         err = snd_pcm_prepare(wwo->p_handle);
2501         state = snd_pcm_state(wwo->p_handle);
2502     }
2503     if ( state == SND_PCM_STATE_PREPARED )
2504      {
2505         DSDB_MMAPCopy(This);
2506         err = snd_pcm_start(wwo->p_handle);
2507      }
2508     return DS_OK;
2509 }
2510
2511 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
2512 {
2513     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2514     WINE_WAVEOUT *    wwo = &(WOutDev[This->drv->wDevID]);
2515     int               err;
2516     DWORD             play;
2517     DWORD             write;
2518
2519     TRACE("(%p)\n",iface);
2520
2521     if (wwo->p_handle == NULL) return DSERR_GENERIC;
2522
2523     /* ring buffer wrap up detection */
2524     IDsDriverBufferImpl_GetPosition(iface, &play, &write);
2525     if ( play > write)
2526     {
2527         TRACE("writepos wrapper up\n");
2528         return DS_OK;
2529     }
2530
2531     if ( ( err = snd_pcm_drop(wwo->p_handle)) < 0 )
2532     {
2533         ERR("error while stopping pcm: %s\n", snd_strerror(err));
2534         return DSERR_GENERIC;
2535     }
2536     return DS_OK;
2537 }
2538
2539 static IDsDriverBufferVtbl dsdbvt =
2540 {
2541     IDsDriverBufferImpl_QueryInterface,
2542     IDsDriverBufferImpl_AddRef,
2543     IDsDriverBufferImpl_Release,
2544     IDsDriverBufferImpl_Lock,
2545     IDsDriverBufferImpl_Unlock,
2546     IDsDriverBufferImpl_SetFormat,
2547     IDsDriverBufferImpl_SetFrequency,
2548     IDsDriverBufferImpl_SetVolumePan,
2549     IDsDriverBufferImpl_SetPosition,
2550     IDsDriverBufferImpl_GetPosition,
2551     IDsDriverBufferImpl_Play,
2552     IDsDriverBufferImpl_Stop
2553 };
2554
2555 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
2556 {
2557     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2558     FIXME("(%p): stub!\n",iface);
2559     return DSERR_UNSUPPORTED;
2560 }
2561
2562 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
2563 {
2564     IDsDriverImpl *This = (IDsDriverImpl *)iface;
2565     ULONG refCount = InterlockedIncrement(&This->ref);
2566
2567     TRACE("(%p)->(ref before=%lu)\n",This, refCount - 1);
2568
2569     return refCount;
2570 }
2571
2572 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
2573 {
2574     IDsDriverImpl *This = (IDsDriverImpl *)iface;
2575     ULONG refCount = InterlockedDecrement(&This->ref);
2576
2577     TRACE("(%p)->(ref before=%lu)\n",This, refCount + 1);
2578
2579     if (refCount)
2580         return refCount;
2581     HeapFree(GetProcessHeap(),0,This);
2582     return 0;
2583 }
2584
2585 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
2586 {
2587     IDsDriverImpl *This = (IDsDriverImpl *)iface;
2588     TRACE("(%p,%p)\n",iface,pDesc);
2589     memcpy(pDesc, &(WOutDev[This->wDevID].ds_desc), sizeof(DSDRIVERDESC));
2590     pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
2591         DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK;
2592     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
2593     pDesc->wVxdId               = 0;
2594     pDesc->wReserved            = 0;
2595     pDesc->ulDeviceNum          = This->wDevID;
2596     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
2597     pDesc->pvDirectDrawHeap     = NULL;
2598     pDesc->dwMemStartAddress    = 0;
2599     pDesc->dwMemEndAddress      = 0;
2600     pDesc->dwMemAllocExtra      = 0;
2601     pDesc->pvReserved1          = NULL;
2602     pDesc->pvReserved2          = NULL;
2603     return DS_OK;
2604 }
2605
2606 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
2607 {
2608     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2609     TRACE("(%p)\n",iface);
2610     return DS_OK;
2611 }
2612
2613 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
2614 {
2615     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2616     TRACE("(%p)\n",iface);
2617     return DS_OK;
2618 }
2619
2620 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
2621 {
2622     IDsDriverImpl *This = (IDsDriverImpl *)iface;
2623     TRACE("(%p,%p)\n",iface,pCaps);
2624     memset(pCaps, 0, sizeof(*pCaps));
2625
2626     pCaps->dwFlags = DSCAPS_PRIMARYMONO;
2627     if ( WOutDev[This->wDevID].caps.wChannels == 2 )
2628         pCaps->dwFlags |= DSCAPS_PRIMARYSTEREO;
2629
2630     if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 ) )
2631         pCaps->dwFlags |= DSCAPS_PRIMARY8BIT;
2632
2633     if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S16 | WAVE_FORMAT_2S16 | WAVE_FORMAT_4S16))
2634         pCaps->dwFlags |= DSCAPS_PRIMARY16BIT;
2635
2636     pCaps->dwPrimaryBuffers = 1;
2637     TRACE("caps=0x%X\n",(unsigned int)pCaps->dwFlags);
2638     pCaps->dwMinSecondarySampleRate = DSBFREQUENCY_MIN;
2639     pCaps->dwMaxSecondarySampleRate = DSBFREQUENCY_MAX;
2640
2641     /* the other fields only apply to secondary buffers, which we don't support
2642      * (unless we want to mess with wavetable synthesizers and MIDI) */
2643     return DS_OK;
2644 }
2645
2646 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
2647                                                       LPWAVEFORMATEX pwfx,
2648                                                       DWORD dwFlags, DWORD dwCardAddress,
2649                                                       LPDWORD pdwcbBufferSize,
2650                                                       LPBYTE *ppbBuffer,
2651                                                       LPVOID *ppvObj)
2652 {
2653     IDsDriverImpl *This = (IDsDriverImpl *)iface;
2654     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
2655     int err;
2656
2657     TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
2658     /* we only support primary buffers */
2659     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
2660         return DSERR_UNSUPPORTED;
2661     if (This->primary)
2662         return DSERR_ALLOCATED;
2663     if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
2664         return DSERR_CONTROLUNAVAIL;
2665
2666     *ippdsdb = (IDsDriverBufferImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
2667     if (*ippdsdb == NULL)
2668         return DSERR_OUTOFMEMORY;
2669     (*ippdsdb)->lpVtbl  = &dsdbvt;
2670     (*ippdsdb)->ref     = 1;
2671     (*ippdsdb)->drv     = This;
2672
2673     err = DSDB_CreateMMAP((*ippdsdb));
2674     if ( err != DS_OK )
2675      {
2676         HeapFree(GetProcessHeap(), 0, *ippdsdb);
2677         *ippdsdb = NULL;
2678         return err;
2679      }
2680     *ppbBuffer = (*ippdsdb)->mmap_buffer;
2681     *pdwcbBufferSize = (*ippdsdb)->mmap_buflen_bytes;
2682
2683     This->primary = *ippdsdb;
2684
2685     /* buffer is ready to go */
2686     TRACE("buffer created at %p\n", *ippdsdb);
2687     return DS_OK;
2688 }
2689
2690 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
2691                                                          PIDSDRIVERBUFFER pBuffer,
2692                                                          LPVOID *ppvObj)
2693 {
2694     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2695     TRACE("(%p,%p): stub\n",iface,pBuffer);
2696     return DSERR_INVALIDCALL;
2697 }
2698
2699 static IDsDriverVtbl dsdvt =
2700 {
2701     IDsDriverImpl_QueryInterface,
2702     IDsDriverImpl_AddRef,
2703     IDsDriverImpl_Release,
2704     IDsDriverImpl_GetDriverDesc,
2705     IDsDriverImpl_Open,
2706     IDsDriverImpl_Close,
2707     IDsDriverImpl_GetCaps,
2708     IDsDriverImpl_CreateSoundBuffer,
2709     IDsDriverImpl_DuplicateSoundBuffer
2710 };
2711
2712 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
2713 {
2714     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
2715
2716     TRACE("driver created\n");
2717
2718     /* the HAL isn't much better than the HEL if we can't do mmap() */
2719     if (!(WOutDev[wDevID].caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
2720         ERR("DirectSound flag not set\n");
2721         MESSAGE("This sound card's driver does not support direct access\n");
2722         MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
2723         return MMSYSERR_NOTSUPPORTED;
2724     }
2725
2726     *idrv = (IDsDriverImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
2727     if (!*idrv)
2728         return MMSYSERR_NOMEM;
2729     (*idrv)->lpVtbl     = &dsdvt;
2730     (*idrv)->ref        = 1;
2731
2732     (*idrv)->wDevID     = wDevID;
2733     (*idrv)->primary    = NULL;
2734     return MMSYSERR_NOERROR;
2735 }
2736
2737 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2738 {
2739     memcpy(desc, &(WOutDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
2740     return MMSYSERR_NOERROR;
2741 }
2742
2743 /*======================================================================*
2744 *                  Low level WAVE IN implementation                     *
2745 *======================================================================*/
2746
2747 /**************************************************************************
2748 *                       widNotifyClient                 [internal]
2749 */
2750 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
2751 {
2752    TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
2753
2754    switch (wMsg) {
2755    case WIM_OPEN:
2756    case WIM_CLOSE:
2757    case WIM_DATA:
2758        if (wwi->wFlags != DCB_NULL &&
2759            !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags, (HDRVR)wwi->waveDesc.hWave,
2760                            wMsg, wwi->waveDesc.dwInstance, dwParam1, dwParam2)) {
2761            WARN("can't notify client !\n");
2762            return MMSYSERR_ERROR;
2763        }
2764        break;
2765    default:
2766        FIXME("Unknown callback message %u\n", wMsg);
2767        return MMSYSERR_INVALPARAM;
2768    }
2769    return MMSYSERR_NOERROR;
2770 }
2771
2772 /**************************************************************************
2773  *                      widGetDevCaps                           [internal]
2774  */
2775 static DWORD widGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
2776 {
2777     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
2778
2779     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
2780
2781     if (wDevID >= MAX_WAVEINDRV) {
2782         TRACE("MAX_WAVOUTDRV reached !\n");
2783         return MMSYSERR_BADDEVICEID;
2784     }
2785
2786     memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
2787     return MMSYSERR_NOERROR;
2788 }
2789
2790 /**************************************************************************
2791  *                              widRecorder_ReadHeaders         [internal]
2792  */
2793 static void widRecorder_ReadHeaders(WINE_WAVEIN * wwi)
2794 {
2795     enum win_wm_message tmp_msg;
2796     DWORD               tmp_param;
2797     HANDLE              tmp_ev;
2798     WAVEHDR*            lpWaveHdr;
2799
2800     while (ALSA_RetrieveRingMessage(&wwi->msgRing, &tmp_msg, &tmp_param, &tmp_ev)) {
2801         if (tmp_msg == WINE_WM_HEADER) {
2802             LPWAVEHDR*  wh;
2803             lpWaveHdr = (LPWAVEHDR)tmp_param;
2804             lpWaveHdr->lpNext = 0;
2805
2806             if (wwi->lpQueuePtr == 0)
2807                 wwi->lpQueuePtr = lpWaveHdr;
2808             else {
2809                 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2810                 *wh = lpWaveHdr;
2811             }
2812         } else {
2813             ERR("should only have headers left\n");
2814         }
2815     }
2816 }
2817
2818 /**************************************************************************
2819  *                              widRecorder                     [internal]
2820  */
2821 static  DWORD   CALLBACK        widRecorder(LPVOID pmt)
2822 {
2823     WORD                uDevID = (DWORD)pmt;
2824     WINE_WAVEIN*        wwi = (WINE_WAVEIN*)&WInDev[uDevID];
2825     WAVEHDR*            lpWaveHdr;
2826     DWORD               dwSleepTime;
2827     DWORD               bytesRead;
2828     LPVOID              buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, wwi->dwPeriodSize);
2829     char               *pOffset = buffer;
2830     enum win_wm_message msg;
2831     DWORD               param;
2832     HANDLE              ev;
2833     DWORD               frames_per_period;
2834
2835     wwi->state = WINE_WS_STOPPED;
2836     wwi->dwTotalRecorded = 0;
2837     wwi->lpQueuePtr = NULL;
2838
2839     SetEvent(wwi->hStartUpEvent);
2840
2841     /* make sleep time to be # of ms to output a period */
2842     dwSleepTime = (1024/*wwi-dwPeriodSize => overrun!*/ * 1000) / wwi->format.Format.nAvgBytesPerSec;
2843     frames_per_period = snd_pcm_bytes_to_frames(wwi->p_handle, wwi->dwPeriodSize); 
2844     TRACE("sleeptime=%ld ms\n", dwSleepTime);
2845
2846     for (;;) {
2847         /* wait for dwSleepTime or an event in thread's queue */
2848         /* FIXME: could improve wait time depending on queue state,
2849          * ie, number of queued fragments
2850          */
2851         if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
2852         {
2853             int periods;
2854             DWORD frames;
2855             DWORD bytes;
2856             DWORD read;
2857
2858             lpWaveHdr = wwi->lpQueuePtr;
2859             /* read all the fragments accumulated so far */
2860             frames = snd_pcm_avail_update(wwi->p_handle);
2861             bytes = snd_pcm_frames_to_bytes(wwi->p_handle, frames);
2862             TRACE("frames = %ld  bytes = %ld\n", frames, bytes);
2863             periods = bytes / wwi->dwPeriodSize;
2864             while ((periods > 0) && (wwi->lpQueuePtr))
2865             {
2866                 periods--;
2867                 bytes = wwi->dwPeriodSize;
2868                 TRACE("bytes = %ld\n",bytes);
2869                 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwPeriodSize)
2870                 {
2871                     /* directly read fragment in wavehdr */
2872                     read = wwi->read(wwi->p_handle, lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded, frames_per_period);
2873                     bytesRead = snd_pcm_frames_to_bytes(wwi->p_handle, read);
2874                         
2875                     TRACE("bytesRead=%ld (direct)\n", bytesRead);
2876                     if (bytesRead != (DWORD) -1)
2877                     {
2878                         /* update number of bytes recorded in current buffer and by this device */
2879                         lpWaveHdr->dwBytesRecorded += bytesRead;
2880                         wwi->dwTotalRecorded       += bytesRead;
2881
2882                         /* buffer is full. notify client */
2883                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2884                         {
2885                             /* must copy the value of next waveHdr, because we have no idea of what
2886                              * will be done with the content of lpWaveHdr in callback
2887                              */
2888                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
2889
2890                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2891                             lpWaveHdr->dwFlags |=  WHDR_DONE;
2892
2893                             wwi->lpQueuePtr = lpNext;
2894                             widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2895                             lpWaveHdr = lpNext;
2896                         }
2897                     } else {
2898                         TRACE("read(%s, %p, %ld) failed (%s)\n", wwi->device,
2899                             lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2900                             frames_per_period, strerror(errno));
2901                     }
2902                 }
2903                 else
2904                 {
2905                     /* read the fragment in a local buffer */
2906                     read = wwi->read(wwi->p_handle, buffer, frames_per_period);
2907                     bytesRead = snd_pcm_frames_to_bytes(wwi->p_handle, read);
2908                     pOffset = buffer;
2909
2910                     TRACE("bytesRead=%ld (local)\n", bytesRead);
2911
2912                     if (bytesRead == (DWORD) -1) {
2913                         TRACE("read(%s, %p, %ld) failed (%s)\n", wwi->device,
2914                               buffer, frames_per_period, strerror(errno));
2915                         continue;
2916                     }   
2917
2918                     /* copy data in client buffers */
2919                     while (bytesRead != (DWORD) -1 && bytesRead > 0)
2920                     {
2921                         DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
2922
2923                         memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2924                                pOffset,
2925                                dwToCopy);
2926
2927                         /* update number of bytes recorded in current buffer and by this device */
2928                         lpWaveHdr->dwBytesRecorded += dwToCopy;
2929                         wwi->dwTotalRecorded += dwToCopy;
2930                         bytesRead -= dwToCopy;
2931                         pOffset   += dwToCopy;
2932
2933                         /* client buffer is full. notify client */
2934                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2935                         {
2936                             /* must copy the value of next waveHdr, because we have no idea of what
2937                              * will be done with the content of lpWaveHdr in callback
2938                              */
2939                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
2940                             TRACE("lpNext=%p\n", lpNext);
2941
2942                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2943                             lpWaveHdr->dwFlags |=  WHDR_DONE;
2944
2945                             wwi->lpQueuePtr = lpNext;
2946                             widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2947
2948                             lpWaveHdr = lpNext;
2949                             if (!lpNext && bytesRead) {
2950                                 /* before we give up, check for more header messages */
2951                                 while (ALSA_PeekRingMessage(&wwi->msgRing, &msg, &param, &ev))
2952                                 {
2953                                     if (msg == WINE_WM_HEADER) {
2954                                         LPWAVEHDR hdr;
2955                                         ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev);
2956                                         hdr = ((LPWAVEHDR)param);
2957                                         TRACE("msg = %s, hdr = %p, ev = %p\n", getCmdString(msg), hdr, ev);
2958                                         hdr->lpNext = 0;
2959                                         if (lpWaveHdr == 0) {
2960                                             /* new head of queue */
2961                                             wwi->lpQueuePtr = lpWaveHdr = hdr;
2962                                         } else {
2963                                             /* insert buffer at the end of queue */
2964                                             LPWAVEHDR*  wh;
2965                                             for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2966                                             *wh = hdr;
2967                                         }
2968                                     } else
2969                                         break;
2970                                 }
2971
2972                                 if (lpWaveHdr == 0) {
2973                                     /* no more buffer to copy data to, but we did read more.
2974                                      * what hasn't been copied will be dropped
2975                                      */
2976                                     WARN("buffer under run! %lu bytes dropped.\n", bytesRead);
2977                                     wwi->lpQueuePtr = NULL;
2978                                     break;
2979                                 }
2980                             }
2981                         }
2982                     }
2983                 }
2984             }
2985         }
2986
2987         WAIT_OMR(&wwi->msgRing, dwSleepTime);
2988
2989         while (ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev))
2990         {
2991             TRACE("msg=%s param=0x%lx\n", getCmdString(msg), param);
2992             switch (msg) {
2993             case WINE_WM_PAUSING:
2994                 wwi->state = WINE_WS_PAUSED;
2995                 /*FIXME("Device should stop recording\n");*/
2996                 SetEvent(ev);
2997                 break;
2998             case WINE_WM_STARTING:
2999                 wwi->state = WINE_WS_PLAYING;
3000                 snd_pcm_start(wwi->p_handle);
3001                 SetEvent(ev);
3002                 break;
3003             case WINE_WM_HEADER:
3004                 lpWaveHdr = (LPWAVEHDR)param;
3005                 lpWaveHdr->lpNext = 0;
3006
3007                 /* insert buffer at the end of queue */
3008                 {
3009                     LPWAVEHDR*  wh;
3010                     for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
3011                     *wh = lpWaveHdr;
3012                 }
3013                 break;
3014             case WINE_WM_STOPPING:
3015                 if (wwi->state != WINE_WS_STOPPED)
3016                 {
3017                     snd_pcm_drain(wwi->p_handle);
3018
3019                     /* read any headers in queue */
3020                     widRecorder_ReadHeaders(wwi);
3021
3022                     /* return current buffer to app */
3023                     lpWaveHdr = wwi->lpQueuePtr;
3024                     if (lpWaveHdr)
3025                     {
3026                         LPWAVEHDR       lpNext = lpWaveHdr->lpNext;
3027                         TRACE("stop %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
3028                         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
3029                         lpWaveHdr->dwFlags |= WHDR_DONE;
3030                         wwi->lpQueuePtr = lpNext;
3031                         widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
3032                     }
3033                 }
3034                 wwi->state = WINE_WS_STOPPED;
3035                 SetEvent(ev);
3036                 break;
3037             case WINE_WM_RESETTING:
3038                 if (wwi->state != WINE_WS_STOPPED)
3039                 {
3040                     snd_pcm_drain(wwi->p_handle);
3041                 }
3042                 wwi->state = WINE_WS_STOPPED;
3043                 wwi->dwTotalRecorded = 0;
3044
3045                 /* read any headers in queue */
3046                 widRecorder_ReadHeaders(wwi);
3047
3048                 /* return all buffers to the app */
3049                 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
3050                     TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
3051                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
3052                     lpWaveHdr->dwFlags |= WHDR_DONE;
3053                     wwi->lpQueuePtr = lpWaveHdr->lpNext;
3054                     widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
3055                 }
3056
3057                 wwi->lpQueuePtr = NULL;
3058                 SetEvent(ev);
3059                 break;
3060             case WINE_WM_CLOSING:
3061                 wwi->hThread = 0;
3062                 wwi->state = WINE_WS_CLOSED;
3063                 SetEvent(ev);
3064                 HeapFree(GetProcessHeap(), 0, buffer);
3065                 ExitThread(0);
3066                 /* shouldn't go here */
3067             case WINE_WM_UPDATE:
3068                 SetEvent(ev);
3069                 break;
3070
3071             default:
3072                 FIXME("unknown message %d\n", msg);
3073                 break;
3074             }
3075         }
3076     }
3077     ExitThread(0);
3078     /* just for not generating compilation warnings... should never be executed */
3079     return 0;
3080 }
3081
3082 /**************************************************************************
3083  *                              widOpen                         [internal]
3084  */
3085 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
3086 {
3087     WINE_WAVEIN*                wwi;
3088     snd_pcm_hw_params_t *       hw_params;
3089     snd_pcm_sw_params_t *       sw_params;
3090     snd_pcm_access_t            access;
3091     snd_pcm_format_t            format;
3092     unsigned int                rate;
3093     unsigned int                buffer_time = 500000;
3094     unsigned int                period_time = 10000;
3095     snd_pcm_uframes_t           buffer_size;
3096     snd_pcm_uframes_t           period_size;
3097     int                         flags;
3098     snd_pcm_t *                 pcm;
3099     int                         err;
3100     int                         dir;
3101
3102     snd_pcm_hw_params_alloca(&hw_params);
3103     snd_pcm_sw_params_alloca(&sw_params);
3104
3105     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
3106     if (lpDesc == NULL) {
3107         WARN("Invalid Parameter !\n");
3108         return MMSYSERR_INVALPARAM;
3109     }
3110     if (wDevID >= MAX_WAVEOUTDRV) {
3111         TRACE("MAX_WAVOUTDRV reached !\n");
3112         return MMSYSERR_BADDEVICEID;
3113     }
3114
3115     /* only PCM format is supported so far... */
3116     if (!supportedFormat(lpDesc->lpFormat)) {
3117         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
3118              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
3119              lpDesc->lpFormat->nSamplesPerSec);
3120         return WAVERR_BADFORMAT;
3121     }
3122
3123     if (dwFlags & WAVE_FORMAT_QUERY) {
3124         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
3125              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
3126              lpDesc->lpFormat->nSamplesPerSec);
3127         return MMSYSERR_NOERROR;
3128     }
3129
3130     wwi = &WInDev[wDevID];
3131
3132     if ((dwFlags & WAVE_DIRECTSOUND) && !(wwi->caps.dwSupport & WAVECAPS_DIRECTSOUND))
3133         /* not supported, ignore it */
3134         dwFlags &= ~WAVE_DIRECTSOUND;
3135
3136     wwi->p_handle = 0;
3137     flags = SND_PCM_NONBLOCK;
3138 #if 0
3139     if ( dwFlags & WAVE_DIRECTSOUND )
3140         flags |= SND_PCM_ASYNC;
3141 #endif
3142
3143     if ( (err=snd_pcm_open(&pcm, wwi->device, SND_PCM_STREAM_CAPTURE, flags)) < 0 )
3144     {
3145         ERR("Error open: %s\n", snd_strerror(err));
3146         return MMSYSERR_NOTENABLED;
3147     }
3148
3149     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
3150
3151     memcpy(&wwi->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
3152     copy_format(lpDesc->lpFormat, &wwi->format);
3153
3154     if (wwi->format.Format.wBitsPerSample == 0) {
3155         WARN("Resetting zeroed wBitsPerSample\n");
3156         wwi->format.Format.wBitsPerSample = 8 *
3157             (wwi->format.Format.nAvgBytesPerSec /
3158              wwi->format.Format.nSamplesPerSec) /
3159             wwi->format.Format.nChannels;
3160     }
3161
3162     snd_pcm_hw_params_any(pcm, hw_params);
3163
3164 #define EXIT_ON_ERROR(f,e,txt) do \
3165 { \
3166     int err; \
3167     if ( (err = (f) ) < 0) \
3168     { \
3169         ERR(txt ": %s\n", snd_strerror(err)); \
3170         snd_pcm_close(pcm); \
3171         return e; \
3172     } \
3173 } while(0)
3174
3175     access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
3176     if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
3177         WARN("mmap not available. switching to standard write.\n");
3178         access = SND_PCM_ACCESS_RW_INTERLEAVED;
3179         EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
3180         wwi->read = snd_pcm_readi;
3181     }
3182     else
3183         wwi->read = snd_pcm_mmap_readi;
3184
3185     EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwi->format.Format.nChannels), MMSYSERR_INVALPARAM, "unable to set required channels");
3186
3187     if ((wwi->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
3188         ((wwi->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
3189         IsEqualGUID(&wwi->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
3190         format = (wwi->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
3191                  (wwi->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
3192                  (wwi->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
3193                  (wwi->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
3194     } else if ((wwi->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
3195         IsEqualGUID(&wwi->format.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)){
3196         format = (wwi->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_FLOAT_LE : -1;
3197     } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
3198         FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
3199         snd_pcm_close(pcm);
3200         return WAVERR_BADFORMAT;
3201     } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
3202         FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
3203         snd_pcm_close(pcm);
3204         return WAVERR_BADFORMAT;
3205     } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
3206         FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
3207         snd_pcm_close(pcm);
3208         return WAVERR_BADFORMAT;
3209     } else {
3210         ERR("invalid format: %0x04x\n", wwi->format.Format.wFormatTag);
3211         snd_pcm_close(pcm);
3212         return WAVERR_BADFORMAT;
3213     }
3214
3215     EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), MMSYSERR_INVALPARAM, "unable to set required format");
3216
3217     rate = wwi->format.Format.nSamplesPerSec;
3218     dir = 0;
3219     err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
3220     if (err < 0) {
3221         ERR("Rate %ld Hz not available for playback: %s\n", wwi->format.Format.nSamplesPerSec, snd_strerror(rate));
3222         snd_pcm_close(pcm);
3223         return WAVERR_BADFORMAT;
3224     }
3225     if (rate != wwi->format.Format.nSamplesPerSec) {
3226         ERR("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwi->format.Format.nSamplesPerSec, rate);
3227         snd_pcm_close(pcm);
3228         return WAVERR_BADFORMAT;
3229     }
3230     
3231     dir=0; 
3232     EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
3233     dir=0; 
3234     EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
3235
3236     EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
3237     
3238     dir=0;
3239     err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
3240     err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
3241
3242     snd_pcm_sw_params_current(pcm, sw_params);
3243     EXIT_ON_ERROR( snd_pcm_sw_params_set_start_threshold(pcm, sw_params, dwFlags & WAVE_DIRECTSOUND ? INT_MAX : 1 ), MMSYSERR_ERROR, "unable to set start threshold");
3244     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
3245     EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
3246     EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
3247     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
3248     EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
3249 #undef EXIT_ON_ERROR
3250
3251     snd_pcm_prepare(pcm);
3252
3253     if (TRACE_ON(wave))
3254         ALSA_TraceParameters(hw_params, sw_params, FALSE);
3255
3256     /* now, we can save all required data for later use... */
3257     if ( wwi->hw_params )
3258         snd_pcm_hw_params_free(wwi->hw_params);
3259     snd_pcm_hw_params_malloc(&(wwi->hw_params));
3260     snd_pcm_hw_params_copy(wwi->hw_params, hw_params);
3261
3262     wwi->dwBufferSize = buffer_size;
3263     wwi->lpQueuePtr = wwi->lpPlayPtr = wwi->lpLoopPtr = NULL;
3264     wwi->p_handle = pcm;
3265
3266     ALSA_InitRingMessage(&wwi->msgRing);
3267
3268     wwi->count = snd_pcm_poll_descriptors_count (wwi->p_handle);
3269     if (wwi->count <= 0) {
3270         ERR("Invalid poll descriptors count\n");
3271         return MMSYSERR_ERROR;
3272     }
3273
3274     wwi->ufds = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct pollfd) * wwi->count);
3275     if (wwi->ufds == NULL) {
3276         ERR("No enough memory\n");
3277         return MMSYSERR_NOMEM;
3278     }
3279     if ((err = snd_pcm_poll_descriptors(wwi->p_handle, wwi->ufds, wwi->count)) < 0) {
3280         ERR("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
3281         return MMSYSERR_ERROR;
3282     }
3283
3284     wwi->dwPeriodSize = period_size;
3285     /*if (wwi->dwFragmentSize % wwi->format.Format.nBlockAlign)
3286         ERR("Fragment doesn't contain an integral number of data blocks\n");
3287     */
3288     TRACE("dwPeriodSize=%lu\n", wwi->dwPeriodSize);
3289     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
3290           wwi->format.Format.wBitsPerSample, wwi->format.Format.nAvgBytesPerSec,
3291           wwi->format.Format.nSamplesPerSec, wwi->format.Format.nChannels,
3292           wwi->format.Format.nBlockAlign);
3293
3294     if (!(dwFlags & WAVE_DIRECTSOUND)) {
3295         wwi->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
3296         wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
3297         WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
3298         CloseHandle(wwi->hStartUpEvent);
3299     } else {
3300         wwi->hThread = INVALID_HANDLE_VALUE;
3301         wwi->dwThreadID = 0;
3302     }
3303     wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
3304
3305     return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
3306 }
3307
3308
3309 /**************************************************************************
3310  *                              widClose                        [internal]
3311  */
3312 static DWORD widClose(WORD wDevID)
3313 {
3314     DWORD               ret = MMSYSERR_NOERROR;
3315     WINE_WAVEIN*        wwi;
3316
3317     TRACE("(%u);\n", wDevID);
3318
3319     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3320         WARN("bad device ID !\n");
3321         return MMSYSERR_BADDEVICEID;
3322     }
3323
3324     wwi = &WInDev[wDevID];
3325     if (wwi->lpQueuePtr) {
3326         WARN("buffers still playing !\n");
3327         ret = WAVERR_STILLPLAYING;
3328     } else {
3329         if (wwi->hThread != INVALID_HANDLE_VALUE) {
3330             ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
3331         }
3332         ALSA_DestroyRingMessage(&wwi->msgRing);
3333
3334         snd_pcm_hw_params_free(wwi->hw_params);
3335         wwi->hw_params = NULL;
3336
3337         snd_pcm_close(wwi->p_handle);
3338         wwi->p_handle = NULL;
3339
3340         ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
3341     }
3342
3343     HeapFree(GetProcessHeap(), 0, wwi->ufds);
3344     return ret;
3345 }
3346
3347 /**************************************************************************
3348  *                              widAddBuffer                    [internal]
3349  *
3350  */
3351 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3352 {
3353     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3354
3355     /* first, do the sanity checks... */
3356     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3357         WARN("bad dev ID !\n");
3358         return MMSYSERR_BADDEVICEID;
3359     }
3360
3361     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
3362         return WAVERR_UNPREPARED;
3363
3364     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3365         return WAVERR_STILLPLAYING;
3366
3367     lpWaveHdr->dwFlags &= ~WHDR_DONE;
3368     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
3369     lpWaveHdr->lpNext = 0;
3370
3371     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
3372
3373     return MMSYSERR_NOERROR;
3374 }
3375
3376 /**************************************************************************
3377  *                              widPrepare                      [internal]
3378  */
3379 static DWORD widPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3380 {
3381     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3382
3383     if (wDevID >= MAX_WAVEINDRV) {
3384         WARN("bad device ID !\n");
3385         return MMSYSERR_BADDEVICEID;
3386     }
3387
3388     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3389         return WAVERR_STILLPLAYING;
3390
3391     lpWaveHdr->dwFlags |= WHDR_PREPARED;
3392     lpWaveHdr->dwFlags &= ~WHDR_DONE;
3393     return MMSYSERR_NOERROR;
3394 }
3395
3396 /**************************************************************************
3397  *                              widUnprepare                    [internal]
3398  */
3399 static DWORD widUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3400 {
3401     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3402
3403     if (wDevID >= MAX_WAVEINDRV) {
3404         WARN("bad device ID !\n");
3405         return MMSYSERR_BADDEVICEID;
3406     }
3407
3408     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3409         return WAVERR_STILLPLAYING;
3410
3411     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
3412     lpWaveHdr->dwFlags |= WHDR_DONE;
3413
3414     return MMSYSERR_NOERROR;
3415 }
3416
3417 /**************************************************************************
3418  *                              widStart                        [internal]
3419  *
3420  */
3421 static DWORD widStart(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3422 {
3423     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3424
3425     /* first, do the sanity checks... */
3426     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3427         WARN("bad dev ID !\n");
3428         return MMSYSERR_BADDEVICEID;
3429     }
3430     
3431     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
3432
3433     Sleep(500);
3434
3435     return MMSYSERR_NOERROR;
3436 }
3437
3438 /**************************************************************************
3439  *                              widStop                 [internal]
3440  *
3441  */
3442 static DWORD widStop(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3443 {
3444     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3445
3446     /* first, do the sanity checks... */
3447     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3448         WARN("bad dev ID !\n");
3449         return MMSYSERR_BADDEVICEID;
3450     }
3451
3452     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
3453
3454     return MMSYSERR_NOERROR;
3455 }
3456
3457 /**************************************************************************
3458  *                      widReset                                [internal]
3459  */
3460 static DWORD widReset(WORD wDevID)
3461 {
3462     TRACE("(%u);\n", wDevID);
3463     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
3464         WARN("can't reset !\n");
3465         return MMSYSERR_INVALHANDLE;
3466     }
3467     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
3468     return MMSYSERR_NOERROR;
3469 }
3470
3471 /**************************************************************************
3472  *                              widGetPosition                  [internal]
3473  */
3474 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
3475 {
3476     WINE_WAVEIN*        wwi;
3477
3478     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
3479
3480     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
3481         WARN("can't get pos !\n");
3482         return MMSYSERR_INVALHANDLE;
3483     }
3484
3485     if (lpTime == NULL) {
3486         WARN("invalid parameter: lpTime = NULL\n");
3487         return MMSYSERR_INVALPARAM;
3488     }
3489
3490     wwi = &WInDev[wDevID];
3491     ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_UPDATE, 0, TRUE);
3492
3493     return bytes_to_mmtime(lpTime, wwi->dwTotalRecorded, &wwi->format);
3494 }
3495
3496 /**************************************************************************
3497  *                              widGetNumDevs                   [internal]
3498  */
3499 static  DWORD   widGetNumDevs(void)
3500 {
3501     return ALSA_WidNumDevs;
3502 }
3503
3504 /**************************************************************************
3505  *                              widDevInterfaceSize             [internal]
3506  */
3507 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
3508 {
3509     TRACE("(%u, %p)\n", wDevID, dwParam1);
3510
3511     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3512                                     NULL, 0 ) * sizeof(WCHAR);
3513     return MMSYSERR_NOERROR;
3514 }
3515
3516 /**************************************************************************
3517  *                              widDevInterface                 [internal]
3518  */
3519 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
3520 {
3521     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3522                                         NULL, 0 ) * sizeof(WCHAR))
3523     {
3524         MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3525                             dwParam1, dwParam2 / sizeof(WCHAR));
3526         return MMSYSERR_NOERROR;
3527     }
3528     return MMSYSERR_INVALPARAM;
3529 }
3530
3531 /**************************************************************************
3532  *                              widDsCreate                     [internal]
3533  */
3534 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
3535 {
3536     TRACE("(%d,%p)\n",wDevID,drv);
3537
3538     /* the HAL isn't much better than the HEL if we can't do mmap() */
3539     FIXME("DirectSoundCapture not implemented\n");
3540     MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
3541     return MMSYSERR_NOTSUPPORTED;
3542 }
3543
3544 /**************************************************************************
3545  *                              widDsDesc                       [internal]
3546  */
3547 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
3548 {
3549     memcpy(desc, &(WInDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
3550     return MMSYSERR_NOERROR;
3551 }
3552
3553 /**************************************************************************
3554  *                              widMessage (WINEALSA.@)
3555  */
3556 DWORD WINAPI ALSA_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
3557                              DWORD dwParam1, DWORD dwParam2)
3558 {
3559     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
3560           wDevID, wMsg, dwUser, dwParam1, dwParam2);
3561
3562     switch (wMsg) {
3563     case DRVM_INIT:
3564     case DRVM_EXIT:
3565     case DRVM_ENABLE:
3566     case DRVM_DISABLE:
3567         /* FIXME: Pretend this is supported */
3568         return 0;
3569     case WIDM_OPEN:             return widOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
3570     case WIDM_CLOSE:            return widClose         (wDevID);
3571     case WIDM_ADDBUFFER:        return widAddBuffer     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
3572     case WIDM_PREPARE:          return widPrepare       (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
3573     case WIDM_UNPREPARE:        return widUnprepare     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
3574     case WIDM_GETDEVCAPS:       return widGetDevCaps    (wDevID, (LPWAVEOUTCAPSW)dwParam1,      dwParam2);
3575     case WIDM_GETNUMDEVS:       return widGetNumDevs    ();
3576     case WIDM_GETPOS:           return widGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
3577     case WIDM_RESET:            return widReset         (wDevID);
3578     case WIDM_START:            return widStart (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
3579     case WIDM_STOP:             return widStop  (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
3580     case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
3581     case DRV_QUERYDEVICEINTERFACE:     return widDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
3582     case DRV_QUERYDSOUNDIFACE:  return widDsCreate   (wDevID, (PIDSCDRIVER*)dwParam1);
3583     case DRV_QUERYDSOUNDDESC:   return widDsDesc     (wDevID, (PDSDRIVERDESC)dwParam1);
3584     default:
3585         FIXME("unknown message %d!\n", wMsg);
3586     }
3587     return MMSYSERR_NOTSUPPORTED;
3588 }
3589
3590 #else
3591
3592 /**************************************************************************
3593  *                              widMessage (WINEALSA.@)
3594  */
3595 DWORD WINAPI ALSA_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3596                              DWORD dwParam1, DWORD dwParam2)
3597 {
3598     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3599     return MMSYSERR_NOTENABLED;
3600 }
3601
3602 /**************************************************************************
3603  *                              wodMessage (WINEALSA.@)
3604  */
3605 DWORD WINAPI ALSA_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3606                              DWORD dwParam1, DWORD dwParam2)
3607 {
3608     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3609     return MMSYSERR_NOTENABLED;
3610 }
3611
3612 #endif /* HAVE_ALSA */