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