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