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