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