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