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