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