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