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