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