ALSA_WaveInit: repaired device name.
[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  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
27 #include <stdlib.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34 #include <errno.h>
35 #include <limits.h>
36 #include <fcntl.h>
37 #ifdef HAVE_SYS_IOCTL_H
38 # include <sys/ioctl.h>
39 #endif
40 #ifdef HAVE_SYS_MMAN_H
41 # include <sys/mman.h>
42 #endif
43 #include "windef.h"
44 #include "winbase.h"
45 #include "wingdi.h"
46 #include "winerror.h"
47 #include "winuser.h"
48 #include "mmddk.h"
49 #include "dsound.h"
50 #include "dsdriver.h"
51 #include "alsa.h"
52 #include "wine/library.h"
53 #include "wine/debug.h"
54
55 WINE_DEFAULT_DEBUG_CHANNEL(wave);
56
57
58 #define FAKE_CHARPTR(s) ((char *)(unsigned long)(s))
59
60 #if defined(HAVE_ALSA) && ((SND_LIB_MAJOR == 0 && SND_LIB_MINOR >= 9) || SND_LIB_MAJOR >= 1)
61
62 /* internal ALSALIB functions */
63 snd_pcm_uframes_t _snd_pcm_mmap_hw_ptr(snd_pcm_t *pcm);
64
65
66 #define MAX_WAVEOUTDRV  (1)
67 #define MAX_WAVEINDRV   (1)
68
69 /* state diagram for waveOut writing:
70  *
71  * +---------+-------------+---------------+---------------------------------+
72  * |  state  |  function   |     event     |            new state            |
73  * +---------+-------------+---------------+---------------------------------+
74  * |         | open()      |               | STOPPED                         |
75  * | PAUSED  | write()     |               | PAUSED                          |
76  * | STOPPED | write()     | <thrd create> | PLAYING                         |
77  * | PLAYING | write()     | HEADER        | PLAYING                         |
78  * | (other) | write()     | <error>       |                                 |
79  * | (any)   | pause()     | PAUSING       | PAUSED                          |
80  * | PAUSED  | restart()   | RESTARTING    | PLAYING (if no thrd => STOPPED) |
81  * | (any)   | reset()     | RESETTING     | STOPPED                         |
82  * | (any)   | close()     | CLOSING       | CLOSED                          |
83  * +---------+-------------+---------------+---------------------------------+
84  */
85
86 /* states of the playing device */
87 #define WINE_WS_PLAYING         0
88 #define WINE_WS_PAUSED          1
89 #define WINE_WS_STOPPED         2
90 #define WINE_WS_CLOSED          3
91
92 /* events to be send to device */
93 enum win_wm_message {
94     WINE_WM_PAUSING = WM_USER + 1, WINE_WM_RESTARTING, WINE_WM_RESETTING, WINE_WM_HEADER,
95     WINE_WM_UPDATE, WINE_WM_BREAKLOOP, WINE_WM_CLOSING
96 };
97
98 typedef struct {
99     enum win_wm_message         msg;    /* message identifier */
100     DWORD                       param;  /* parameter for this message */
101     HANDLE                      hEvent; /* if message is synchronous, handle of event for synchro */
102 } ALSA_MSG;
103
104 /* implement an in-process message ring for better performance
105  * (compared to passing thru the server)
106  * this ring will be used by the input (resp output) record (resp playback) routine
107  */
108 #define ALSA_RING_BUFFER_INCREMENT      64
109 typedef struct {
110     ALSA_MSG                    * messages;
111     int                         ring_buffer_size;
112     int                         msg_tosave;
113     int                         msg_toget;
114     HANDLE                      msg_event;
115     CRITICAL_SECTION            msg_crst;
116 } ALSA_MSG_RING;
117
118 typedef struct {
119     /* Windows information */
120     volatile int                state;                  /* one of the WINE_WS_ manifest constants */
121     WAVEOPENDESC                waveDesc;
122     WORD                        wFlags;
123     PCMWAVEFORMAT               format;
124     WAVEOUTCAPSA                caps;
125
126     /* ALSA information (ALSA 0.9/1.x uses two different devices for playback/capture) */
127     char *                      device;
128     snd_pcm_t*                  p_handle;                 /* handle to ALSA playback device */
129     snd_pcm_t*                  c_handle;                 /* handle to ALSA capture device */
130     snd_pcm_hw_params_t *       hw_params;              /* ALSA Hw params */
131
132     snd_ctl_t *                 ctl;                    /* control handle for the playback volume */
133     snd_ctl_elem_id_t *         playback_eid;           /* element id of the playback volume control */
134     snd_ctl_elem_value_t *      playback_evalue;        /* element value of the playback volume control */
135     snd_ctl_elem_info_t *       playback_einfo;         /* element info of the playback volume control */
136
137     snd_pcm_sframes_t           (*write)(snd_pcm_t *, const void *, snd_pcm_uframes_t );
138
139     struct pollfd               *ufds;
140     int                         count;
141
142     DWORD                       dwBufferSize;           /* size of whole ALSA buffer in bytes */
143     LPWAVEHDR                   lpQueuePtr;             /* start of queued WAVEHDRs (waiting to be notified) */
144     LPWAVEHDR                   lpPlayPtr;              /* start of not yet fully played buffers */
145
146     LPWAVEHDR                   lpLoopPtr;              /* pointer of first buffer in loop, if any */
147     DWORD                       dwLoops;                /* private copy of loop counter */
148
149     DWORD                       dwPlayedTotal;
150
151     /* synchronization stuff */
152     HANDLE                      hStartUpEvent;
153     HANDLE                      hThread;
154     DWORD                       dwThreadID;
155     ALSA_MSG_RING               msgRing;
156
157     /* DirectSound stuff */
158     DSDRIVERDESC                ds_desc;
159     GUID                        ds_guid;
160 } WINE_WAVEOUT;
161
162 static WINE_WAVEOUT     WOutDev   [MAX_WAVEOUTDRV];
163 static DWORD            ALSA_WodNumDevs;
164
165 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
166 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
167 static DWORD wodDsGuid(UINT wDevID, LPGUID pGuid);
168
169 /* These strings used only for tracing */
170 #if 0
171 static const char *wodPlayerCmdString[] = {
172     "WINE_WM_PAUSING",
173     "WINE_WM_RESTARTING",
174     "WINE_WM_RESETTING",
175     "WINE_WM_HEADER",
176     "WINE_WM_UPDATE",
177     "WINE_WM_BREAKLOOP",
178     "WINE_WM_CLOSING",
179 };
180 #endif
181
182 /*======================================================================*
183  *                  Low level WAVE implementation                       *
184  *======================================================================*/
185
186 /**************************************************************************
187  *                      ALSA_InitializeVolumeCtl                [internal]
188  *
189  * used to initialize the PCM Volume Control
190  */
191 static int ALSA_InitializeVolumeCtl(WINE_WAVEOUT * wwo)
192 {
193     snd_ctl_t *                 ctl = NULL;
194     snd_ctl_card_info_t *       cardinfo;
195     snd_ctl_elem_list_t *       elemlist;
196     snd_ctl_elem_id_t *         e_id;
197     snd_ctl_elem_info_t *       einfo;
198     snd_hctl_t *                hctl = NULL;
199     snd_hctl_elem_t *           elem;
200     int                         nCtrls;
201     int                         i;
202
203     snd_ctl_card_info_alloca(&cardinfo);
204     memset(cardinfo,0,snd_ctl_card_info_sizeof());
205
206     snd_ctl_elem_list_alloca(&elemlist);
207     memset(elemlist,0,snd_ctl_elem_list_sizeof());
208
209     snd_ctl_elem_id_alloca(&e_id);
210     memset(e_id,0,snd_ctl_elem_id_sizeof());
211
212     snd_ctl_elem_info_alloca(&einfo);
213     memset(einfo,0,snd_ctl_elem_info_sizeof());
214
215 #define EXIT_ON_ERROR(f,txt) do \
216 { \
217     int err; \
218     if ( (err = (f) ) < 0) \
219     { \
220         ERR(txt ": %s\n", snd_strerror(err)); \
221         if (hctl) \
222             snd_hctl_close(hctl); \
223         if (ctl) \
224             snd_ctl_close(ctl); \
225         return -1; \
226     } \
227 } while(0)
228
229     EXIT_ON_ERROR( snd_ctl_open(&ctl,"hw",0) , "ctl open failed" );
230     EXIT_ON_ERROR( snd_ctl_card_info(ctl, cardinfo), "card info failed");
231     EXIT_ON_ERROR( snd_ctl_elem_list(ctl, elemlist), "elem list failed");
232
233     nCtrls = snd_ctl_elem_list_get_count(elemlist);
234
235     EXIT_ON_ERROR( snd_hctl_open(&hctl,"hw",0), "hctl open failed");
236     EXIT_ON_ERROR( snd_hctl_load(hctl), "hctl load failed" );
237
238     elem=snd_hctl_first_elem(hctl);
239     for ( i= 0; i<nCtrls; i++) {
240
241         memset(e_id,0,snd_ctl_elem_id_sizeof());
242
243         snd_hctl_elem_get_id(elem,e_id);
244 /*
245         TRACE("ctl: #%d '%s'%d\n",
246                                    snd_ctl_elem_id_get_numid(e_id),
247                                    snd_ctl_elem_id_get_name(e_id),
248                                    snd_ctl_elem_id_get_index(e_id));
249 */
250         if ( !strcmp("PCM Playback Volume", snd_ctl_elem_id_get_name(e_id)) )
251         {
252             EXIT_ON_ERROR( snd_hctl_elem_info(elem,einfo), "hctl elem info failed" );
253
254             /* few sanity checks... you'll never know... */
255             if ( snd_ctl_elem_info_get_type(einfo) != SND_CTL_ELEM_TYPE_INTEGER )
256                 WARN("playback volume control is not an integer\n");
257             if ( !snd_ctl_elem_info_is_readable(einfo) )
258                 WARN("playback volume control is readable\n");
259             if ( !snd_ctl_elem_info_is_writable(einfo) )
260                 WARN("playback volume control is readable\n");
261
262             TRACE("   ctrl range: min=%ld  max=%ld  step=%ld\n",
263                  snd_ctl_elem_info_get_min(einfo),
264                  snd_ctl_elem_info_get_max(einfo),
265                  snd_ctl_elem_info_get_step(einfo));
266
267             EXIT_ON_ERROR( snd_ctl_elem_id_malloc(&wwo->playback_eid), "elem id malloc failed" );
268             EXIT_ON_ERROR( snd_ctl_elem_info_malloc(&wwo->playback_einfo), "elem info malloc failed" );
269             EXIT_ON_ERROR( snd_ctl_elem_value_malloc(&wwo->playback_evalue), "elem value malloc failed" );
270
271             /* ok, now we can safely save these objects for later */
272             snd_ctl_elem_id_copy(wwo->playback_eid, e_id);
273             snd_ctl_elem_info_copy(wwo->playback_einfo, einfo);
274             snd_ctl_elem_value_set_id(wwo->playback_evalue, wwo->playback_eid);
275             wwo->ctl = ctl;
276         }
277
278         elem=snd_hctl_elem_next(elem);
279     }
280     snd_hctl_close(hctl);
281 #undef EXIT_ON_ERROR
282     return 0;
283 }
284
285 /**************************************************************************
286  *                      ALSA_XRUNRecovery               [internal]
287  *
288  * used to recovery from XRUN errors (buffer underflow/overflow)
289  */
290 static int ALSA_XRUNRecovery(WINE_WAVEOUT * wwo, int err)
291 {
292     if (err == -EPIPE) {    /* under-run */
293         err = snd_pcm_prepare(wwo->p_handle);
294         if (err < 0)
295              ERR( "underrun recovery failed. prepare failed: %s\n", snd_strerror(err));
296         return 0;
297     } else if (err == -ESTRPIPE) {
298         while ((err = snd_pcm_resume(wwo->p_handle)) == -EAGAIN)
299             sleep(1);       /* wait until the suspend flag is released */
300             if (err < 0) {
301                 err = snd_pcm_prepare(wwo->p_handle);
302                 if (err < 0)
303                     ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
304             }
305             return 0;
306     }
307     return err;
308 }
309
310 /**************************************************************************
311  *                      ALSA_TraceParameters            [internal]
312  *
313  * used to trace format changes, hw and sw parameters
314  */
315 static void ALSA_TraceParameters(snd_pcm_hw_params_t * hw_params, snd_pcm_sw_params_t * sw, int full)
316 {
317     snd_pcm_format_t   format = snd_pcm_hw_params_get_format(hw_params);
318     snd_pcm_access_t   access = snd_pcm_hw_params_get_access(hw_params);
319
320 #define X(x) ((x)? "true" : "false")
321     if (full)
322         TRACE("FLAGS: sampleres=%s overrng=%s pause=%s resume=%s syncstart=%s batch=%s block=%s double=%s "
323               "halfd=%s joint=%s \n",
324               X(snd_pcm_hw_params_can_mmap_sample_resolution(hw_params)),
325               X(snd_pcm_hw_params_can_overrange(hw_params)),
326               X(snd_pcm_hw_params_can_pause(hw_params)),
327               X(snd_pcm_hw_params_can_resume(hw_params)),
328               X(snd_pcm_hw_params_can_sync_start(hw_params)),
329               X(snd_pcm_hw_params_is_batch(hw_params)),
330               X(snd_pcm_hw_params_is_block_transfer(hw_params)),
331               X(snd_pcm_hw_params_is_double(hw_params)),
332               X(snd_pcm_hw_params_is_half_duplex(hw_params)),
333               X(snd_pcm_hw_params_is_joint_duplex(hw_params)));
334 #undef X
335
336     if (access >= 0)
337         TRACE("access=%s\n", snd_pcm_access_name(access));
338     else
339     {
340         snd_pcm_access_mask_t * acmask;
341         snd_pcm_access_mask_alloca(&acmask);
342         snd_pcm_hw_params_get_access_mask(hw_params, acmask);
343         for ( access = SND_PCM_ACCESS_MMAP_INTERLEAVED; access <= SND_PCM_ACCESS_LAST; access++)
344             if (snd_pcm_access_mask_test(acmask, access))
345                 TRACE("access=%s\n", snd_pcm_access_name(access));
346     }
347
348     if (format >= 0)
349     {
350         TRACE("format=%s\n", snd_pcm_format_name(format));
351
352     }
353     else
354     {
355         snd_pcm_format_mask_t *     fmask;
356
357         snd_pcm_format_mask_alloca(&fmask);
358         snd_pcm_hw_params_get_format_mask(hw_params, fmask);
359         for ( format = SND_PCM_FORMAT_S8; format <= SND_PCM_FORMAT_LAST ; format++)
360             if ( snd_pcm_format_mask_test(fmask, format) )
361                 TRACE("format=%s\n", snd_pcm_format_name(format));
362     }
363
364 #define X(x) do { \
365 int n = snd_pcm_hw_params_get_##x(hw_params); \
366 if (n<0) \
367     TRACE(#x "_min=%ld " #x "_max=%ld\n", \
368         (long int)snd_pcm_hw_params_get_##x##_min(hw_params), \
369         (long int)snd_pcm_hw_params_get_##x##_max(hw_params)); \
370 else \
371     TRACE(#x "=%d\n", n); \
372 } while(0)
373     X(channels);
374     X(buffer_size);
375 #undef X
376
377 #define X(x) do { \
378 int n = snd_pcm_hw_params_get_##x(hw_params,0); \
379 if (n<0) \
380     TRACE(#x "_min=%ld " #x "_max=%ld\n", \
381         (long int)snd_pcm_hw_params_get_##x##_min(hw_params,0), \
382         (long int)snd_pcm_hw_params_get_##x##_max(hw_params,0)); \
383 else \
384     TRACE(#x "=%d\n", n); \
385 } while(0)
386     X(rate);
387     X(buffer_time);
388     X(periods);
389     X(period_size);
390     X(period_time);
391     X(tick_time);
392 #undef X
393
394     if (!sw)
395         return;
396
397
398 }
399
400
401
402 /******************************************************************
403  *              ALSA_WaveInit
404  *
405  * Initialize internal structures from ALSA information
406  */
407 LONG ALSA_WaveInit(void)
408 {
409     snd_pcm_t*                  h = NULL;
410     snd_pcm_info_t *            info;
411     snd_pcm_hw_params_t *       hw_params;
412     WINE_WAVEOUT*               wwo;
413
414     wwo = &WOutDev[0];
415
416     /* FIXME: use better values */
417     wwo->device = FAKE_CHARPTR("hw");
418     wwo->caps.wMid = 0x0002;
419     wwo->caps.wPid = 0x0104;
420     strcpy(wwo->caps.szPname, "SB16 Wave Out");
421     wwo->caps.vDriverVersion = 0x0100;
422     wwo->caps.dwFormats = 0x00000000;
423     wwo->caps.dwSupport = WAVECAPS_VOLUME;
424     strcpy(wwo->ds_desc.szDesc, "WineALSA DirectSound Driver");
425     strcpy(wwo->ds_desc.szDrvName, "winealsa.drv");
426     wwo->ds_guid = DSDEVID_DefaultPlayback;
427
428     if (!wine_dlopen("libasound.so.2", RTLD_LAZY|RTLD_GLOBAL, NULL, 0))
429     {
430         ERR("Error: ALSA lib needs to be loaded with flags RTLD_LAZY and RTLD_GLOBAL.\n");
431         return -1;
432     }
433
434     snd_pcm_info_alloca(&info);
435     snd_pcm_hw_params_alloca(&hw_params);
436
437 #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)
438
439     ALSA_WodNumDevs = 0;
440     EXIT_ON_ERROR( snd_pcm_open(&h, wwo->device, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK) , "open pcm" );
441     if (!h) return -1;
442     ALSA_WodNumDevs++;
443
444     EXIT_ON_ERROR( snd_pcm_info(h, info) , "pcm info" );
445
446     TRACE("dev=%d id=%s name=%s subdev=%d subdev_name=%s subdev_avail=%d subdev_num=%d stream=%s subclass=%s \n",
447        snd_pcm_info_get_device(info),
448        snd_pcm_info_get_id(info),
449        snd_pcm_info_get_name(info),
450        snd_pcm_info_get_subdevice(info),
451        snd_pcm_info_get_subdevice_name(info),
452        snd_pcm_info_get_subdevices_avail(info),
453        snd_pcm_info_get_subdevices_count(info),
454        snd_pcm_stream_name(snd_pcm_info_get_stream(info)),
455        (snd_pcm_info_get_subclass(info) == SND_PCM_SUBCLASS_GENERIC_MIX ? "GENERIC MIX": "MULTI MIX"));
456
457     EXIT_ON_ERROR( snd_pcm_hw_params_any(h, hw_params) , "pcm hw params" );
458 #undef EXIT_ON_ERROR
459
460     if (TRACE_ON(wave))
461         ALSA_TraceParameters(hw_params, NULL, TRUE);
462
463     {
464         snd_pcm_format_mask_t *     fmask;
465         int ratemin = snd_pcm_hw_params_get_rate_min(hw_params, 0);
466         int ratemax = snd_pcm_hw_params_get_rate_max(hw_params, 0);
467         int chmin = snd_pcm_hw_params_get_channels_min(hw_params); \
468         int chmax = snd_pcm_hw_params_get_channels_max(hw_params); \
469
470         snd_pcm_format_mask_alloca(&fmask);
471         snd_pcm_hw_params_get_format_mask(hw_params, fmask);
472
473 #define X(r,v) \
474        if ( (r) >= ratemin && ( (r) <= ratemax || ratemax == -1) ) \
475        { \
476           if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_U8)) \
477           { \
478               if (chmin <= 1 && 1 <= chmax) \
479                   wwo->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
480               if (chmin <= 2 && 2 <= chmax) \
481                   wwo->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
482           } \
483           if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_S16_LE)) \
484           { \
485               if (chmin <= 1 && 1 <= chmax) \
486                   wwo->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
487               if (chmin <= 2 && 2 <= chmax) \
488                   wwo->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
489           } \
490        }
491        X(11025,1);
492        X(22050,2);
493        X(44100,4);
494 #undef X
495     }
496
497     if ( snd_pcm_hw_params_get_channels_min(hw_params) > 1) FIXME("-\n");
498     wwo->caps.wChannels = (snd_pcm_hw_params_get_channels_max(hw_params) >= 2) ? 2 : 1;
499     if (snd_pcm_hw_params_get_channels_min(hw_params) <= 2 && 2 <= snd_pcm_hw_params_get_channels_max(hw_params))
500         wwo->caps.dwSupport |= WAVECAPS_LRVOLUME;
501
502     /* FIXME: always true ? */
503     wwo->caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
504
505     {
506         snd_pcm_access_mask_t *     acmask;
507         snd_pcm_access_mask_alloca(&acmask);
508         snd_pcm_hw_params_get_access_mask(hw_params, acmask);
509
510         /* FIXME: NONITERLEAVED and COMPLEX are not supported right now */
511         if ( snd_pcm_access_mask_test( acmask, SND_PCM_ACCESS_MMAP_INTERLEAVED ) )
512             wwo->caps.dwSupport |= WAVECAPS_DIRECTSOUND;
513     }
514
515     TRACE("Configured with dwFmts=%08lx dwSupport=%08lx\n",
516           wwo->caps.dwFormats, wwo->caps.dwSupport);
517
518     snd_pcm_close(h);
519
520     ALSA_InitializeVolumeCtl(wwo);
521
522     return 0;
523 }
524
525 /******************************************************************
526  *              ALSA_InitRingMessage
527  *
528  * Initialize the ring of messages for passing between driver's caller and playback/record
529  * thread
530  */
531 static int ALSA_InitRingMessage(ALSA_MSG_RING* omr)
532 {
533     omr->msg_toget = 0;
534     omr->msg_tosave = 0;
535     omr->msg_event = CreateEventA(NULL, FALSE, FALSE, NULL);
536     omr->ring_buffer_size = ALSA_RING_BUFFER_INCREMENT;
537     omr->messages = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,omr->ring_buffer_size * sizeof(ALSA_MSG));
538
539     InitializeCriticalSection(&omr->msg_crst);
540     return 0;
541 }
542
543 /******************************************************************
544  *              ALSA_DestroyRingMessage
545  *
546  */
547 static int ALSA_DestroyRingMessage(ALSA_MSG_RING* omr)
548 {
549     CloseHandle(omr->msg_event);
550     HeapFree(GetProcessHeap(),0,omr->messages);
551     DeleteCriticalSection(&omr->msg_crst);
552     return 0;
553 }
554
555 /******************************************************************
556  *              ALSA_AddRingMessage
557  *
558  * Inserts a new message into the ring (should be called from DriverProc derivated routines)
559  */
560 static int ALSA_AddRingMessage(ALSA_MSG_RING* omr, enum win_wm_message msg, DWORD param, BOOL wait)
561 {
562     HANDLE      hEvent = INVALID_HANDLE_VALUE;
563
564     EnterCriticalSection(&omr->msg_crst);
565     if ((omr->msg_toget == ((omr->msg_tosave + 1) % omr->ring_buffer_size)))
566     {
567         omr->ring_buffer_size += ALSA_RING_BUFFER_INCREMENT;
568         TRACE("omr->ring_buffer_size=%d\n",omr->ring_buffer_size);
569         omr->messages = HeapReAlloc(GetProcessHeap(),0,omr->messages, omr->ring_buffer_size * sizeof(ALSA_MSG));
570     }
571     if (wait)
572     {
573         hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
574         if (hEvent == INVALID_HANDLE_VALUE)
575         {
576             ERR("can't create event !?\n");
577             LeaveCriticalSection(&omr->msg_crst);
578             return 0;
579         }
580         if (omr->msg_toget != omr->msg_tosave && omr->messages[omr->msg_toget].msg != WINE_WM_HEADER)
581             FIXME("two fast messages in the queue!!!!\n");
582
583         /* fast messages have to be added at the start of the queue */
584         omr->msg_toget = (omr->msg_toget + omr->ring_buffer_size - 1) % omr->ring_buffer_size;
585
586         omr->messages[omr->msg_toget].msg = msg;
587         omr->messages[omr->msg_toget].param = param;
588         omr->messages[omr->msg_toget].hEvent = hEvent;
589     }
590     else
591     {
592         omr->messages[omr->msg_tosave].msg = msg;
593         omr->messages[omr->msg_tosave].param = param;
594         omr->messages[omr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
595         omr->msg_tosave = (omr->msg_tosave + 1) % omr->ring_buffer_size;
596     }
597     LeaveCriticalSection(&omr->msg_crst);
598     /* signal a new message */
599     SetEvent(omr->msg_event);
600     if (wait)
601     {
602         /* wait for playback/record thread to have processed the message */
603         WaitForSingleObject(hEvent, INFINITE);
604         CloseHandle(hEvent);
605     }
606     return 1;
607 }
608
609 /******************************************************************
610  *              ALSA_RetrieveRingMessage
611  *
612  * Get a message from the ring. Should be called by the playback/record thread.
613  */
614 static int ALSA_RetrieveRingMessage(ALSA_MSG_RING* omr,
615                                    enum win_wm_message *msg, DWORD *param, HANDLE *hEvent)
616 {
617     EnterCriticalSection(&omr->msg_crst);
618
619     if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
620     {
621         LeaveCriticalSection(&omr->msg_crst);
622         return 0;
623     }
624
625     *msg = omr->messages[omr->msg_toget].msg;
626     omr->messages[omr->msg_toget].msg = 0;
627     *param = omr->messages[omr->msg_toget].param;
628     *hEvent = omr->messages[omr->msg_toget].hEvent;
629     omr->msg_toget = (omr->msg_toget + 1) % omr->ring_buffer_size;
630     LeaveCriticalSection(&omr->msg_crst);
631     return 1;
632 }
633
634 /*======================================================================*
635  *                  Low level WAVE OUT implementation                   *
636  *======================================================================*/
637
638
639 /**************************************************************************
640  *                      wodNotifyClient                 [internal]
641  */
642 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
643 {
644     TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
645
646     switch (wMsg) {
647     case WOM_OPEN:
648     case WOM_CLOSE:
649     case WOM_DONE:
650         if (wwo->wFlags != DCB_NULL &&
651             !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags, (HDRVR)wwo->waveDesc.hWave,
652                             wMsg, wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
653             WARN("can't notify client !\n");
654             return MMSYSERR_ERROR;
655         }
656         break;
657     default:
658         FIXME("Unknown callback message %u\n", wMsg);
659         return MMSYSERR_INVALPARAM;
660     }
661     return MMSYSERR_NOERROR;
662 }
663
664 /**************************************************************************
665  *                              wodUpdatePlayedTotal    [internal]
666  *
667  */
668 static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo, snd_pcm_status_t* ps)
669 {
670    return TRUE;
671 }
672
673 /**************************************************************************
674  *                              wodPlayer_BeginWaveHdr          [internal]
675  *
676  * Makes the specified lpWaveHdr the currently playing wave header.
677  * If the specified wave header is a begin loop and we're not already in
678  * a loop, setup the loop.
679  */
680 static void wodPlayer_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
681 {
682     wwo->lpPlayPtr = lpWaveHdr;
683
684     if (!lpWaveHdr) return;
685
686     wwo->lpPlayPtr->reserved = 0;
687
688     if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
689         if (wwo->lpLoopPtr) {
690             WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
691         } else {
692             TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
693             wwo->lpLoopPtr = lpWaveHdr;
694             /* Windows does not touch WAVEHDR.dwLoops,
695              * so we need to make an internal copy */
696             wwo->dwLoops = lpWaveHdr->dwLoops;
697         }
698     }
699 }
700
701 /**************************************************************************
702  *                              wodPlayer_PlayPtrNext           [internal]
703  *
704  * Advance the play pointer to the next waveheader, looping if required.
705  */
706 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEOUT* wwo)
707 {
708     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
709
710     if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
711         /* We're at the end of a loop, loop if required */
712         if (--wwo->dwLoops > 0) {
713             wwo->lpPlayPtr = wwo->lpLoopPtr;
714             wwo->lpPlayPtr->reserved = 0;
715         } else {
716             /* Handle overlapping loops correctly */
717             if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
718                 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
719                 /* shall we consider the END flag for the closing loop or for
720                  * the opening one or for both ???
721                  * code assumes for closing loop only
722                  */
723             } else {
724                 lpWaveHdr = lpWaveHdr->lpNext;
725             }
726             wwo->lpLoopPtr = NULL;
727             wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
728         }
729     } else {
730         /* We're not in a loop.  Advance to the next wave header */
731         wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
732     }
733
734     return lpWaveHdr;
735 }
736
737 /**************************************************************************
738  *                           wodPlayer_DSPWait                  [internal]
739  * Returns the number of milliseconds to wait for the DSP buffer to play a
740  * period
741  */
742 static DWORD wodPlayer_DSPWait(const WINE_WAVEOUT *wwo)
743 {
744     /* time for one period to be played */
745     return snd_pcm_hw_params_get_period_time(wwo->hw_params, 0) / 1000;
746 }
747
748 /**************************************************************************
749  *                           wodPllayer_NotifyWait               [internal]
750  * Returns the number of milliseconds to wait before attempting to notify
751  * completion of the specified wavehdr.
752  * This is based on the number of bytes remaining to be written in the
753  * wave.
754  */
755 static DWORD wodPlayer_NotifyWait(const WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
756 {
757     DWORD dwMillis;
758
759     dwMillis = (lpWaveHdr->dwBufferLength - lpWaveHdr->reserved) * 1000 / wwo->format.wf.nAvgBytesPerSec;
760     if (!dwMillis) dwMillis = 1;
761
762     return dwMillis;
763 }
764
765
766 /**************************************************************************
767  *                           wodPlayer_WriteMaxFrags            [internal]
768  * Writes the maximum number of frames possible to the DSP and returns
769  * the number of frames written.
770  */
771 static int wodPlayer_WriteMaxFrags(WINE_WAVEOUT* wwo, DWORD* frames)
772 {
773     /* Only attempt to write to free frames */
774     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
775     DWORD dwLength = snd_pcm_bytes_to_frames(wwo->p_handle, lpWaveHdr->dwBufferLength - lpWaveHdr->reserved);
776     int toWrite = min(dwLength, *frames);
777     int written;
778
779     TRACE("Writing wavehdr %p.%lu[%lu]\n", lpWaveHdr, lpWaveHdr->reserved, lpWaveHdr->dwBufferLength);
780
781     written = (wwo->write)(wwo->p_handle, lpWaveHdr->lpData + lpWaveHdr->reserved, toWrite);
782     if ( written < 0)
783     {
784         /* XRUN occurred. let's try to recover */
785         ALSA_XRUNRecovery(wwo, written);
786         written = (wwo->write)(wwo->p_handle, lpWaveHdr->lpData + lpWaveHdr->reserved, toWrite);
787     }
788     if (written <= 0)
789     {
790         /* still in error */
791         ERR("Error in writing wavehdr. Reason: %s\n", snd_strerror(written));
792         return written;
793     }
794
795     lpWaveHdr->reserved += snd_pcm_frames_to_bytes(wwo->p_handle, written);
796     if ( lpWaveHdr->reserved >= lpWaveHdr->dwBufferLength) {
797         /* this will be used to check if the given wave header has been fully played or not... */
798         lpWaveHdr->reserved = lpWaveHdr->dwBufferLength;
799         /* If we wrote all current wavehdr, skip to the next one */
800         wodPlayer_PlayPtrNext(wwo);
801     }
802     *frames -= written;
803     wwo->dwPlayedTotal += snd_pcm_frames_to_bytes(wwo->p_handle, written);
804
805     return written;
806 }
807
808
809 /**************************************************************************
810  *                              wodPlayer_NotifyCompletions     [internal]
811  *
812  * Notifies and remove from queue all wavehdrs which have been played to
813  * the speaker (ie. they have cleared the ALSA buffer).  If force is true,
814  * we notify all wavehdrs and remove them all from the queue even if they
815  * are unplayed or part of a loop.
816  */
817 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
818 {
819     LPWAVEHDR           lpWaveHdr;
820
821     /* Start from lpQueuePtr and keep notifying until:
822      * - we hit an unwritten wavehdr
823      * - we hit the beginning of a running loop
824      * - we hit a wavehdr which hasn't finished playing
825      */
826     while ((lpWaveHdr = wwo->lpQueuePtr) &&
827            (force ||
828             (lpWaveHdr != wwo->lpPlayPtr &&
829              lpWaveHdr != wwo->lpLoopPtr &&
830              lpWaveHdr->reserved == lpWaveHdr->dwBufferLength))) {
831
832         wwo->lpQueuePtr = lpWaveHdr->lpNext;
833
834         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
835         lpWaveHdr->dwFlags |= WHDR_DONE;
836
837         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
838     }
839     return  (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
840         wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
841 }
842
843
844 void wait_for_poll(snd_pcm_t *handle, struct pollfd *ufds, unsigned int count)
845 {
846     unsigned short revents;
847
848     while (1) {
849         poll(ufds, count, -1);
850         snd_pcm_poll_descriptors_revents(handle, ufds, count, &revents);
851
852         if (revents & POLLERR)
853             return;
854
855         /*if (revents & POLLOUT)
856                 return 0;*/
857     }
858 }
859
860
861 /**************************************************************************
862  *                              wodPlayer_Reset                 [internal]
863  *
864  * wodPlayer helper. Resets current output stream.
865  */
866 static  void    wodPlayer_Reset(WINE_WAVEOUT* wwo)
867 {
868     enum win_wm_message msg;
869     DWORD                       param;
870     HANDLE                      ev;
871     int                         err;
872
873     /* flush all possible output */
874     wait_for_poll(wwo->p_handle, wwo->ufds, wwo->count);
875
876     /* updates current notify list */
877     wodPlayer_NotifyCompletions(wwo, FALSE);
878
879     if ( (err = snd_pcm_drop(wwo->p_handle)) < 0) {
880         FIXME("flush: %s\n", snd_strerror(err));
881         wwo->hThread = 0;
882         wwo->state = WINE_WS_STOPPED;
883         ExitThread(-1);
884     }
885     if ( (err = snd_pcm_prepare(wwo->p_handle)) < 0 )
886         ERR("pcm prepare failed: %s\n", snd_strerror(err));
887
888     /* remove any buffer */
889     wodPlayer_NotifyCompletions(wwo, TRUE);
890
891     wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
892     wwo->state = WINE_WS_STOPPED;
893
894     /* remove any existing message in the ring */
895     EnterCriticalSection(&wwo->msgRing.msg_crst);
896     /* return all pending headers in queue */
897     while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
898     {
899         if (msg != WINE_WM_HEADER)
900         {
901             FIXME("shouldn't have headers left\n");
902             SetEvent(ev);
903             continue;
904         }
905         ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
906         ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
907
908         wodNotifyClient(wwo, WOM_DONE, param, 0);
909     }
910     ResetEvent(wwo->msgRing.msg_event);
911     LeaveCriticalSection(&wwo->msgRing.msg_crst);
912 }
913
914 /**************************************************************************
915  *                    wodPlayer_ProcessMessages                 [internal]
916  */
917 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
918 {
919     LPWAVEHDR           lpWaveHdr;
920     enum win_wm_message msg;
921     DWORD               param;
922     HANDLE              ev;
923     int                 err;
924
925     while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
926     /* TRACE("Received %s %lx\n", wodPlayerCmdString[msg - WM_USER - 1], param); */
927
928         switch (msg) {
929         case WINE_WM_PAUSING:
930             if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_RUNNING )
931              {
932                 err = snd_pcm_pause(wwo->p_handle, 1);
933                 if ( err < 0 )
934                     ERR("pcm_pause failed: %s\n", snd_strerror(err));
935              }
936             wwo->state = WINE_WS_PAUSED;
937             SetEvent(ev);
938             break;
939         case WINE_WM_RESTARTING:
940             if (wwo->state == WINE_WS_PAUSED)
941             {
942                 if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_PAUSED )
943                  {
944                     err = snd_pcm_pause(wwo->p_handle, 0);
945                     if ( err < 0 )
946                         ERR("pcm_pause failed: %s\n", snd_strerror(err));
947                  }
948                 wwo->state = WINE_WS_PLAYING;
949             }
950             SetEvent(ev);
951             break;
952         case WINE_WM_HEADER:
953             lpWaveHdr = (LPWAVEHDR)param;
954
955             /* insert buffer at the end of queue */
956             {
957                 LPWAVEHDR*      wh;
958                 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
959                 *wh = lpWaveHdr;
960             }
961             if (!wwo->lpPlayPtr)
962                 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
963             if (wwo->state == WINE_WS_STOPPED)
964                 wwo->state = WINE_WS_PLAYING;
965             break;
966         case WINE_WM_RESETTING:
967             wodPlayer_Reset(wwo);
968             SetEvent(ev);
969             break;
970         case WINE_WM_UPDATE:
971             wodUpdatePlayedTotal(wwo, NULL);
972             SetEvent(ev);
973             break;
974         case WINE_WM_BREAKLOOP:
975             if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
976                 /* ensure exit at end of current loop */
977                 wwo->dwLoops = 1;
978             }
979             SetEvent(ev);
980             break;
981         case WINE_WM_CLOSING:
982             /* sanity check: this should not happen since the device must have been reset before */
983             if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
984             wwo->hThread = 0;
985             wwo->state = WINE_WS_CLOSED;
986             SetEvent(ev);
987             ExitThread(0);
988             /* shouldn't go here */
989         default:
990             FIXME("unknown message %d\n", msg);
991             break;
992         }
993     }
994 }
995
996 /**************************************************************************
997  *                           wodPlayer_FeedDSP                  [internal]
998  * Feed as much sound data as we can into the DSP and return the number of
999  * milliseconds before it will be necessary to feed the DSP again.
1000  */
1001 static DWORD wodPlayer_FeedDSP(WINE_WAVEOUT* wwo)
1002 {
1003     DWORD               availInQ = snd_pcm_avail_update(wwo->p_handle);
1004
1005     /* no more room... no need to try to feed */
1006     while (wwo->lpPlayPtr && availInQ > 0)
1007         if ( wodPlayer_WriteMaxFrags(wwo, &availInQ) < 0 )
1008             break;
1009
1010     return wodPlayer_DSPWait(wwo);
1011 }
1012
1013 /**************************************************************************
1014  *                              wodPlayer                       [internal]
1015  */
1016 static  DWORD   CALLBACK        wodPlayer(LPVOID pmt)
1017 {
1018     WORD          uDevID = (DWORD)pmt;
1019     WINE_WAVEOUT* wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
1020     DWORD         dwNextFeedTime = INFINITE;   /* Time before DSP needs feeding */
1021     DWORD         dwNextNotifyTime = INFINITE; /* Time before next wave completion */
1022     DWORD         dwSleepTime;
1023
1024     wwo->state = WINE_WS_STOPPED;
1025     SetEvent(wwo->hStartUpEvent);
1026
1027     for (;;) {
1028         /** Wait for the shortest time before an action is required.  If there
1029          *  are no pending actions, wait forever for a command.
1030          */
1031         dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
1032         TRACE("waiting %lums (%lu,%lu)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
1033         WaitForSingleObject(wwo->msgRing.msg_event, dwSleepTime);
1034         wodPlayer_ProcessMessages(wwo);
1035         if (wwo->state == WINE_WS_PLAYING) {
1036             dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1037             dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1038         } else {
1039             dwNextFeedTime = dwNextNotifyTime = INFINITE;
1040         }
1041     }
1042 }
1043
1044 /**************************************************************************
1045  *                      wodGetDevCaps                           [internal]
1046  */
1047 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSA lpCaps, DWORD dwSize)
1048 {
1049     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1050
1051     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1052
1053     if (wDevID >= MAX_WAVEOUTDRV) {
1054         TRACE("MAX_WAVOUTDRV reached !\n");
1055         return MMSYSERR_BADDEVICEID;
1056     }
1057
1058     memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1059     return MMSYSERR_NOERROR;
1060 }
1061
1062 /**************************************************************************
1063  *                              wodOpen                         [internal]
1064  */
1065 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1066 {
1067     WINE_WAVEOUT*               wwo;
1068     snd_pcm_hw_params_t *       hw_params;
1069     snd_pcm_sw_params_t *       sw_params;
1070     snd_pcm_access_t            access;
1071     snd_pcm_format_t            format;
1072     int                         rate;
1073     unsigned int                buffer_time = 500000;
1074     unsigned int                period_time = 10000;
1075     int                         buffer_size;
1076     snd_pcm_uframes_t           period_size;
1077     int                         flags;
1078     snd_pcm_t *                 pcm;
1079     int                         err;
1080
1081     snd_pcm_hw_params_alloca(&hw_params);
1082     snd_pcm_sw_params_alloca(&sw_params);
1083
1084     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
1085     if (lpDesc == NULL) {
1086         WARN("Invalid Parameter !\n");
1087         return MMSYSERR_INVALPARAM;
1088     }
1089     if (wDevID >= MAX_WAVEOUTDRV) {
1090         TRACE("MAX_WAVOUTDRV reached !\n");
1091         return MMSYSERR_BADDEVICEID;
1092     }
1093
1094     /* only PCM format is supported so far... */
1095     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1096         lpDesc->lpFormat->nChannels == 0 ||
1097         lpDesc->lpFormat->nSamplesPerSec == 0) {
1098         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1099              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1100              lpDesc->lpFormat->nSamplesPerSec);
1101         return WAVERR_BADFORMAT;
1102     }
1103
1104     if (dwFlags & WAVE_FORMAT_QUERY) {
1105         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1106              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1107              lpDesc->lpFormat->nSamplesPerSec);
1108         return MMSYSERR_NOERROR;
1109     }
1110
1111     wwo = &WOutDev[wDevID];
1112
1113     if ((dwFlags & WAVE_DIRECTSOUND) && !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
1114         /* not supported, ignore it */
1115         dwFlags &= ~WAVE_DIRECTSOUND;
1116
1117     wwo->p_handle = 0;
1118     flags = SND_PCM_NONBLOCK;
1119     if ( dwFlags & WAVE_DIRECTSOUND )
1120         flags |= SND_PCM_ASYNC;
1121
1122     if (snd_pcm_open(&pcm, wwo->device, SND_PCM_STREAM_PLAYBACK, dwFlags))
1123     {
1124         ERR("Error open: %s\n", snd_strerror(errno));
1125         return MMSYSERR_NOTENABLED;
1126     }
1127
1128     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1129
1130     memcpy(&wwo->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
1131     memcpy(&wwo->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1132
1133     if (wwo->format.wBitsPerSample == 0) {
1134         WARN("Resetting zeroed wBitsPerSample\n");
1135         wwo->format.wBitsPerSample = 8 *
1136             (wwo->format.wf.nAvgBytesPerSec /
1137              wwo->format.wf.nSamplesPerSec) /
1138             wwo->format.wf.nChannels;
1139     }
1140
1141     snd_pcm_hw_params_any(pcm, hw_params);
1142
1143 #define EXIT_ON_ERROR(f,e,txt) do \
1144 { \
1145     int err; \
1146     if ( (err = (f) ) < 0) \
1147     { \
1148         ERR(txt ": %s\n", snd_strerror(err)); \
1149         snd_pcm_close(pcm); \
1150         return e; \
1151     } \
1152 } while(0)
1153
1154     access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
1155     if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
1156         WARN("mmap not available. switching to standard write.\n");
1157         access = SND_PCM_ACCESS_RW_INTERLEAVED;
1158         EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
1159         wwo->write = snd_pcm_writei;
1160     }
1161     else
1162         wwo->write = snd_pcm_mmap_writei;
1163
1164     EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwo->format.wf.nChannels), MMSYSERR_INVALPARAM, "unable to set required channels");
1165
1166     format = (wwo->format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE : SND_PCM_FORMAT_U8;
1167     EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), MMSYSERR_INVALPARAM, "unable to set required format");
1168
1169     rate = snd_pcm_hw_params_set_rate_near(pcm, hw_params, wwo->format.wf.nSamplesPerSec, 0);
1170     if (rate < 0) {
1171         ERR("Rate %ld Hz not available for playback: %s\n", wwo->format.wf.nSamplesPerSec, snd_strerror(rate));
1172         snd_pcm_close(pcm);
1173         return WAVERR_BADFORMAT;
1174     }
1175     if (rate != wwo->format.wf.nSamplesPerSec) {
1176         ERR("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwo->format.wf.nSamplesPerSec, rate);
1177         snd_pcm_close(pcm);
1178         return WAVERR_BADFORMAT;
1179     }
1180     
1181     EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, buffer_time, 0), MMSYSERR_INVALPARAM, "unable to set buffer time");
1182     EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, period_time, 0), MMSYSERR_INVALPARAM, "unable to set period time");
1183
1184     EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
1185     
1186     period_size = snd_pcm_hw_params_get_period_size(hw_params, 0);
1187     buffer_size = snd_pcm_hw_params_get_buffer_size(hw_params);
1188
1189     snd_pcm_sw_params_current(pcm, sw_params);
1190     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");
1191     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
1192     EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
1193     EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
1194     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
1195     EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
1196 #undef EXIT_ON_ERROR
1197
1198     snd_pcm_prepare(pcm);
1199
1200     if (TRACE_ON(wave))
1201         ALSA_TraceParameters(hw_params, sw_params, FALSE);
1202
1203     /* now, we can save all required data for later use... */
1204     if ( wwo->hw_params )
1205         snd_pcm_hw_params_free(wwo->hw_params);
1206     snd_pcm_hw_params_malloc(&(wwo->hw_params));
1207     snd_pcm_hw_params_copy(wwo->hw_params, hw_params);
1208
1209     wwo->dwBufferSize = buffer_size;
1210     wwo->lpQueuePtr = wwo->lpPlayPtr = wwo->lpLoopPtr = NULL;
1211     wwo->p_handle = pcm;
1212
1213     ALSA_InitRingMessage(&wwo->msgRing);
1214
1215     wwo->count = snd_pcm_poll_descriptors_count (wwo->p_handle);
1216     if (wwo->count <= 0) {
1217         ERR("Invalid poll descriptors count\n");
1218         return MMSYSERR_ERROR;
1219     }
1220
1221     wwo->ufds = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct pollfd) * wwo->count);
1222     if (wwo->ufds == NULL) {
1223         ERR("No enough memory\n");
1224         return MMSYSERR_NOMEM;
1225     }
1226     if ((err = snd_pcm_poll_descriptors(wwo->p_handle, wwo->ufds, wwo->count)) < 0) {
1227         ERR("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
1228         return MMSYSERR_ERROR;
1229     }
1230
1231     if (!(dwFlags & WAVE_DIRECTSOUND)) {
1232         wwo->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
1233         wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
1234         WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
1235         CloseHandle(wwo->hStartUpEvent);
1236     } else {
1237         wwo->hThread = INVALID_HANDLE_VALUE;
1238         wwo->dwThreadID = 0;
1239     }
1240     wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
1241
1242     TRACE("handle=%08lx \n", (DWORD)wwo->p_handle);
1243 /*    if (wwo->dwFragmentSize % wwo->format.wf.nBlockAlign)
1244         ERR("Fragment doesn't contain an integral number of data blocks\n");
1245 */
1246     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
1247           wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec,
1248           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
1249           wwo->format.wf.nBlockAlign);
1250
1251     return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
1252 }
1253
1254
1255 /**************************************************************************
1256  *                              wodClose                        [internal]
1257  */
1258 static DWORD wodClose(WORD wDevID)
1259 {
1260     DWORD               ret = MMSYSERR_NOERROR;
1261     WINE_WAVEOUT*       wwo;
1262
1263     TRACE("(%u);\n", wDevID);
1264
1265     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1266         WARN("bad device ID !\n");
1267         return MMSYSERR_BADDEVICEID;
1268     }
1269
1270     wwo = &WOutDev[wDevID];
1271     if (wwo->lpQueuePtr) {
1272         WARN("buffers still playing !\n");
1273         ret = WAVERR_STILLPLAYING;
1274     } else {
1275         if (wwo->hThread != INVALID_HANDLE_VALUE) {
1276             ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1277         }
1278         ALSA_DestroyRingMessage(&wwo->msgRing);
1279
1280         snd_pcm_hw_params_free(wwo->hw_params);
1281         wwo->hw_params = NULL;
1282
1283         snd_pcm_close(wwo->p_handle);
1284         wwo->p_handle = NULL;
1285
1286         ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1287     }
1288
1289     HeapFree(GetProcessHeap(), 0, wwo->ufds);
1290     return ret;
1291 }
1292
1293
1294 /**************************************************************************
1295  *                              wodWrite                        [internal]
1296  *
1297  */
1298 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1299 {
1300     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1301
1302     /* first, do the sanity checks... */
1303     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1304         WARN("bad dev ID !\n");
1305         return MMSYSERR_BADDEVICEID;
1306     }
1307
1308     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1309         return WAVERR_UNPREPARED;
1310
1311     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1312         return WAVERR_STILLPLAYING;
1313
1314     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1315     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1316     lpWaveHdr->lpNext = 0;
1317
1318     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1319
1320     return MMSYSERR_NOERROR;
1321 }
1322
1323 /**************************************************************************
1324  *                              wodPrepare                      [internal]
1325  */
1326 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1327 {
1328     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1329
1330     if (wDevID >= MAX_WAVEOUTDRV) {
1331         WARN("bad device ID !\n");
1332         return MMSYSERR_BADDEVICEID;
1333     }
1334
1335     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1336         return WAVERR_STILLPLAYING;
1337
1338     lpWaveHdr->dwFlags |= WHDR_PREPARED;
1339     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1340     return MMSYSERR_NOERROR;
1341 }
1342
1343 /**************************************************************************
1344  *                              wodUnprepare                    [internal]
1345  */
1346 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1347 {
1348     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1349
1350     if (wDevID >= MAX_WAVEOUTDRV) {
1351         WARN("bad device ID !\n");
1352         return MMSYSERR_BADDEVICEID;
1353     }
1354
1355     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1356         return WAVERR_STILLPLAYING;
1357
1358     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1359     lpWaveHdr->dwFlags |= WHDR_DONE;
1360
1361     return MMSYSERR_NOERROR;
1362 }
1363
1364 /**************************************************************************
1365  *                      wodPause                                [internal]
1366  */
1367 static DWORD wodPause(WORD wDevID)
1368 {
1369     TRACE("(%u);!\n", wDevID);
1370
1371     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1372         WARN("bad device ID !\n");
1373         return MMSYSERR_BADDEVICEID;
1374     }
1375
1376     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1377
1378     return MMSYSERR_NOERROR;
1379 }
1380
1381 /**************************************************************************
1382  *                      wodRestart                              [internal]
1383  */
1384 static DWORD wodRestart(WORD wDevID)
1385 {
1386     TRACE("(%u);\n", wDevID);
1387
1388     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1389         WARN("bad device ID !\n");
1390         return MMSYSERR_BADDEVICEID;
1391     }
1392
1393     if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1394         ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1395     }
1396
1397     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1398     /* FIXME: Myst crashes with this ... hmm -MM
1399        return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1400     */
1401
1402     return MMSYSERR_NOERROR;
1403 }
1404
1405 /**************************************************************************
1406  *                      wodReset                                [internal]
1407  */
1408 static DWORD wodReset(WORD wDevID)
1409 {
1410     TRACE("(%u);\n", wDevID);
1411
1412     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1413         WARN("bad device ID !\n");
1414         return MMSYSERR_BADDEVICEID;
1415     }
1416
1417     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1418
1419     return MMSYSERR_NOERROR;
1420 }
1421
1422 /**************************************************************************
1423  *                              wodGetPosition                  [internal]
1424  */
1425 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1426 {
1427     int                 time;
1428     DWORD               val;
1429     WINE_WAVEOUT*       wwo;
1430
1431     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1432
1433     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1434         WARN("bad device ID !\n");
1435         return MMSYSERR_BADDEVICEID;
1436     }
1437
1438     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1439
1440     wwo = &WOutDev[wDevID];
1441     ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1442     val = wwo->dwPlayedTotal;
1443
1444     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
1445           lpTime->wType, wwo->format.wBitsPerSample,
1446           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
1447           wwo->format.wf.nAvgBytesPerSec);
1448     TRACE("dwPlayedTotal=%lu\n", val);
1449
1450     switch (lpTime->wType) {
1451     case TIME_BYTES:
1452         lpTime->u.cb = val;
1453         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
1454         break;
1455     case TIME_SAMPLES:
1456         lpTime->u.sample = val * 8 / wwo->format.wBitsPerSample /wwo->format.wf.nChannels;
1457         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
1458         break;
1459     case TIME_SMPTE:
1460         time = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1461         lpTime->u.smpte.hour = time / 108000;
1462         time -= lpTime->u.smpte.hour * 108000;
1463         lpTime->u.smpte.min = time / 1800;
1464         time -= lpTime->u.smpte.min * 1800;
1465         lpTime->u.smpte.sec = time / 30;
1466         time -= lpTime->u.smpte.sec * 30;
1467         lpTime->u.smpte.frame = time;
1468         lpTime->u.smpte.fps = 30;
1469         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
1470               lpTime->u.smpte.hour, lpTime->u.smpte.min,
1471               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
1472         break;
1473     default:
1474         FIXME("Format %d not supported ! use TIME_MS !\n", lpTime->wType);
1475         lpTime->wType = TIME_MS;
1476     case TIME_MS:
1477         lpTime->u.ms = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1478         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
1479         break;
1480     }
1481     return MMSYSERR_NOERROR;
1482 }
1483
1484 /**************************************************************************
1485  *                              wodBreakLoop                    [internal]
1486  */
1487 static DWORD wodBreakLoop(WORD wDevID)
1488 {
1489     TRACE("(%u);\n", wDevID);
1490
1491     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1492         WARN("bad device ID !\n");
1493         return MMSYSERR_BADDEVICEID;
1494     }
1495     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
1496     return MMSYSERR_NOERROR;
1497 }
1498
1499 /**************************************************************************
1500  *                              wodGetVolume                    [internal]
1501  */
1502 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1503 {
1504     WORD               left, right;
1505     WINE_WAVEOUT*      wwo;
1506     int                count;
1507     long               min, max;
1508
1509     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1510     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1511         WARN("bad device ID !\n");
1512         return MMSYSERR_BADDEVICEID;
1513     }
1514     wwo = &WOutDev[wDevID];
1515     count = snd_ctl_elem_info_get_count(wwo->playback_einfo);
1516     min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
1517     max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
1518
1519 #define VOLUME_ALSA_TO_WIN(x) (((x)-min) * 65536 /(max-min))
1520     if (lpdwVol == NULL)
1521         return MMSYSERR_NOTENABLED;
1522
1523     switch (count)
1524     {
1525         case 2:
1526             left = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
1527             right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 1));
1528             break;
1529         case 1:
1530             left = right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
1531             break;
1532         default:
1533             WARN("%d channels mixer not supported\n", count);
1534             return MMSYSERR_NOERROR;
1535      }
1536 #undef VOLUME_ALSA_TO_WIN
1537
1538     TRACE("left=%d right=%d !\n", left, right);
1539     *lpdwVol = MAKELONG( left, right );
1540     return MMSYSERR_NOERROR;
1541 }
1542
1543 /**************************************************************************
1544  *                              wodSetVolume                    [internal]
1545  */
1546 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1547 {
1548     WORD               left, right;
1549     WINE_WAVEOUT*      wwo;
1550     int                count, err;
1551     long               min, max;
1552
1553     TRACE("(%u, %08lX);\n", wDevID, dwParam);
1554     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1555         WARN("bad device ID !\n");
1556         return MMSYSERR_BADDEVICEID;
1557     }
1558     wwo = &WOutDev[wDevID];
1559     count=snd_ctl_elem_info_get_count(wwo->playback_einfo);
1560     min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
1561     max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
1562
1563     left  = LOWORD(dwParam);
1564     right = HIWORD(dwParam);
1565
1566 #define VOLUME_WIN_TO_ALSA(x) ( (((x) * (max-min)) / 65536) + min )
1567     switch (count)
1568     {
1569         case 2:
1570             snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
1571             snd_ctl_elem_value_set_integer(wwo->playback_evalue, 1, VOLUME_WIN_TO_ALSA(right));
1572             break;
1573         case 1:
1574             snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
1575             break;
1576         default:
1577             WARN("%d channels mixer not supported\n", count);
1578      }
1579 #undef VOLUME_WIN_TO_ALSA
1580     if ( (err = snd_ctl_elem_write(wwo->ctl, wwo->playback_evalue)) < 0)
1581     {
1582         ERR("error writing snd_ctl_elem_value: %s\n", snd_strerror(err));
1583     }
1584     return MMSYSERR_NOERROR;
1585 }
1586
1587 /**************************************************************************
1588  *                              wodGetNumDevs                   [internal]
1589  */
1590 static  DWORD   wodGetNumDevs(void)
1591 {
1592     return ALSA_WodNumDevs;
1593 }
1594
1595
1596 /**************************************************************************
1597  *                              wodMessage (WINEALSA.@)
1598  */
1599 DWORD WINAPI ALSA_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1600                              DWORD dwParam1, DWORD dwParam2)
1601 {
1602     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
1603           wDevID, wMsg, dwUser, dwParam1, dwParam2);
1604
1605     switch (wMsg) {
1606     case DRVM_INIT:
1607     case DRVM_EXIT:
1608     case DRVM_ENABLE:
1609     case DRVM_DISABLE:
1610         /* FIXME: Pretend this is supported */
1611         return 0;
1612     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1613     case WODM_CLOSE:            return wodClose         (wDevID);
1614     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSA)dwParam1,      dwParam2);
1615     case WODM_GETNUMDEVS:       return wodGetNumDevs    ();
1616     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1617     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1618     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1619     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1620     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1621     case WODM_PAUSE:            return wodPause         (wDevID);
1622     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
1623     case WODM_BREAKLOOP:        return wodBreakLoop     (wDevID);
1624     case WODM_PREPARE:          return wodPrepare       (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1625     case WODM_UNPREPARE:        return wodUnprepare     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1626     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
1627     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
1628     case WODM_RESTART:          return wodRestart       (wDevID);
1629     case WODM_RESET:            return wodReset         (wDevID);
1630     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate      (wDevID, (PIDSDRIVER*)dwParam1);
1631     case DRV_QUERYDSOUNDDESC:   return wodDsDesc        (wDevID, (PDSDRIVERDESC)dwParam1);
1632     case DRV_QUERYDSOUNDGUID:   return wodDsGuid        (wDevID, (LPGUID)dwParam1);
1633
1634     default:
1635         FIXME("unknown message %d!\n", wMsg);
1636     }
1637     return MMSYSERR_NOTSUPPORTED;
1638 }
1639
1640 /*======================================================================*
1641  *                  Low level DSOUND implementation                     *
1642  *======================================================================*/
1643
1644 typedef struct IDsDriverImpl IDsDriverImpl;
1645 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1646
1647 struct IDsDriverImpl
1648 {
1649     /* IUnknown fields */
1650     ICOM_VFIELD(IDsDriver);
1651     DWORD               ref;
1652     /* IDsDriverImpl fields */
1653     UINT                wDevID;
1654     IDsDriverBufferImpl*primary;
1655 };
1656
1657 struct IDsDriverBufferImpl
1658 {
1659     /* IUnknown fields */
1660     ICOM_VFIELD(IDsDriverBuffer);
1661     DWORD                     ref;
1662     /* IDsDriverBufferImpl fields */
1663     IDsDriverImpl*            drv;
1664
1665     CRITICAL_SECTION          mmap_crst;
1666     LPVOID                    mmap_buffer;
1667     DWORD                     mmap_buflen_bytes;
1668     snd_pcm_uframes_t         mmap_buflen_frames;
1669     snd_pcm_channel_area_t *  mmap_areas;
1670     snd_async_handler_t *     mmap_async_handler;
1671 };
1672
1673 static void DSDB_CheckXRUN(IDsDriverBufferImpl* pdbi)
1674 {
1675     WINE_WAVEOUT *     wwo = &(WOutDev[pdbi->drv->wDevID]);
1676     snd_pcm_state_t    state = snd_pcm_state(wwo->p_handle);
1677
1678     if ( state == SND_PCM_STATE_XRUN )
1679     {
1680         int            err = snd_pcm_prepare(wwo->p_handle);
1681         TRACE("xrun occurred\n");
1682         if ( err < 0 )
1683             ERR("recovery from xrun failed, prepare failed: %s\n", snd_strerror(err));
1684     }
1685     else if ( state == SND_PCM_STATE_SUSPENDED )
1686     {
1687         int            err = snd_pcm_resume(wwo->p_handle);
1688         TRACE("recovery from suspension occurred\n");
1689         if (err < 0 && err != -EAGAIN){
1690             err = snd_pcm_prepare(wwo->p_handle);
1691             if (err < 0)
1692                 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
1693         }
1694     }
1695 }
1696
1697 static void DSDB_MMAPCopy(IDsDriverBufferImpl* pdbi)
1698 {
1699     WINE_WAVEOUT *     wwo = &(WOutDev[pdbi->drv->wDevID]);
1700     int                channels;
1701     snd_pcm_format_t   format;
1702     snd_pcm_uframes_t  period_size;
1703     snd_pcm_sframes_t  avail;
1704
1705     if ( !pdbi->mmap_buffer || !wwo->hw_params || !wwo->p_handle)
1706         return;
1707
1708     channels = snd_pcm_hw_params_get_channels(wwo->hw_params);
1709     format = snd_pcm_hw_params_get_format(wwo->hw_params);
1710     period_size = snd_pcm_hw_params_get_period_size(wwo->hw_params, 0);
1711     avail = snd_pcm_avail_update(wwo->p_handle);
1712
1713     DSDB_CheckXRUN(pdbi);
1714
1715     TRACE("avail=%d format=%s channels=%d\n", (int)avail, snd_pcm_format_name(format), channels );
1716
1717     while (avail >= period_size)
1718     {
1719         const snd_pcm_channel_area_t *areas;
1720         snd_pcm_uframes_t     ofs;
1721         snd_pcm_uframes_t     frames;
1722         int                   err;
1723
1724         frames = avail / period_size * period_size; /* round down to a multiple of period_size */
1725
1726         EnterCriticalSection(&pdbi->mmap_crst);
1727
1728         snd_pcm_mmap_begin(wwo->p_handle, &areas, &ofs, &frames);
1729         snd_pcm_areas_copy(areas, ofs, pdbi->mmap_areas, ofs, channels, frames, format);
1730         err = snd_pcm_mmap_commit(wwo->p_handle, ofs, frames);
1731
1732         LeaveCriticalSection(&pdbi->mmap_crst);
1733
1734         if ( err != (snd_pcm_sframes_t) frames)
1735             ERR("mmap partially failed.\n");
1736
1737         avail = snd_pcm_avail_update(wwo->p_handle);
1738     }
1739  }
1740
1741 static void DSDB_PCMCallback(snd_async_handler_t *ahandler)
1742 {
1743     /* snd_pcm_t *               handle = snd_async_handler_get_pcm(ahandler); */
1744     IDsDriverBufferImpl*      pdbi = snd_async_handler_get_callback_private(ahandler);
1745     TRACE("callback called\n");
1746     DSDB_MMAPCopy(pdbi);
1747 }
1748
1749 static int DSDB_CreateMMAP(IDsDriverBufferImpl* pdbi)
1750  {
1751     WINE_WAVEOUT *            wwo = &(WOutDev[pdbi->drv->wDevID]);
1752     snd_pcm_format_t          format = snd_pcm_hw_params_get_format(wwo->hw_params);
1753     snd_pcm_uframes_t         frames = snd_pcm_hw_params_get_buffer_size(wwo->hw_params);
1754     int                       channels = snd_pcm_hw_params_get_channels(wwo->hw_params);
1755     unsigned int              bits_per_sample = snd_pcm_format_physical_width(format);
1756     unsigned int              bits_per_frame = bits_per_sample * channels;
1757     snd_pcm_channel_area_t *  a;
1758     unsigned int              c;
1759     int                       err;
1760
1761     if (TRACE_ON(wave))
1762         ALSA_TraceParameters(wwo->hw_params, NULL, FALSE);
1763
1764     TRACE("format=%s  frames=%ld  channels=%d  bits_per_sample=%d  bits_per_frame=%d\n",
1765           snd_pcm_format_name(format), frames, channels, bits_per_sample, bits_per_frame);
1766
1767     pdbi->mmap_buflen_frames = frames;
1768     pdbi->mmap_buflen_bytes = snd_pcm_frames_to_bytes( wwo->p_handle, frames );
1769     pdbi->mmap_buffer = HeapAlloc(GetProcessHeap(),0,pdbi->mmap_buflen_bytes);
1770     if (!pdbi->mmap_buffer)
1771         return DSERR_OUTOFMEMORY;
1772
1773     snd_pcm_format_set_silence(format, pdbi->mmap_buffer, frames );
1774
1775     TRACE("created mmap buffer of %ld frames (%ld bytes) at %p\n",
1776         frames, pdbi->mmap_buflen_bytes, pdbi->mmap_buffer);
1777
1778     pdbi->mmap_areas = HeapAlloc(GetProcessHeap(),0,channels*sizeof(snd_pcm_channel_area_t));
1779     if (!pdbi->mmap_areas)
1780         return DSERR_OUTOFMEMORY;
1781
1782     a = pdbi->mmap_areas;
1783     for (c = 0; c < channels; c++, a++)
1784     {
1785         a->addr = pdbi->mmap_buffer;
1786         a->first = bits_per_sample * c;
1787         a->step = bits_per_frame;
1788         TRACE("Area %d: addr=%p  first=%d  step=%d\n", c, a->addr, a->first, a->step);
1789     }
1790
1791     InitializeCriticalSection(&pdbi->mmap_crst);
1792
1793     err = snd_async_add_pcm_handler(&pdbi->mmap_async_handler, wwo->p_handle, DSDB_PCMCallback, pdbi);
1794     if ( err < 0 )
1795      {
1796         ERR("add_pcm_handler failed. reason: %s\n", snd_strerror(err));
1797         return DSERR_GENERIC;
1798      }
1799
1800     return DS_OK;
1801  }
1802
1803 static void DSDB_DestroyMMAP(IDsDriverBufferImpl* pdbi)
1804 {
1805     TRACE("mmap buffer %p destroyed\n", pdbi->mmap_buffer);
1806     HeapFree(GetProcessHeap(), 0, pdbi->mmap_areas);
1807     HeapFree(GetProcessHeap(), 0, pdbi->mmap_buffer);
1808     pdbi->mmap_areas = NULL;
1809     pdbi->mmap_buffer = NULL;
1810     DeleteCriticalSection(&pdbi->mmap_crst);
1811 }
1812
1813
1814 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
1815 {
1816     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1817     FIXME("(): stub!\n");
1818     return DSERR_UNSUPPORTED;
1819 }
1820
1821 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
1822 {
1823     ICOM_THIS(IDsDriverBufferImpl,iface);
1824     TRACE("(%p)\n",iface);
1825     return ++This->ref;
1826 }
1827
1828 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
1829 {
1830     ICOM_THIS(IDsDriverBufferImpl,iface);
1831     TRACE("(%p)\n",iface);
1832     if (--This->ref)
1833         return This->ref;
1834     if (This == This->drv->primary)
1835         This->drv->primary = NULL;
1836     DSDB_DestroyMMAP(This);
1837     HeapFree(GetProcessHeap(), 0, This);
1838     return 0;
1839 }
1840
1841 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
1842                                                LPVOID*ppvAudio1,LPDWORD pdwLen1,
1843                                                LPVOID*ppvAudio2,LPDWORD pdwLen2,
1844                                                DWORD dwWritePosition,DWORD dwWriteLen,
1845                                                DWORD dwFlags)
1846 {
1847     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1848     TRACE("(%p)\n",iface);
1849     return DSERR_UNSUPPORTED;
1850 }
1851
1852 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
1853                                                  LPVOID pvAudio1,DWORD dwLen1,
1854                                                  LPVOID pvAudio2,DWORD dwLen2)
1855 {
1856     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1857     TRACE("(%p)\n",iface);
1858     return DSERR_UNSUPPORTED;
1859 }
1860
1861 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
1862                                                     LPWAVEFORMATEX pwfx)
1863 {
1864     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1865     TRACE("(%p,%p)\n",iface,pwfx);
1866     return DSERR_BUFFERLOST;
1867 }
1868
1869 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
1870 {
1871     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1872     TRACE("(%p,%ld): stub\n",iface,dwFreq);
1873     return DSERR_UNSUPPORTED;
1874 }
1875
1876 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
1877 {
1878     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1879     FIXME("(%p,%p): stub!\n",iface,pVolPan);
1880     return DS_OK;
1881 }
1882
1883 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
1884 {
1885     /* ICOM_THIS(IDsDriverImpl,iface); */
1886     TRACE("(%p,%ld): stub\n",iface,dwNewPos);
1887     return DSERR_UNSUPPORTED;
1888 }
1889
1890 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
1891                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
1892 {
1893     ICOM_THIS(IDsDriverBufferImpl,iface);
1894     WINE_WAVEOUT *      wwo = &(WOutDev[This->drv->wDevID]);
1895     snd_pcm_uframes_t   hw_ptr;
1896     snd_pcm_uframes_t   period_size;
1897
1898     if (wwo->hw_params == NULL) return DSERR_GENERIC;
1899
1900     period_size  = snd_pcm_hw_params_get_period_size(wwo->hw_params, 0);
1901
1902     if (wwo->p_handle == NULL) return DSERR_GENERIC;
1903     /** we need to track down buffer underruns */
1904     DSDB_CheckXRUN(This);
1905
1906     EnterCriticalSection(&This->mmap_crst);
1907     hw_ptr = _snd_pcm_mmap_hw_ptr(wwo->p_handle);
1908     if (lpdwPlay)
1909         *lpdwPlay = snd_pcm_frames_to_bytes(wwo->p_handle, hw_ptr/ period_size  * period_size) % This->mmap_buflen_bytes;
1910     if (lpdwWrite)
1911         *lpdwWrite = snd_pcm_frames_to_bytes(wwo->p_handle, (hw_ptr / period_size + 1) * period_size ) % This->mmap_buflen_bytes;
1912     LeaveCriticalSection(&This->mmap_crst);
1913
1914     TRACE("hw_ptr=0x%08x, playpos=%ld, writepos=%ld\n", (unsigned int)hw_ptr, lpdwPlay?*lpdwPlay:-1, lpdwWrite?*lpdwWrite:-1);
1915     return DS_OK;
1916 }
1917
1918 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
1919 {
1920     ICOM_THIS(IDsDriverBufferImpl,iface);
1921     WINE_WAVEOUT *       wwo = &(WOutDev[This->drv->wDevID]);
1922     snd_pcm_state_t      state;
1923     int                  err;
1924
1925     TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
1926
1927     if (wwo->p_handle == NULL) return DSERR_GENERIC;
1928
1929     state = snd_pcm_state(wwo->p_handle);
1930     if ( state == SND_PCM_STATE_SETUP )
1931     {
1932         err = snd_pcm_prepare(wwo->p_handle);
1933         state = snd_pcm_state(wwo->p_handle);
1934     }
1935     if ( state == SND_PCM_STATE_PREPARED )
1936      {
1937         DSDB_MMAPCopy(This);
1938         err = snd_pcm_start(wwo->p_handle);
1939      }
1940     return DS_OK;
1941 }
1942
1943 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
1944 {
1945     ICOM_THIS(IDsDriverBufferImpl,iface);
1946     WINE_WAVEOUT *    wwo = &(WOutDev[This->drv->wDevID]);
1947     int               err;
1948     DWORD             play;
1949     DWORD             write;
1950
1951     TRACE("(%p)\n",iface);
1952
1953     if (wwo->p_handle == NULL) return DSERR_GENERIC;
1954
1955     /* ring buffer wrap up detection */
1956     IDsDriverBufferImpl_GetPosition(iface, &play, &write);
1957     if ( play > write)
1958     {
1959         TRACE("writepos wrapper up\n");
1960         return DS_OK;
1961     }
1962
1963     if ( ( err = snd_pcm_drop(wwo->p_handle)) < 0 )
1964     {
1965         ERR("error while stopping pcm: %s\n", snd_strerror(err));
1966         return DSERR_GENERIC;
1967     }
1968     return DS_OK;
1969 }
1970
1971 static ICOM_VTABLE(IDsDriverBuffer) dsdbvt =
1972 {
1973     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1974     IDsDriverBufferImpl_QueryInterface,
1975     IDsDriverBufferImpl_AddRef,
1976     IDsDriverBufferImpl_Release,
1977     IDsDriverBufferImpl_Lock,
1978     IDsDriverBufferImpl_Unlock,
1979     IDsDriverBufferImpl_SetFormat,
1980     IDsDriverBufferImpl_SetFrequency,
1981     IDsDriverBufferImpl_SetVolumePan,
1982     IDsDriverBufferImpl_SetPosition,
1983     IDsDriverBufferImpl_GetPosition,
1984     IDsDriverBufferImpl_Play,
1985     IDsDriverBufferImpl_Stop
1986 };
1987
1988 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
1989 {
1990     /* ICOM_THIS(IDsDriverImpl,iface); */
1991     FIXME("(%p): stub!\n",iface);
1992     return DSERR_UNSUPPORTED;
1993 }
1994
1995 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
1996 {
1997     ICOM_THIS(IDsDriverImpl,iface);
1998     TRACE("(%p)\n",iface);
1999     This->ref++;
2000     return This->ref;
2001 }
2002
2003 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
2004 {
2005     ICOM_THIS(IDsDriverImpl,iface);
2006     TRACE("(%p)\n",iface);
2007     if (--This->ref)
2008         return This->ref;
2009     HeapFree(GetProcessHeap(),0,This);
2010     return 0;
2011 }
2012
2013 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
2014 {
2015     ICOM_THIS(IDsDriverImpl,iface);
2016     TRACE("(%p,%p)\n",iface,pDesc);
2017     memcpy(pDesc, &(WOutDev[This->wDevID].ds_desc), sizeof(DSDRIVERDESC));
2018     pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
2019         DSDDESC_USESYSTEMMEMORY;
2020     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
2021     pDesc->wVxdId               = 0;
2022     pDesc->wReserved            = 0;
2023     pDesc->ulDeviceNum          = This->wDevID;
2024     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
2025     pDesc->pvDirectDrawHeap     = NULL;
2026     pDesc->dwMemStartAddress    = 0;
2027     pDesc->dwMemEndAddress      = 0;
2028     pDesc->dwMemAllocExtra      = 0;
2029     pDesc->pvReserved1          = NULL;
2030     pDesc->pvReserved2          = NULL;
2031     return DS_OK;
2032 }
2033
2034 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
2035 {
2036     /* ICOM_THIS(IDsDriverImpl,iface); */
2037     TRACE("(%p)\n",iface);
2038     return DS_OK;
2039 }
2040
2041 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
2042 {
2043     /* ICOM_THIS(IDsDriverImpl,iface); */
2044     TRACE("(%p)\n",iface);
2045     return DS_OK;
2046 }
2047
2048 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
2049 {
2050     ICOM_THIS(IDsDriverImpl,iface);
2051     TRACE("(%p,%p)\n",iface,pCaps);
2052     memset(pCaps, 0, sizeof(*pCaps));
2053
2054     pCaps->dwFlags = DSCAPS_PRIMARYMONO;
2055     if ( WOutDev[This->wDevID].caps.wChannels == 2 )
2056         pCaps->dwFlags |= DSCAPS_PRIMARYSTEREO;
2057
2058     if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 ) )
2059         pCaps->dwFlags |= DSCAPS_PRIMARY8BIT;
2060
2061     if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S16 | WAVE_FORMAT_2S16 | WAVE_FORMAT_4S16))
2062         pCaps->dwFlags |= DSCAPS_PRIMARY16BIT;
2063
2064     pCaps->dwPrimaryBuffers = 1;
2065     TRACE("caps=0x%X\n",(unsigned int)pCaps->dwFlags);
2066     pCaps->dwMinSecondarySampleRate = DSBFREQUENCY_MIN;
2067     pCaps->dwMaxSecondarySampleRate = DSBFREQUENCY_MAX;
2068
2069     /* the other fields only apply to secondary buffers, which we don't support
2070      * (unless we want to mess with wavetable synthesizers and MIDI) */
2071     return DS_OK;
2072 }
2073
2074 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
2075                                                       LPWAVEFORMATEX pwfx,
2076                                                       DWORD dwFlags, DWORD dwCardAddress,
2077                                                       LPDWORD pdwcbBufferSize,
2078                                                       LPBYTE *ppbBuffer,
2079                                                       LPVOID *ppvObj)
2080 {
2081     ICOM_THIS(IDsDriverImpl,iface);
2082     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
2083     int err;
2084
2085     TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
2086     /* we only support primary buffers */
2087     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
2088         return DSERR_UNSUPPORTED;
2089     if (This->primary)
2090         return DSERR_ALLOCATED;
2091     if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
2092         return DSERR_CONTROLUNAVAIL;
2093
2094     *ippdsdb = (IDsDriverBufferImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
2095     if (*ippdsdb == NULL)
2096         return DSERR_OUTOFMEMORY;
2097     (*ippdsdb)->lpVtbl  = &dsdbvt;
2098     (*ippdsdb)->ref     = 1;
2099     (*ippdsdb)->drv     = This;
2100
2101     err = DSDB_CreateMMAP((*ippdsdb));
2102     if ( err != DS_OK )
2103      {
2104         HeapFree(GetProcessHeap(), 0, *ippdsdb);
2105         *ippdsdb = NULL;
2106         return err;
2107      }
2108     *ppbBuffer = (*ippdsdb)->mmap_buffer;
2109     *pdwcbBufferSize = (*ippdsdb)->mmap_buflen_bytes;
2110
2111     This->primary = *ippdsdb;
2112
2113     /* buffer is ready to go */
2114     TRACE("buffer created at %p\n", *ippdsdb);
2115     return DS_OK;
2116 }
2117
2118 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
2119                                                          PIDSDRIVERBUFFER pBuffer,
2120                                                          LPVOID *ppvObj)
2121 {
2122     /* ICOM_THIS(IDsDriverImpl,iface); */
2123     TRACE("(%p,%p): stub\n",iface,pBuffer);
2124     return DSERR_INVALIDCALL;
2125 }
2126
2127 static ICOM_VTABLE(IDsDriver) dsdvt =
2128 {
2129     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
2130     IDsDriverImpl_QueryInterface,
2131     IDsDriverImpl_AddRef,
2132     IDsDriverImpl_Release,
2133     IDsDriverImpl_GetDriverDesc,
2134     IDsDriverImpl_Open,
2135     IDsDriverImpl_Close,
2136     IDsDriverImpl_GetCaps,
2137     IDsDriverImpl_CreateSoundBuffer,
2138     IDsDriverImpl_DuplicateSoundBuffer
2139 };
2140
2141 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
2142 {
2143     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
2144
2145     TRACE("driver created\n");
2146
2147     /* the HAL isn't much better than the HEL if we can't do mmap() */
2148     if (!(WOutDev[wDevID].caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
2149         ERR("DirectSound flag not set\n");
2150         MESSAGE("This sound card's driver does not support direct access\n");
2151         MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
2152         return MMSYSERR_NOTSUPPORTED;
2153     }
2154
2155     *idrv = (IDsDriverImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
2156     if (!*idrv)
2157         return MMSYSERR_NOMEM;
2158     (*idrv)->lpVtbl     = &dsdvt;
2159     (*idrv)->ref        = 1;
2160
2161     (*idrv)->wDevID     = wDevID;
2162     (*idrv)->primary    = NULL;
2163     return MMSYSERR_NOERROR;
2164 }
2165
2166 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2167 {
2168     memcpy(desc, &(WOutDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
2169     return MMSYSERR_NOERROR;
2170 }
2171
2172 static DWORD wodDsGuid(UINT wDevID, LPGUID pGuid)
2173 {
2174     TRACE("(%d,%p)\n",wDevID,pGuid);
2175
2176     memcpy(pGuid, &(WOutDev[wDevID].ds_guid), sizeof(GUID));
2177
2178     return MMSYSERR_NOERROR;
2179 }
2180
2181 #endif
2182
2183 #ifndef HAVE_ALSA
2184
2185 /**************************************************************************
2186  *                              wodMessage (WINEALSA.@)
2187  */
2188 DWORD WINAPI ALSA_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2189                              DWORD dwParam1, DWORD dwParam2)
2190 {
2191     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2192     return MMSYSERR_NOTENABLED;
2193 }
2194
2195 #endif /* HAVE_ALSA */