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