Make sure the 'alsa handle' is initialized to NULL before calling
[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 "dsound.h"
56 #include "dsdriver.h"
57 #define ALSA_PCM_OLD_HW_PARAMS_API
58 #define ALSA_PCM_OLD_SW_PARAMS_API
59 #include "alsa.h"
60 #include "wine/library.h"
61 #include "wine/debug.h"
62
63 WINE_DEFAULT_DEBUG_CHANNEL(wave);
64
65
66 #if defined(HAVE_ALSA) && ((SND_LIB_MAJOR == 0 && SND_LIB_MINOR >= 9) || SND_LIB_MAJOR >= 1)
67
68 /* internal ALSALIB functions */
69 snd_pcm_uframes_t _snd_pcm_mmap_hw_ptr(snd_pcm_t *pcm);
70
71
72 #define MAX_WAVEOUTDRV  (1)
73 #define MAX_WAVEINDRV   (1)
74
75 /* state diagram for waveOut writing:
76  *
77  * +---------+-------------+---------------+---------------------------------+
78  * |  state  |  function   |     event     |            new state            |
79  * +---------+-------------+---------------+---------------------------------+
80  * |         | open()      |               | STOPPED                         |
81  * | PAUSED  | write()     |               | PAUSED                          |
82  * | STOPPED | write()     | <thrd create> | PLAYING                         |
83  * | PLAYING | write()     | HEADER        | PLAYING                         |
84  * | (other) | write()     | <error>       |                                 |
85  * | (any)   | pause()     | PAUSING       | PAUSED                          |
86  * | PAUSED  | restart()   | RESTARTING    | PLAYING (if no thrd => STOPPED) |
87  * | (any)   | reset()     | RESETTING     | STOPPED                         |
88  * | (any)   | close()     | CLOSING       | CLOSED                          |
89  * +---------+-------------+---------------+---------------------------------+
90  */
91
92 /* states of the playing device */
93 #define WINE_WS_PLAYING         0
94 #define WINE_WS_PAUSED          1
95 #define WINE_WS_STOPPED         2
96 #define WINE_WS_CLOSED          3
97
98 /* events to be send to device */
99 enum win_wm_message {
100     WINE_WM_PAUSING = WM_USER + 1, WINE_WM_RESTARTING, WINE_WM_RESETTING, WINE_WM_HEADER,
101     WINE_WM_UPDATE, WINE_WM_BREAKLOOP, WINE_WM_CLOSING, WINE_WM_STARTING, WINE_WM_STOPPING
102 };
103
104 #ifdef USE_PIPE_SYNC
105 #define SIGNAL_OMR(omr) do { int x = 0; write((omr)->msg_pipe[1], &x, sizeof(x)); } while (0)
106 #define CLEAR_OMR(omr) do { int x = 0; read((omr)->msg_pipe[0], &x, sizeof(x)); } while (0)
107 #define RESET_OMR(omr) do { } while (0)
108 #define WAIT_OMR(omr, sleep) \
109   do { struct pollfd pfd; pfd.fd = (omr)->msg_pipe[0]; \
110        pfd.events = POLLIN; poll(&pfd, 1, sleep); } while (0)
111 #else
112 #define SIGNAL_OMR(omr) do { SetEvent((omr)->msg_event); } while (0)
113 #define CLEAR_OMR(omr) do { } while (0)
114 #define RESET_OMR(omr) do { ResetEvent((omr)->msg_event); } while (0)
115 #define WAIT_OMR(omr, sleep) \
116   do { WaitForSingleObject((omr)->msg_event, sleep); } while (0)
117 #endif
118
119 typedef struct {
120     enum win_wm_message         msg;    /* message identifier */
121     DWORD                       param;  /* parameter for this message */
122     HANDLE                      hEvent; /* if message is synchronous, handle of event for synchro */
123 } ALSA_MSG;
124
125 /* implement an in-process message ring for better performance
126  * (compared to passing thru the server)
127  * this ring will be used by the input (resp output) record (resp playback) routine
128  */
129 #define ALSA_RING_BUFFER_INCREMENT      64
130 typedef struct {
131     ALSA_MSG                    * messages;
132     int                         ring_buffer_size;
133     int                         msg_tosave;
134     int                         msg_toget;
135 #ifdef USE_PIPE_SYNC
136     int                         msg_pipe[2];
137 #else
138     HANDLE                      msg_event;
139 #endif
140     CRITICAL_SECTION            msg_crst;
141 } ALSA_MSG_RING;
142
143 typedef struct {
144     /* Windows information */
145     volatile int                state;                  /* one of the WINE_WS_ manifest constants */
146     WAVEOPENDESC                waveDesc;
147     WORD                        wFlags;
148     PCMWAVEFORMAT               format;
149     WAVEOUTCAPSA                caps;
150
151     /* ALSA information (ALSA 0.9/1.x uses two different devices for playback/capture) */
152     char*                      device;
153     snd_pcm_t*                  p_handle;                 /* handle to ALSA playback device */
154     snd_pcm_t*                  c_handle;                 /* handle to ALSA capture device */
155     snd_pcm_hw_params_t *       hw_params;              /* ALSA Hw params */
156
157     snd_ctl_t *                 ctl;                    /* control handle for the playback volume */
158     snd_ctl_elem_id_t *         playback_eid;           /* element id of the playback volume control */
159     snd_ctl_elem_value_t *      playback_evalue;        /* element value of the playback volume control */
160     snd_ctl_elem_info_t *       playback_einfo;         /* element info of the playback volume control */
161
162     snd_pcm_sframes_t           (*write)(snd_pcm_t *, const void *, snd_pcm_uframes_t );
163
164     struct pollfd               *ufds;
165     int                         count;
166
167     DWORD                       dwBufferSize;           /* size of whole ALSA buffer in bytes */
168     LPWAVEHDR                   lpQueuePtr;             /* start of queued WAVEHDRs (waiting to be notified) */
169     LPWAVEHDR                   lpPlayPtr;              /* start of not yet fully played buffers */
170     DWORD                       dwPartialOffset;        /* Offset of not yet written bytes in lpPlayPtr */
171
172     LPWAVEHDR                   lpLoopPtr;              /* pointer of first buffer in loop, if any */
173     DWORD                       dwLoops;                /* private copy of loop counter */
174
175     DWORD                       dwPlayedTotal;          /* number of bytes actually played since opening */
176     DWORD                       dwWrittenTotal;         /* number of bytes written to ALSA buffer since opening */
177
178     /* synchronization stuff */
179     HANDLE                      hStartUpEvent;
180     HANDLE                      hThread;
181     DWORD                       dwThreadID;
182     ALSA_MSG_RING               msgRing;
183
184     /* DirectSound stuff */
185     DSDRIVERDESC                ds_desc;
186     GUID                        ds_guid;
187 } WINE_WAVEOUT;
188
189 typedef struct {
190     /* Windows information */
191     volatile int                state;                  /* one of the WINE_WS_ manifest constants */
192     WAVEOPENDESC                waveDesc;
193     WORD                        wFlags;
194     PCMWAVEFORMAT               format;
195     WAVEOUTCAPSA                caps;
196
197     /* ALSA information (ALSA 0.9/1.x uses two different devices for playback/capture) */
198     char*                      device;
199     snd_pcm_t*                  p_handle;                 /* handle to ALSA playback device */
200     snd_pcm_t*                  c_handle;                 /* handle to ALSA capture device */
201     snd_pcm_hw_params_t *       hw_params;              /* ALSA Hw params */
202
203     snd_ctl_t *                 ctl;                    /* control handle for the playback volume */
204     snd_ctl_elem_id_t *         playback_eid;           /* element id of the playback volume control */
205     snd_ctl_elem_value_t *      playback_evalue;        /* element value of the playback volume control */
206     snd_ctl_elem_info_t *       playback_einfo;         /* element info of the playback volume control */
207
208     snd_pcm_sframes_t           (*read)(snd_pcm_t *, void *, snd_pcm_uframes_t );
209
210     struct pollfd               *ufds;
211     int                         count;
212
213     DWORD                       dwPeriodSize;           /* size of OSS buffer period */
214     DWORD                       dwBufferSize;           /* size of whole ALSA buffer in bytes */
215     LPWAVEHDR                   lpQueuePtr;             /* start of queued WAVEHDRs (waiting to be notified) */
216     LPWAVEHDR                   lpPlayPtr;              /* start of not yet fully played buffers */
217
218     LPWAVEHDR                   lpLoopPtr;              /* pointer of first buffer in loop, if any */
219     DWORD                       dwLoops;                /* private copy of loop counter */
220
221     /*DWORD                     dwPlayedTotal; */
222     DWORD                       dwTotalRecorded;
223
224     /* synchronization stuff */
225     HANDLE                      hStartUpEvent;
226     HANDLE                      hThread;
227     DWORD                       dwThreadID;
228     ALSA_MSG_RING               msgRing;
229
230     /* DirectSound stuff */
231     DSDRIVERDESC                ds_desc;
232     GUID                        ds_guid;
233 } WINE_WAVEIN;
234
235 static WINE_WAVEOUT     WOutDev   [MAX_WAVEOUTDRV];
236 static DWORD            ALSA_WodNumDevs;
237 static WINE_WAVEIN      WInDev   [MAX_WAVEINDRV];
238 static DWORD            ALSA_WidNumDevs;
239
240 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
241 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
242 static DWORD wodDsGuid(UINT wDevID, LPGUID pGuid);
243
244 /* These strings used only for tracing */
245 #if 1
246 static const char *wodPlayerCmdString[] = {
247     "WINE_WM_PAUSING",
248     "WINE_WM_RESTARTING",
249     "WINE_WM_RESETTING",
250     "WINE_WM_HEADER",
251     "WINE_WM_UPDATE",
252     "WINE_WM_BREAKLOOP",
253     "WINE_WM_CLOSING",
254     "WINE_WM_STARTING",
255     "WINE_WM_STOPPING",
256 };
257 #endif
258
259 /*======================================================================*
260  *                  Low level WAVE implementation                       *
261  *======================================================================*/
262
263 /**************************************************************************
264  *                      ALSA_InitializeVolumeCtl                [internal]
265  *
266  * used to initialize the PCM Volume Control
267  */
268 static int ALSA_InitializeVolumeCtl(WINE_WAVEOUT * wwo)
269 {
270     snd_ctl_t *                 ctl = NULL;
271     snd_ctl_card_info_t *       cardinfo;
272     snd_ctl_elem_list_t *       elemlist;
273     snd_ctl_elem_id_t *         e_id;
274     snd_ctl_elem_info_t *       einfo;
275     snd_hctl_t *                hctl = NULL;
276     snd_hctl_elem_t *           elem;
277     int                         nCtrls;
278     int                         i;
279
280     snd_ctl_card_info_alloca(&cardinfo);
281     memset(cardinfo,0,snd_ctl_card_info_sizeof());
282
283     snd_ctl_elem_list_alloca(&elemlist);
284     memset(elemlist,0,snd_ctl_elem_list_sizeof());
285
286     snd_ctl_elem_id_alloca(&e_id);
287     memset(e_id,0,snd_ctl_elem_id_sizeof());
288
289     snd_ctl_elem_info_alloca(&einfo);
290     memset(einfo,0,snd_ctl_elem_info_sizeof());
291
292 #define EXIT_ON_ERROR(f,txt) do \
293 { \
294     int err; \
295     if ( (err = (f) ) < 0) \
296     { \
297         ERR(txt ": %s\n", snd_strerror(err)); \
298         if (hctl) \
299             snd_hctl_close(hctl); \
300         if (ctl) \
301             snd_ctl_close(ctl); \
302         return -1; \
303     } \
304 } while(0)
305
306     EXIT_ON_ERROR( snd_ctl_open(&ctl,"hw",0) , "ctl open failed" );
307     EXIT_ON_ERROR( snd_ctl_card_info(ctl, cardinfo), "card info failed");
308     EXIT_ON_ERROR( snd_ctl_elem_list(ctl, elemlist), "elem list failed");
309
310     nCtrls = snd_ctl_elem_list_get_count(elemlist);
311
312     EXIT_ON_ERROR( snd_hctl_open(&hctl,"hw",0), "hctl open failed");
313     EXIT_ON_ERROR( snd_hctl_load(hctl), "hctl load failed" );
314
315     elem=snd_hctl_first_elem(hctl);
316     for ( i= 0; i<nCtrls; i++) {
317
318         memset(e_id,0,snd_ctl_elem_id_sizeof());
319
320         snd_hctl_elem_get_id(elem,e_id);
321 /*
322         TRACE("ctl: #%d '%s'%d\n",
323                                    snd_ctl_elem_id_get_numid(e_id),
324                                    snd_ctl_elem_id_get_name(e_id),
325                                    snd_ctl_elem_id_get_index(e_id));
326 */
327         if ( !strcmp("PCM Playback Volume", snd_ctl_elem_id_get_name(e_id)) )
328         {
329             EXIT_ON_ERROR( snd_hctl_elem_info(elem,einfo), "hctl elem info failed" );
330
331             /* few sanity checks... you'll never know... */
332             if ( snd_ctl_elem_info_get_type(einfo) != SND_CTL_ELEM_TYPE_INTEGER )
333                 WARN("playback volume control is not an integer\n");
334             if ( !snd_ctl_elem_info_is_readable(einfo) )
335                 WARN("playback volume control is readable\n");
336             if ( !snd_ctl_elem_info_is_writable(einfo) )
337                 WARN("playback volume control is readable\n");
338
339             TRACE("   ctrl range: min=%ld  max=%ld  step=%ld\n",
340                  snd_ctl_elem_info_get_min(einfo),
341                  snd_ctl_elem_info_get_max(einfo),
342                  snd_ctl_elem_info_get_step(einfo));
343
344             EXIT_ON_ERROR( snd_ctl_elem_id_malloc(&wwo->playback_eid), "elem id malloc failed" );
345             EXIT_ON_ERROR( snd_ctl_elem_info_malloc(&wwo->playback_einfo), "elem info malloc failed" );
346             EXIT_ON_ERROR( snd_ctl_elem_value_malloc(&wwo->playback_evalue), "elem value malloc failed" );
347
348             /* ok, now we can safely save these objects for later */
349             snd_ctl_elem_id_copy(wwo->playback_eid, e_id);
350             snd_ctl_elem_info_copy(wwo->playback_einfo, einfo);
351             snd_ctl_elem_value_set_id(wwo->playback_evalue, wwo->playback_eid);
352             wwo->ctl = ctl;
353         }
354
355         elem=snd_hctl_elem_next(elem);
356     }
357     snd_hctl_close(hctl);
358 #undef EXIT_ON_ERROR
359     return 0;
360 }
361
362 /**************************************************************************
363  *                      ALSA_XRUNRecovery               [internal]
364  *
365  * used to recovery from XRUN errors (buffer underflow/overflow)
366  */
367 static int ALSA_XRUNRecovery(WINE_WAVEOUT * wwo, int err)
368 {
369     if (err == -EPIPE) {    /* under-run */
370         err = snd_pcm_prepare(wwo->p_handle);
371         if (err < 0)
372              ERR( "underrun recovery failed. prepare failed: %s\n", snd_strerror(err));
373         return 0;
374     } else if (err == -ESTRPIPE) {
375         while ((err = snd_pcm_resume(wwo->p_handle)) == -EAGAIN)
376             sleep(1);       /* wait until the suspend flag is released */
377         if (err < 0) {
378             err = snd_pcm_prepare(wwo->p_handle);
379             if (err < 0)
380                 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
381         }
382         return 0;
383     }
384     return err;
385 }
386
387 /**************************************************************************
388  *                      ALSA_TraceParameters            [internal]
389  *
390  * used to trace format changes, hw and sw parameters
391  */
392 static void ALSA_TraceParameters(snd_pcm_hw_params_t * hw_params, snd_pcm_sw_params_t * sw, int full)
393 {
394     snd_pcm_format_t   format = snd_pcm_hw_params_get_format(hw_params);
395     snd_pcm_access_t   access = snd_pcm_hw_params_get_access(hw_params);
396
397 #define X(x) ((x)? "true" : "false")
398     if (full)
399         TRACE("FLAGS: sampleres=%s overrng=%s pause=%s resume=%s syncstart=%s batch=%s block=%s double=%s "
400               "halfd=%s joint=%s \n",
401               X(snd_pcm_hw_params_can_mmap_sample_resolution(hw_params)),
402               X(snd_pcm_hw_params_can_overrange(hw_params)),
403               X(snd_pcm_hw_params_can_pause(hw_params)),
404               X(snd_pcm_hw_params_can_resume(hw_params)),
405               X(snd_pcm_hw_params_can_sync_start(hw_params)),
406               X(snd_pcm_hw_params_is_batch(hw_params)),
407               X(snd_pcm_hw_params_is_block_transfer(hw_params)),
408               X(snd_pcm_hw_params_is_double(hw_params)),
409               X(snd_pcm_hw_params_is_half_duplex(hw_params)),
410               X(snd_pcm_hw_params_is_joint_duplex(hw_params)));
411 #undef X
412
413     if (access >= 0)
414         TRACE("access=%s\n", snd_pcm_access_name(access));
415     else
416     {
417         snd_pcm_access_mask_t * acmask;
418         snd_pcm_access_mask_alloca(&acmask);
419         snd_pcm_hw_params_get_access_mask(hw_params, acmask);
420         for ( access = SND_PCM_ACCESS_MMAP_INTERLEAVED; access <= SND_PCM_ACCESS_LAST; access++)
421             if (snd_pcm_access_mask_test(acmask, access))
422                 TRACE("access=%s\n", snd_pcm_access_name(access));
423     }
424
425     if (format >= 0)
426     {
427         TRACE("format=%s\n", snd_pcm_format_name(format));
428
429     }
430     else
431     {
432         snd_pcm_format_mask_t *     fmask;
433
434         snd_pcm_format_mask_alloca(&fmask);
435         snd_pcm_hw_params_get_format_mask(hw_params, fmask);
436         for ( format = SND_PCM_FORMAT_S8; format <= SND_PCM_FORMAT_LAST ; format++)
437             if ( snd_pcm_format_mask_test(fmask, format) )
438                 TRACE("format=%s\n", snd_pcm_format_name(format));
439     }
440
441 #define X(x) do { \
442 int n = snd_pcm_hw_params_get_##x(hw_params); \
443 if (n<0) \
444     TRACE(#x "_min=%ld " #x "_max=%ld\n", \
445         (long int)snd_pcm_hw_params_get_##x##_min(hw_params), \
446         (long int)snd_pcm_hw_params_get_##x##_max(hw_params)); \
447 else \
448     TRACE(#x "=%d\n", n); \
449 } while(0)
450     X(channels);
451     X(buffer_size);
452 #undef X
453
454 #define X(x) do { \
455 int n = snd_pcm_hw_params_get_##x(hw_params,0); \
456 if (n<0) \
457     TRACE(#x "_min=%ld " #x "_max=%ld\n", \
458         (long int)snd_pcm_hw_params_get_##x##_min(hw_params,0), \
459         (long int)snd_pcm_hw_params_get_##x##_max(hw_params,0)); \
460 else \
461     TRACE(#x "=%d\n", n); \
462 } while(0)
463     X(rate);
464     X(buffer_time);
465     X(periods);
466     X(period_size);
467     X(period_time);
468     X(tick_time);
469 #undef X
470
471     if (!sw)
472         return;
473
474
475 }
476
477 /* return a string duplicated on the win32 process heap, free with HeapFree */
478 static char* ALSA_strdup(char *s) {
479     char *result = HeapAlloc(GetProcessHeap(), 0, strlen(s)+1);
480     strcpy(result, s);
481     return result;
482 }
483
484 /******************************************************************
485  *             ALSA_GetDeviceFromReg
486  *
487  * Returns either "default" or reads the registry so the user can
488  * override the playback/record device used.
489  */
490 char *ALSA_GetDeviceFromReg(char *value)
491 {
492     DWORD res;
493     DWORD type;
494     HKEY playbackKey = 0;
495     char *result = NULL;
496     DWORD resultSize;
497
498     res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\ALSA", 0, KEY_QUERY_VALUE, &playbackKey);
499     if (res != ERROR_SUCCESS) goto end;
500
501     res = RegQueryValueExA(playbackKey, value, NULL, &type, NULL, &resultSize);
502     if (res != ERROR_SUCCESS) goto end;
503
504     if (type != REG_SZ) {
505        ERR("Registry key [HKEY_LOCAL_MACHINE\\Software\\Wine\\Wine\\ALSA\\%s] must be a string\n", value);
506        goto end;
507     }
508
509     result = HeapAlloc(GetProcessHeap(), 0, resultSize);
510     res = RegQueryValueExA(playbackKey, value, NULL, NULL, result, &resultSize);
511
512 end:
513     if (!result) result = ALSA_strdup("default");
514     if (playbackKey) RegCloseKey(playbackKey);
515     return result;
516 }
517
518 /******************************************************************
519  *              ALSA_WaveInit
520  *
521  * Initialize internal structures from ALSA information
522  */
523 LONG ALSA_WaveInit(void)
524 {
525     snd_pcm_t*                  h;
526     snd_pcm_info_t *            info;
527     snd_pcm_hw_params_t *       hw_params;
528     WINE_WAVEOUT*               wwo;
529     WINE_WAVEIN*                wwi;
530
531     wwo = &WOutDev[0];
532
533     /* FIXME: use better values */
534     wwo->device = ALSA_GetDeviceFromReg("PlaybackDevice");
535     TRACE("using waveout device \"%s\"\n", wwo->device);
536
537     wwo->caps.wMid = 0x0002;
538     wwo->caps.wPid = 0x0104;
539     strcpy(wwo->caps.szPname, "SB16 Wave Out");
540     wwo->caps.vDriverVersion = 0x0100;
541     wwo->caps.dwFormats = 0x00000000;
542     wwo->caps.dwSupport = WAVECAPS_VOLUME;
543     strcpy(wwo->ds_desc.szDesc, "WineALSA DirectSound Driver");
544     strcpy(wwo->ds_desc.szDrvName, "winealsa.drv");
545     wwo->ds_guid = DSDEVID_DefaultPlayback;
546
547     if (!wine_dlopen("libasound.so.2", RTLD_LAZY|RTLD_GLOBAL, NULL, 0))
548     {
549         ERR("Error: ALSA lib needs to be loaded with flags RTLD_LAZY and RTLD_GLOBAL.\n");
550         return -1;
551     }
552
553     snd_pcm_info_alloca(&info);
554     snd_pcm_hw_params_alloca(&hw_params);
555
556 #define EXIT_ON_ERROR(f,txt) do { int err; if ( (err = (f) ) < 0) { ERR(txt ": %s\n", snd_strerror(err)); if (h) snd_pcm_close(h); return -1; } } while(0)
557
558     h = NULL;
559     ALSA_WodNumDevs = 0;
560     EXIT_ON_ERROR( snd_pcm_open(&h, wwo->device, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK) , "open pcm" );
561     if (!h) return -1;
562     ALSA_WodNumDevs++;
563
564     EXIT_ON_ERROR( snd_pcm_info(h, info) , "pcm info" );
565
566     TRACE("dev=%d id=%s name=%s subdev=%d subdev_name=%s subdev_avail=%d subdev_num=%d stream=%s subclass=%s \n",
567        snd_pcm_info_get_device(info),
568        snd_pcm_info_get_id(info),
569        snd_pcm_info_get_name(info),
570        snd_pcm_info_get_subdevice(info),
571        snd_pcm_info_get_subdevice_name(info),
572        snd_pcm_info_get_subdevices_avail(info),
573        snd_pcm_info_get_subdevices_count(info),
574        snd_pcm_stream_name(snd_pcm_info_get_stream(info)),
575        (snd_pcm_info_get_subclass(info) == SND_PCM_SUBCLASS_GENERIC_MIX ? "GENERIC MIX": "MULTI MIX"));
576
577     EXIT_ON_ERROR( snd_pcm_hw_params_any(h, hw_params) , "pcm hw params" );
578 #undef EXIT_ON_ERROR
579
580     if (TRACE_ON(wave))
581         ALSA_TraceParameters(hw_params, NULL, TRUE);
582
583     {
584         snd_pcm_format_mask_t *     fmask;
585         int ratemin = snd_pcm_hw_params_get_rate_min(hw_params, 0);
586         int ratemax = snd_pcm_hw_params_get_rate_max(hw_params, 0);
587         int chmin = snd_pcm_hw_params_get_channels_min(hw_params); \
588         int chmax = snd_pcm_hw_params_get_channels_max(hw_params); \
589
590         snd_pcm_format_mask_alloca(&fmask);
591         snd_pcm_hw_params_get_format_mask(hw_params, fmask);
592
593 #define X(r,v) \
594        if ( (r) >= ratemin && ( (r) <= ratemax || ratemax == -1) ) \
595        { \
596           if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_U8)) \
597           { \
598               if (chmin <= 1 && 1 <= chmax) \
599                   wwo->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
600               if (chmin <= 2 && 2 <= chmax) \
601                   wwo->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
602           } \
603           if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_S16_LE)) \
604           { \
605               if (chmin <= 1 && 1 <= chmax) \
606                   wwo->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
607               if (chmin <= 2 && 2 <= chmax) \
608                   wwo->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
609           } \
610        }
611        X(11025,1);
612        X(22050,2);
613        X(44100,4);
614        X(48000,48);
615        X(96000,96);
616 #undef X
617     }
618
619     if ( snd_pcm_hw_params_get_channels_min(hw_params) > 1) FIXME("-\n");
620     wwo->caps.wChannels = (snd_pcm_hw_params_get_channels_max(hw_params) >= 2) ? 2 : 1;
621     if (snd_pcm_hw_params_get_channels_min(hw_params) <= 2 && 2 <= snd_pcm_hw_params_get_channels_max(hw_params))
622         wwo->caps.dwSupport |= WAVECAPS_LRVOLUME;
623
624     /* FIXME: always true ? */
625     wwo->caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
626
627     {
628         snd_pcm_access_mask_t *     acmask;
629         snd_pcm_access_mask_alloca(&acmask);
630         snd_pcm_hw_params_get_access_mask(hw_params, acmask);
631
632         /* FIXME: NONITERLEAVED and COMPLEX are not supported right now */
633         if ( snd_pcm_access_mask_test( acmask, SND_PCM_ACCESS_MMAP_INTERLEAVED ) )
634             wwo->caps.dwSupport |= WAVECAPS_DIRECTSOUND;
635     }
636
637     TRACE("Configured with dwFmts=%08lx dwSupport=%08lx\n",
638           wwo->caps.dwFormats, wwo->caps.dwSupport);
639
640     snd_pcm_close(h);
641
642     ALSA_InitializeVolumeCtl(wwo);
643
644     wwi = &WInDev[0];
645
646     /* FIXME: use better values */
647     wwi->device = ALSA_GetDeviceFromReg("RecordDevice");
648     TRACE("using wavein device \"%s\"\n", wwi->device);
649
650     wwi->caps.wMid = 0x0002;
651     wwi->caps.wPid = 0x0104;
652     strcpy(wwi->caps.szPname, "SB16 Wave In");
653     wwi->caps.vDriverVersion = 0x0100;
654     wwi->caps.dwFormats = 0x00000000;
655     wwi->caps.dwSupport = WAVECAPS_VOLUME;
656     strcpy(wwi->ds_desc.szDesc, "WineALSA DirectSound Driver");
657     strcpy(wwi->ds_desc.szDrvName, "winealsa.drv");
658     wwi->ds_guid = DSDEVID_DefaultPlayback;
659
660     snd_pcm_info_alloca(&info);
661     snd_pcm_hw_params_alloca(&hw_params);
662
663 #define EXIT_ON_ERROR(f,txt) do { int err; if ( (err = (f) ) < 0) { ERR(txt ": %s\n", snd_strerror(err)); if (h) snd_pcm_close(h); return -1; } } while(0)
664
665     h = NULL;
666     ALSA_WidNumDevs = 0;
667     EXIT_ON_ERROR( snd_pcm_open(&h, wwi->device, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK) , "open pcm" );
668     if (!h) return -1;
669     ALSA_WidNumDevs++;
670
671     EXIT_ON_ERROR( snd_pcm_info(h, info) , "pcm info" );
672
673     TRACE("dev=%d id=%s name=%s subdev=%d subdev_name=%s subdev_avail=%d subdev_num=%d stream=%s subclass=%s \n",
674        snd_pcm_info_get_device(info),
675        snd_pcm_info_get_id(info),
676        snd_pcm_info_get_name(info),
677        snd_pcm_info_get_subdevice(info),
678        snd_pcm_info_get_subdevice_name(info),
679        snd_pcm_info_get_subdevices_avail(info),
680        snd_pcm_info_get_subdevices_count(info),
681        snd_pcm_stream_name(snd_pcm_info_get_stream(info)),
682        (snd_pcm_info_get_subclass(info) == SND_PCM_SUBCLASS_GENERIC_MIX ? "GENERIC MIX": "MULTI MIX"));
683
684     EXIT_ON_ERROR( snd_pcm_hw_params_any(h, hw_params) , "pcm hw params" );
685 #undef EXIT_ON_ERROR
686
687     if (TRACE_ON(wave))
688         ALSA_TraceParameters(hw_params, NULL, TRUE);
689
690     {
691         snd_pcm_format_mask_t *     fmask;
692         int ratemin = snd_pcm_hw_params_get_rate_min(hw_params, 0);
693         int ratemax = snd_pcm_hw_params_get_rate_max(hw_params, 0);
694         int chmin = snd_pcm_hw_params_get_channels_min(hw_params); \
695         int chmax = snd_pcm_hw_params_get_channels_max(hw_params); \
696
697         snd_pcm_format_mask_alloca(&fmask);
698         snd_pcm_hw_params_get_format_mask(hw_params, fmask);
699
700 #define X(r,v) \
701        if ( (r) >= ratemin && ( (r) <= ratemax || ratemax == -1) ) \
702        { \
703           if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_U8)) \
704           { \
705               if (chmin <= 1 && 1 <= chmax) \
706                   wwi->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
707               if (chmin <= 2 && 2 <= chmax) \
708                   wwi->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
709           } \
710           if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_S16_LE)) \
711           { \
712               if (chmin <= 1 && 1 <= chmax) \
713                   wwi->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
714               if (chmin <= 2 && 2 <= chmax) \
715                   wwi->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
716           } \
717        }
718        X(11025,1);
719        X(22050,2);
720        X(44100,4);
721        X(48000,48);
722        X(96000,96);
723 #undef X
724     }
725
726     if ( snd_pcm_hw_params_get_channels_min(hw_params) > 1) FIXME("-\n");
727     wwi->caps.wChannels = (snd_pcm_hw_params_get_channels_max(hw_params) >= 2) ? 2 : 1;
728     if (snd_pcm_hw_params_get_channels_min(hw_params) <= 2 && 2 <= snd_pcm_hw_params_get_channels_max(hw_params))
729         wwi->caps.dwSupport |= WAVECAPS_LRVOLUME;
730
731     /* FIXME: always true ? */
732     wwi->caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
733
734     {
735         snd_pcm_access_mask_t *     acmask;
736         snd_pcm_access_mask_alloca(&acmask);
737         snd_pcm_hw_params_get_access_mask(hw_params, acmask);
738
739         /* FIXME: NONITERLEAVED and COMPLEX are not supported right now */
740         if ( snd_pcm_access_mask_test( acmask, SND_PCM_ACCESS_MMAP_INTERLEAVED ) )
741             wwi->caps.dwSupport |= WAVECAPS_DIRECTSOUND;
742     }
743
744     TRACE("Configured with dwFmts=%08lx dwSupport=%08lx\n",
745           wwi->caps.dwFormats, wwi->caps.dwSupport);
746
747     snd_pcm_close(h);
748     
749     return 0;
750 }
751
752 /******************************************************************
753  *              ALSA_InitRingMessage
754  *
755  * Initialize the ring of messages for passing between driver's caller and playback/record
756  * thread
757  */
758 static int ALSA_InitRingMessage(ALSA_MSG_RING* omr)
759 {
760     omr->msg_toget = 0;
761     omr->msg_tosave = 0;
762 #ifdef USE_PIPE_SYNC
763     if (pipe(omr->msg_pipe) < 0) {
764         omr->msg_pipe[0] = -1;
765         omr->msg_pipe[1] = -1;
766         ERR("could not create pipe, error=%s\n", strerror(errno));
767     }
768 #else
769     omr->msg_event = CreateEventA(NULL, FALSE, FALSE, NULL);
770 #endif
771     omr->ring_buffer_size = ALSA_RING_BUFFER_INCREMENT;
772     omr->messages = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,omr->ring_buffer_size * sizeof(ALSA_MSG));
773
774     InitializeCriticalSection(&omr->msg_crst);
775     return 0;
776 }
777
778 /******************************************************************
779  *              ALSA_DestroyRingMessage
780  *
781  */
782 static int ALSA_DestroyRingMessage(ALSA_MSG_RING* omr)
783 {
784 #ifdef USE_PIPE_SYNC
785     close(omr->msg_pipe[0]);
786     close(omr->msg_pipe[1]);
787 #else
788     CloseHandle(omr->msg_event);
789 #endif
790     HeapFree(GetProcessHeap(),0,omr->messages);
791     DeleteCriticalSection(&omr->msg_crst);
792     return 0;
793 }
794
795 /******************************************************************
796  *              ALSA_AddRingMessage
797  *
798  * Inserts a new message into the ring (should be called from DriverProc derivated routines)
799  */
800 static int ALSA_AddRingMessage(ALSA_MSG_RING* omr, enum win_wm_message msg, DWORD param, BOOL wait)
801 {
802     HANDLE      hEvent = INVALID_HANDLE_VALUE;
803
804     EnterCriticalSection(&omr->msg_crst);
805     if ((omr->msg_toget == ((omr->msg_tosave + 1) % omr->ring_buffer_size)))
806     {
807         int old_ring_buffer_size = omr->ring_buffer_size;
808         omr->ring_buffer_size += ALSA_RING_BUFFER_INCREMENT;
809         TRACE("omr->ring_buffer_size=%d\n",omr->ring_buffer_size);
810         omr->messages = HeapReAlloc(GetProcessHeap(),0,omr->messages, omr->ring_buffer_size * sizeof(ALSA_MSG));
811         /* Now we need to rearrange the ring buffer so that the new
812            buffers just allocated are in between omr->msg_tosave and
813            omr->msg_toget.
814         */
815         if (omr->msg_tosave < omr->msg_toget)
816         {
817             memmove(&(omr->messages[omr->msg_toget + ALSA_RING_BUFFER_INCREMENT]),
818                     &(omr->messages[omr->msg_toget]),
819                     sizeof(ALSA_MSG)*(old_ring_buffer_size - omr->msg_toget)
820                     );
821             omr->msg_toget += ALSA_RING_BUFFER_INCREMENT;
822         }
823     }
824     if (wait)
825     {
826         hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
827         if (hEvent == INVALID_HANDLE_VALUE)
828         {
829             ERR("can't create event !?\n");
830             LeaveCriticalSection(&omr->msg_crst);
831             return 0;
832         }
833         if (omr->msg_toget != omr->msg_tosave && omr->messages[omr->msg_toget].msg != WINE_WM_HEADER)
834             FIXME("two fast messages in the queue!!!!\n");
835
836         /* fast messages have to be added at the start of the queue */
837         omr->msg_toget = (omr->msg_toget + omr->ring_buffer_size - 1) % omr->ring_buffer_size;
838
839         omr->messages[omr->msg_toget].msg = msg;
840         omr->messages[omr->msg_toget].param = param;
841         omr->messages[omr->msg_toget].hEvent = hEvent;
842     }
843     else
844     {
845         omr->messages[omr->msg_tosave].msg = msg;
846         omr->messages[omr->msg_tosave].param = param;
847         omr->messages[omr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
848         omr->msg_tosave = (omr->msg_tosave + 1) % omr->ring_buffer_size;
849     }
850     LeaveCriticalSection(&omr->msg_crst);
851     /* signal a new message */
852     SIGNAL_OMR(omr);
853     if (wait)
854     {
855         /* wait for playback/record thread to have processed the message */
856         WaitForSingleObject(hEvent, INFINITE);
857         CloseHandle(hEvent);
858     }
859     return 1;
860 }
861
862 /******************************************************************
863  *              ALSA_RetrieveRingMessage
864  *
865  * Get a message from the ring. Should be called by the playback/record thread.
866  */
867 static int ALSA_RetrieveRingMessage(ALSA_MSG_RING* omr,
868                                    enum win_wm_message *msg, DWORD *param, HANDLE *hEvent)
869 {
870     EnterCriticalSection(&omr->msg_crst);
871
872     if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
873     {
874         LeaveCriticalSection(&omr->msg_crst);
875         return 0;
876     }
877
878     *msg = omr->messages[omr->msg_toget].msg;
879     omr->messages[omr->msg_toget].msg = 0;
880     *param = omr->messages[omr->msg_toget].param;
881     *hEvent = omr->messages[omr->msg_toget].hEvent;
882     omr->msg_toget = (omr->msg_toget + 1) % omr->ring_buffer_size;
883     CLEAR_OMR(omr);
884     LeaveCriticalSection(&omr->msg_crst);
885     return 1;
886 }
887
888 /******************************************************************
889  *              ALSA_PeekRingMessage
890  *
891  * Peek at a message from the ring but do not remove it.
892  * Should be called by the playback/record thread.
893  */
894 static int ALSA_PeekRingMessage(ALSA_MSG_RING* omr,
895                                enum win_wm_message *msg,
896                                DWORD *param, HANDLE *hEvent)
897 {
898     EnterCriticalSection(&omr->msg_crst);
899
900     if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
901     {
902         LeaveCriticalSection(&omr->msg_crst);
903         return 0;
904     }
905
906     *msg = omr->messages[omr->msg_toget].msg;
907     *param = omr->messages[omr->msg_toget].param;
908     *hEvent = omr->messages[omr->msg_toget].hEvent;
909     LeaveCriticalSection(&omr->msg_crst);
910     return 1;
911 }
912
913 /*======================================================================*
914  *                  Low level WAVE OUT implementation                   *
915  *======================================================================*/
916
917 /**************************************************************************
918  *                      wodNotifyClient                 [internal]
919  */
920 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
921 {
922     TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
923
924     switch (wMsg) {
925     case WOM_OPEN:
926     case WOM_CLOSE:
927     case WOM_DONE:
928         if (wwo->wFlags != DCB_NULL &&
929             !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags, (HDRVR)wwo->waveDesc.hWave,
930                             wMsg, wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
931             WARN("can't notify client !\n");
932             return MMSYSERR_ERROR;
933         }
934         break;
935     default:
936         FIXME("Unknown callback message %u\n", wMsg);
937         return MMSYSERR_INVALPARAM;
938     }
939     return MMSYSERR_NOERROR;
940 }
941
942 /**************************************************************************
943  *                              wodUpdatePlayedTotal    [internal]
944  *
945  */
946 static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo, snd_pcm_status_t* ps)
947 {
948    snd_pcm_sframes_t delay = 0;
949    snd_pcm_delay(wwo->p_handle, &delay);
950    wwo->dwPlayedTotal = wwo->dwWrittenTotal - delay;
951    return TRUE;
952 }
953
954 /**************************************************************************
955  *                              wodPlayer_BeginWaveHdr          [internal]
956  *
957  * Makes the specified lpWaveHdr the currently playing wave header.
958  * If the specified wave header is a begin loop and we're not already in
959  * a loop, setup the loop.
960  */
961 static void wodPlayer_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
962 {
963     wwo->lpPlayPtr = lpWaveHdr;
964
965     if (!lpWaveHdr) return;
966
967     if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
968         if (wwo->lpLoopPtr) {
969             WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
970         } else {
971             TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
972             wwo->lpLoopPtr = lpWaveHdr;
973             /* Windows does not touch WAVEHDR.dwLoops,
974              * so we need to make an internal copy */
975             wwo->dwLoops = lpWaveHdr->dwLoops;
976         }
977     }
978     wwo->dwPartialOffset = 0;
979 }
980
981 /**************************************************************************
982  *                              wodPlayer_PlayPtrNext           [internal]
983  *
984  * Advance the play pointer to the next waveheader, looping if required.
985  */
986 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEOUT* wwo)
987 {
988     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
989
990     wwo->dwPartialOffset = 0;
991     if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
992         /* We're at the end of a loop, loop if required */
993         if (--wwo->dwLoops > 0) {
994             wwo->lpPlayPtr = wwo->lpLoopPtr;
995         } else {
996             /* Handle overlapping loops correctly */
997             if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
998                 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
999                 /* shall we consider the END flag for the closing loop or for
1000                  * the opening one or for both ???
1001                  * code assumes for closing loop only
1002                  */
1003             } else {
1004                 lpWaveHdr = lpWaveHdr->lpNext;
1005             }
1006             wwo->lpLoopPtr = NULL;
1007             wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
1008         }
1009     } else {
1010         /* We're not in a loop.  Advance to the next wave header */
1011         wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
1012     }
1013
1014     return lpWaveHdr;
1015 }
1016
1017 /**************************************************************************
1018  *                           wodPlayer_DSPWait                  [internal]
1019  * Returns the number of milliseconds to wait for the DSP buffer to play a
1020  * period
1021  */
1022 static DWORD wodPlayer_DSPWait(const WINE_WAVEOUT *wwo)
1023 {
1024     /* time for one period to be played */
1025     return snd_pcm_hw_params_get_period_time(wwo->hw_params, 0) / 1000;
1026 }
1027
1028 /**************************************************************************
1029  *                           wodPlayer_NotifyWait               [internal]
1030  * Returns the number of milliseconds to wait before attempting to notify
1031  * completion of the specified wavehdr.
1032  * This is based on the number of bytes remaining to be written in the
1033  * wave.
1034  */
1035 static DWORD wodPlayer_NotifyWait(const WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1036 {
1037     DWORD dwMillis;
1038
1039     if (lpWaveHdr->reserved < wwo->dwPlayedTotal) {
1040         dwMillis = 1;
1041     } else {
1042         dwMillis = (lpWaveHdr->reserved - wwo->dwPlayedTotal) * 1000 / wwo->format.wf.nAvgBytesPerSec;
1043         if (!dwMillis) dwMillis = 1;
1044     }
1045
1046     return dwMillis;
1047 }
1048
1049
1050 /**************************************************************************
1051  *                           wodPlayer_WriteMaxFrags            [internal]
1052  * Writes the maximum number of frames possible to the DSP and returns
1053  * the number of frames written.
1054  */
1055 static int wodPlayer_WriteMaxFrags(WINE_WAVEOUT* wwo, DWORD* frames)
1056 {
1057     /* Only attempt to write to free frames */
1058     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1059     DWORD dwLength = snd_pcm_bytes_to_frames(wwo->p_handle, lpWaveHdr->dwBufferLength - wwo->dwPartialOffset);
1060     int toWrite = min(dwLength, *frames);
1061     int written;
1062
1063     TRACE("Writing wavehdr %p.%lu[%lu]\n", lpWaveHdr, wwo->dwPartialOffset, lpWaveHdr->dwBufferLength);
1064
1065     written = (wwo->write)(wwo->p_handle, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
1066     if ( written < 0)
1067     {
1068         /* XRUN occurred. let's try to recover */
1069         ALSA_XRUNRecovery(wwo, written);
1070         written = (wwo->write)(wwo->p_handle, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
1071     }
1072     if (written <= 0)
1073     {
1074         /* still in error */
1075         ERR("Error in writing wavehdr. Reason: %s\n", snd_strerror(written));
1076         return written;
1077     }
1078
1079     wwo->dwPartialOffset += snd_pcm_frames_to_bytes(wwo->p_handle, written);
1080     if ( wwo->dwPartialOffset >= lpWaveHdr->dwBufferLength) {
1081         /* this will be used to check if the given wave header has been fully played or not... */
1082         wwo->dwPartialOffset = lpWaveHdr->dwBufferLength;
1083         /* If we wrote all current wavehdr, skip to the next one */
1084         wodPlayer_PlayPtrNext(wwo);
1085     }
1086     *frames -= written;
1087     wwo->dwWrittenTotal += snd_pcm_frames_to_bytes(wwo->p_handle, written);
1088
1089     return written;
1090 }
1091
1092
1093 /**************************************************************************
1094  *                              wodPlayer_NotifyCompletions     [internal]
1095  *
1096  * Notifies and remove from queue all wavehdrs which have been played to
1097  * the speaker (ie. they have cleared the ALSA buffer).  If force is true,
1098  * we notify all wavehdrs and remove them all from the queue even if they
1099  * are unplayed or part of a loop.
1100  */
1101 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1102 {
1103     LPWAVEHDR           lpWaveHdr;
1104
1105     /* Start from lpQueuePtr and keep notifying until:
1106      * - we hit an unwritten wavehdr
1107      * - we hit the beginning of a running loop
1108      * - we hit a wavehdr which hasn't finished playing
1109      */
1110 #if 0
1111     while ((lpWaveHdr = wwo->lpQueuePtr) &&
1112            (force ||
1113             (lpWaveHdr != wwo->lpPlayPtr &&
1114              lpWaveHdr != wwo->lpLoopPtr &&
1115              lpWaveHdr->reserved <= wwo->dwPlayedTotal))) {
1116
1117         wwo->lpQueuePtr = lpWaveHdr->lpNext;
1118
1119         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1120         lpWaveHdr->dwFlags |= WHDR_DONE;
1121
1122         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1123     }
1124 #else
1125     for (;;)
1126     {
1127         lpWaveHdr = wwo->lpQueuePtr;
1128         if (!lpWaveHdr) {TRACE("Empty queue\n"); break;}
1129         if (!force)
1130         {
1131             if (lpWaveHdr == wwo->lpPlayPtr) {TRACE("play %p\n", lpWaveHdr); break;}
1132             if (lpWaveHdr == wwo->lpLoopPtr) {TRACE("loop %p\n", lpWaveHdr); break;}
1133             if (lpWaveHdr->reserved > wwo->dwPlayedTotal){TRACE("still playing %p (%lu/%lu)\n", lpWaveHdr, lpWaveHdr->reserved, wwo->dwPlayedTotal);break;}
1134         }
1135         wwo->lpQueuePtr = lpWaveHdr->lpNext;
1136
1137         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1138         lpWaveHdr->dwFlags |= WHDR_DONE;
1139
1140         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1141     }
1142 #endif
1143     return  (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
1144         wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
1145 }
1146
1147
1148 void wait_for_poll(snd_pcm_t *handle, struct pollfd *ufds, unsigned int count)
1149 {
1150     unsigned short revents;
1151
1152     if (snd_pcm_state(handle) != SND_PCM_STATE_RUNNING)
1153         return;
1154
1155     while (1) {
1156         poll(ufds, count, -1);
1157         snd_pcm_poll_descriptors_revents(handle, ufds, count, &revents);
1158
1159         if (revents & POLLERR)
1160             return;
1161
1162         /*if (revents & POLLOUT)
1163                 return 0;*/
1164     }
1165 }
1166
1167
1168 /**************************************************************************
1169  *                              wodPlayer_Reset                 [internal]
1170  *
1171  * wodPlayer helper. Resets current output stream.
1172  */
1173 static  void    wodPlayer_Reset(WINE_WAVEOUT* wwo)
1174 {
1175     enum win_wm_message msg;
1176     DWORD                       param;
1177     HANDLE                      ev;
1178     int                         err;
1179
1180     /* flush all possible output */
1181     wait_for_poll(wwo->p_handle, wwo->ufds, wwo->count);
1182
1183     wodUpdatePlayedTotal(wwo, NULL);
1184     /* updates current notify list */
1185     wodPlayer_NotifyCompletions(wwo, FALSE);
1186
1187     if ( (err = snd_pcm_drop(wwo->p_handle)) < 0) {
1188         FIXME("flush: %s\n", snd_strerror(err));
1189         wwo->hThread = 0;
1190         wwo->state = WINE_WS_STOPPED;
1191         ExitThread(-1);
1192     }
1193     if ( (err = snd_pcm_prepare(wwo->p_handle)) < 0 )
1194         ERR("pcm prepare failed: %s\n", snd_strerror(err));
1195
1196     /* remove any buffer */
1197     wodPlayer_NotifyCompletions(wwo, TRUE);
1198
1199     wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1200     wwo->state = WINE_WS_STOPPED;
1201     wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1202     /* Clear partial wavehdr */
1203     wwo->dwPartialOffset = 0;
1204
1205     /* remove any existing message in the ring */
1206     EnterCriticalSection(&wwo->msgRing.msg_crst);
1207     /* return all pending headers in queue */
1208     while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
1209     {
1210         if (msg != WINE_WM_HEADER)
1211         {
1212             FIXME("shouldn't have headers left\n");
1213             SetEvent(ev);
1214             continue;
1215         }
1216         ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
1217         ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
1218
1219         wodNotifyClient(wwo, WOM_DONE, param, 0);
1220     }
1221     RESET_OMR(&wwo->msgRing);
1222     LeaveCriticalSection(&wwo->msgRing.msg_crst);
1223 }
1224
1225 /**************************************************************************
1226  *                    wodPlayer_ProcessMessages                 [internal]
1227  */
1228 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
1229 {
1230     LPWAVEHDR           lpWaveHdr;
1231     enum win_wm_message msg;
1232     DWORD               param;
1233     HANDLE              ev;
1234     int                 err;
1235
1236     while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
1237      TRACE("Received %s %lx\n", wodPlayerCmdString[msg - WM_USER - 1], param); 
1238
1239         switch (msg) {
1240         case WINE_WM_PAUSING:
1241             if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_RUNNING )
1242              {
1243                 err = snd_pcm_pause(wwo->p_handle, 1);
1244                 if ( err < 0 )
1245                     ERR("pcm_pause failed: %s\n", snd_strerror(err));
1246              }
1247             wwo->state = WINE_WS_PAUSED;
1248             SetEvent(ev);
1249             break;
1250         case WINE_WM_RESTARTING:
1251             if (wwo->state == WINE_WS_PAUSED)
1252             {
1253                 if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_PAUSED )
1254                  {
1255                     err = snd_pcm_pause(wwo->p_handle, 0);
1256                     if ( err < 0 )
1257                         ERR("pcm_pause failed: %s\n", snd_strerror(err));
1258                  }
1259                 wwo->state = WINE_WS_PLAYING;
1260             }
1261             SetEvent(ev);
1262             break;
1263         case WINE_WM_HEADER:
1264             lpWaveHdr = (LPWAVEHDR)param;
1265
1266             /* insert buffer at the end of queue */
1267             {
1268                 LPWAVEHDR*      wh;
1269                 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1270                 *wh = lpWaveHdr;
1271             }
1272             if (!wwo->lpPlayPtr)
1273                 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
1274             if (wwo->state == WINE_WS_STOPPED)
1275                 wwo->state = WINE_WS_PLAYING;
1276             break;
1277         case WINE_WM_RESETTING:
1278             wodPlayer_Reset(wwo);
1279             SetEvent(ev);
1280             break;
1281         case WINE_WM_UPDATE:
1282             wodUpdatePlayedTotal(wwo, NULL);
1283             SetEvent(ev);
1284             break;
1285         case WINE_WM_BREAKLOOP:
1286             if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
1287                 /* ensure exit at end of current loop */
1288                 wwo->dwLoops = 1;
1289             }
1290             SetEvent(ev);
1291             break;
1292         case WINE_WM_CLOSING:
1293             /* sanity check: this should not happen since the device must have been reset before */
1294             if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1295             wwo->hThread = 0;
1296             wwo->state = WINE_WS_CLOSED;
1297             SetEvent(ev);
1298             ExitThread(0);
1299             /* shouldn't go here */
1300         default:
1301             FIXME("unknown message %d\n", msg);
1302             break;
1303         }
1304     }
1305 }
1306
1307 /**************************************************************************
1308  *                           wodPlayer_FeedDSP                  [internal]
1309  * Feed as much sound data as we can into the DSP and return the number of
1310  * milliseconds before it will be necessary to feed the DSP again.
1311  */
1312 static DWORD wodPlayer_FeedDSP(WINE_WAVEOUT* wwo)
1313 {
1314     DWORD               availInQ;
1315
1316     wodUpdatePlayedTotal(wwo, NULL);
1317     availInQ = snd_pcm_avail_update(wwo->p_handle);
1318
1319 #if 0
1320     /* input queue empty and output buffer with less than one fragment to play */
1321     if (!wwo->lpPlayPtr && wwo->dwBufferSize < availInQ + wwo->dwFragmentSize) {
1322         TRACE("Run out of wavehdr:s...\n");
1323         return INFINITE;
1324     }
1325 #endif
1326
1327     /* no more room... no need to try to feed */
1328     if (availInQ > 0) {
1329         /* Feed from partial wavehdr */
1330         if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0) {
1331             wodPlayer_WriteMaxFrags(wwo, &availInQ);
1332         }
1333
1334         /* Feed wavehdrs until we run out of wavehdrs or DSP space */
1335         if (wwo->dwPartialOffset == 0 && wwo->lpPlayPtr) {
1336             do {
1337                 TRACE("Setting time to elapse for %p to %lu\n",
1338                       wwo->lpPlayPtr, wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength);
1339                 /* note the value that dwPlayedTotal will return when this wave finishes playing */
1340                 wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
1341             } while (wodPlayer_WriteMaxFrags(wwo, &availInQ) && wwo->lpPlayPtr && availInQ > 0);
1342         }
1343     }
1344
1345     return wodPlayer_DSPWait(wwo);
1346 }
1347
1348 /**************************************************************************
1349  *                              wodPlayer                       [internal]
1350  */
1351 static  DWORD   CALLBACK        wodPlayer(LPVOID pmt)
1352 {
1353     WORD          uDevID = (DWORD)pmt;
1354     WINE_WAVEOUT* wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
1355     DWORD         dwNextFeedTime = INFINITE;   /* Time before DSP needs feeding */
1356     DWORD         dwNextNotifyTime = INFINITE; /* Time before next wave completion */
1357     DWORD         dwSleepTime;
1358
1359     wwo->state = WINE_WS_STOPPED;
1360     SetEvent(wwo->hStartUpEvent);
1361
1362     for (;;) {
1363         /** Wait for the shortest time before an action is required.  If there
1364          *  are no pending actions, wait forever for a command.
1365          */
1366         dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
1367         TRACE("waiting %lums (%lu,%lu)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
1368         WAIT_OMR(&wwo->msgRing, dwSleepTime);
1369         wodPlayer_ProcessMessages(wwo);
1370         if (wwo->state == WINE_WS_PLAYING) {
1371             dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1372             dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1373             if (dwNextFeedTime == INFINITE) {
1374                 /* FeedDSP ran out of data, but before giving up, */
1375                 /* check that a notification didn't give us more */
1376                 wodPlayer_ProcessMessages(wwo);
1377                 if (wwo->lpPlayPtr) {
1378                     TRACE("recovering\n");
1379                     dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1380                 }
1381             }
1382         } else {
1383             dwNextFeedTime = dwNextNotifyTime = INFINITE;
1384         }
1385     }
1386 }
1387
1388 /**************************************************************************
1389  *                      wodGetDevCaps                           [internal]
1390  */
1391 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSA lpCaps, DWORD dwSize)
1392 {
1393     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1394
1395     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1396
1397     if (wDevID >= MAX_WAVEOUTDRV) {
1398         TRACE("MAX_WAVOUTDRV reached !\n");
1399         return MMSYSERR_BADDEVICEID;
1400     }
1401
1402     memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1403     return MMSYSERR_NOERROR;
1404 }
1405
1406 /**************************************************************************
1407  *                              wodOpen                         [internal]
1408  */
1409 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1410 {
1411     WINE_WAVEOUT*               wwo;
1412     snd_pcm_hw_params_t *       hw_params;
1413     snd_pcm_sw_params_t *       sw_params;
1414     snd_pcm_access_t            access;
1415     snd_pcm_format_t            format;
1416     int                         rate;
1417     unsigned int                buffer_time = 500000;
1418     unsigned int                period_time = 10000;
1419     int                         buffer_size;
1420     snd_pcm_uframes_t           period_size;
1421     int                         flags;
1422     snd_pcm_t *                 pcm;
1423     int                         err;
1424
1425     snd_pcm_hw_params_alloca(&hw_params);
1426     snd_pcm_sw_params_alloca(&sw_params);
1427
1428     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
1429     if (lpDesc == NULL) {
1430         WARN("Invalid Parameter !\n");
1431         return MMSYSERR_INVALPARAM;
1432     }
1433     if (wDevID >= MAX_WAVEOUTDRV) {
1434         TRACE("MAX_WAVOUTDRV reached !\n");
1435         return MMSYSERR_BADDEVICEID;
1436     }
1437
1438     /* only PCM format is supported so far... */
1439     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1440         lpDesc->lpFormat->nChannels == 0 ||
1441         lpDesc->lpFormat->nSamplesPerSec == 0 ||
1442         (lpDesc->lpFormat->wBitsPerSample!=8 && lpDesc->lpFormat->wBitsPerSample!=16)) {
1443         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1444              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1445              lpDesc->lpFormat->nSamplesPerSec);
1446         return WAVERR_BADFORMAT;
1447     }
1448
1449     if (dwFlags & WAVE_FORMAT_QUERY) {
1450         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1451              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1452              lpDesc->lpFormat->nSamplesPerSec);
1453         return MMSYSERR_NOERROR;
1454     }
1455
1456     wwo = &WOutDev[wDevID];
1457
1458     if ((dwFlags & WAVE_DIRECTSOUND) && !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
1459         /* not supported, ignore it */
1460         dwFlags &= ~WAVE_DIRECTSOUND;
1461
1462     wwo->p_handle = 0;
1463     flags = SND_PCM_NONBLOCK;
1464     if ( dwFlags & WAVE_DIRECTSOUND )
1465         flags |= SND_PCM_ASYNC;
1466
1467     if ( (err = snd_pcm_open(&pcm, wwo->device, SND_PCM_STREAM_PLAYBACK, flags)) < 0)
1468     {
1469         ERR("Error open: %s\n", snd_strerror(err));
1470         return MMSYSERR_NOTENABLED;
1471     }
1472
1473     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1474
1475     memcpy(&wwo->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
1476     memcpy(&wwo->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1477
1478     if (wwo->format.wBitsPerSample == 0) {
1479         WARN("Resetting zeroed wBitsPerSample\n");
1480         wwo->format.wBitsPerSample = 8 *
1481             (wwo->format.wf.nAvgBytesPerSec /
1482              wwo->format.wf.nSamplesPerSec) /
1483             wwo->format.wf.nChannels;
1484     }
1485
1486     snd_pcm_hw_params_any(pcm, hw_params);
1487
1488 #define EXIT_ON_ERROR(f,e,txt) do \
1489 { \
1490     int err; \
1491     if ( (err = (f) ) < 0) \
1492     { \
1493         ERR(txt ": %s\n", snd_strerror(err)); \
1494         snd_pcm_close(pcm); \
1495         return e; \
1496     } \
1497 } while(0)
1498
1499     access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
1500     if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
1501         WARN("mmap not available. switching to standard write.\n");
1502         access = SND_PCM_ACCESS_RW_INTERLEAVED;
1503         EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
1504         wwo->write = snd_pcm_writei;
1505     }
1506     else
1507         wwo->write = snd_pcm_mmap_writei;
1508
1509     EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwo->format.wf.nChannels), MMSYSERR_INVALPARAM, "unable to set required channels");
1510
1511     format = (wwo->format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE : SND_PCM_FORMAT_U8;
1512     EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), MMSYSERR_INVALPARAM, "unable to set required format");
1513
1514     rate = snd_pcm_hw_params_set_rate_near(pcm, hw_params, wwo->format.wf.nSamplesPerSec, 0);
1515     if (rate < 0) {
1516         ERR("Rate %ld Hz not available for playback: %s\n", wwo->format.wf.nSamplesPerSec, snd_strerror(rate));
1517         snd_pcm_close(pcm);
1518         return WAVERR_BADFORMAT;
1519     }
1520     if (rate != wwo->format.wf.nSamplesPerSec) {
1521         ERR("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwo->format.wf.nSamplesPerSec, rate);
1522         snd_pcm_close(pcm);
1523         return WAVERR_BADFORMAT;
1524     }
1525     
1526     EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, buffer_time, 0), MMSYSERR_INVALPARAM, "unable to set buffer time");
1527     EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, period_time, 0), MMSYSERR_INVALPARAM, "unable to set period time");
1528
1529     EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
1530     
1531     period_size = snd_pcm_hw_params_get_period_size(hw_params, 0);
1532     buffer_size = snd_pcm_hw_params_get_buffer_size(hw_params);
1533
1534     snd_pcm_sw_params_current(pcm, sw_params);
1535     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");
1536     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
1537     EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
1538     EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
1539     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
1540     EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
1541 #undef EXIT_ON_ERROR
1542
1543     snd_pcm_prepare(pcm);
1544
1545     if (TRACE_ON(wave))
1546         ALSA_TraceParameters(hw_params, sw_params, FALSE);
1547
1548     /* now, we can save all required data for later use... */
1549     if ( wwo->hw_params )
1550         snd_pcm_hw_params_free(wwo->hw_params);
1551     snd_pcm_hw_params_malloc(&(wwo->hw_params));
1552     snd_pcm_hw_params_copy(wwo->hw_params, hw_params);
1553
1554     wwo->dwBufferSize = buffer_size;
1555     wwo->lpQueuePtr = wwo->lpPlayPtr = wwo->lpLoopPtr = NULL;
1556     wwo->p_handle = pcm;
1557
1558     ALSA_InitRingMessage(&wwo->msgRing);
1559
1560     wwo->count = snd_pcm_poll_descriptors_count (wwo->p_handle);
1561     if (wwo->count <= 0) {
1562         ERR("Invalid poll descriptors count\n");
1563         return MMSYSERR_ERROR;
1564     }
1565
1566     wwo->ufds = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct pollfd) * wwo->count);
1567     if (wwo->ufds == NULL) {
1568         ERR("No enough memory\n");
1569         return MMSYSERR_NOMEM;
1570     }
1571     if ((err = snd_pcm_poll_descriptors(wwo->p_handle, wwo->ufds, wwo->count)) < 0) {
1572         ERR("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
1573         return MMSYSERR_ERROR;
1574     }
1575
1576     if (!(dwFlags & WAVE_DIRECTSOUND)) {
1577         wwo->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
1578         wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
1579         WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
1580         CloseHandle(wwo->hStartUpEvent);
1581     } else {
1582         wwo->hThread = INVALID_HANDLE_VALUE;
1583         wwo->dwThreadID = 0;
1584     }
1585     wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
1586
1587     TRACE("handle=%08lx \n", (DWORD)wwo->p_handle);
1588 /*    if (wwo->dwFragmentSize % wwo->format.wf.nBlockAlign)
1589         ERR("Fragment doesn't contain an integral number of data blocks\n");
1590 */
1591     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
1592           wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec,
1593           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
1594           wwo->format.wf.nBlockAlign);
1595
1596     return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
1597 }
1598
1599
1600 /**************************************************************************
1601  *                              wodClose                        [internal]
1602  */
1603 static DWORD wodClose(WORD wDevID)
1604 {
1605     DWORD               ret = MMSYSERR_NOERROR;
1606     WINE_WAVEOUT*       wwo;
1607
1608     TRACE("(%u);\n", wDevID);
1609
1610     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1611         WARN("bad device ID !\n");
1612         return MMSYSERR_BADDEVICEID;
1613     }
1614
1615     wwo = &WOutDev[wDevID];
1616     if (wwo->lpQueuePtr) {
1617         WARN("buffers still playing !\n");
1618         ret = WAVERR_STILLPLAYING;
1619     } else {
1620         if (wwo->hThread != INVALID_HANDLE_VALUE) {
1621             ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1622         }
1623         ALSA_DestroyRingMessage(&wwo->msgRing);
1624
1625         snd_pcm_hw_params_free(wwo->hw_params);
1626         wwo->hw_params = NULL;
1627
1628         snd_pcm_close(wwo->p_handle);
1629         wwo->p_handle = NULL;
1630
1631         ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1632     }
1633
1634     HeapFree(GetProcessHeap(), 0, wwo->ufds);
1635     return ret;
1636 }
1637
1638
1639 /**************************************************************************
1640  *                              wodWrite                        [internal]
1641  *
1642  */
1643 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1644 {
1645     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1646
1647     /* first, do the sanity checks... */
1648     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1649         WARN("bad dev ID !\n");
1650         return MMSYSERR_BADDEVICEID;
1651     }
1652
1653     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1654         return WAVERR_UNPREPARED;
1655
1656     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1657         return WAVERR_STILLPLAYING;
1658
1659     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1660     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1661     lpWaveHdr->lpNext = 0;
1662
1663     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1664
1665     return MMSYSERR_NOERROR;
1666 }
1667
1668 /**************************************************************************
1669  *                              wodPrepare                      [internal]
1670  */
1671 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1672 {
1673     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1674
1675     if (wDevID >= MAX_WAVEOUTDRV) {
1676         WARN("bad device ID !\n");
1677         return MMSYSERR_BADDEVICEID;
1678     }
1679
1680     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1681         return WAVERR_STILLPLAYING;
1682
1683     lpWaveHdr->dwFlags |= WHDR_PREPARED;
1684     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1685     return MMSYSERR_NOERROR;
1686 }
1687
1688 /**************************************************************************
1689  *                              wodUnprepare                    [internal]
1690  */
1691 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1692 {
1693     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1694
1695     if (wDevID >= MAX_WAVEOUTDRV) {
1696         WARN("bad device ID !\n");
1697         return MMSYSERR_BADDEVICEID;
1698     }
1699
1700     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1701         return WAVERR_STILLPLAYING;
1702
1703     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1704     lpWaveHdr->dwFlags |= WHDR_DONE;
1705
1706     return MMSYSERR_NOERROR;
1707 }
1708
1709 /**************************************************************************
1710  *                      wodPause                                [internal]
1711  */
1712 static DWORD wodPause(WORD wDevID)
1713 {
1714     TRACE("(%u);!\n", wDevID);
1715
1716     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1717         WARN("bad device ID !\n");
1718         return MMSYSERR_BADDEVICEID;
1719     }
1720
1721     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1722
1723     return MMSYSERR_NOERROR;
1724 }
1725
1726 /**************************************************************************
1727  *                      wodRestart                              [internal]
1728  */
1729 static DWORD wodRestart(WORD wDevID)
1730 {
1731     TRACE("(%u);\n", wDevID);
1732
1733     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1734         WARN("bad device ID !\n");
1735         return MMSYSERR_BADDEVICEID;
1736     }
1737
1738     if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1739         ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1740     }
1741
1742     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1743     /* FIXME: Myst crashes with this ... hmm -MM
1744        return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1745     */
1746
1747     return MMSYSERR_NOERROR;
1748 }
1749
1750 /**************************************************************************
1751  *                      wodReset                                [internal]
1752  */
1753 static DWORD wodReset(WORD wDevID)
1754 {
1755     TRACE("(%u);\n", wDevID);
1756
1757     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1758         WARN("bad device ID !\n");
1759         return MMSYSERR_BADDEVICEID;
1760     }
1761
1762     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1763
1764     return MMSYSERR_NOERROR;
1765 }
1766
1767 /**************************************************************************
1768  *                              wodGetPosition                  [internal]
1769  */
1770 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1771 {
1772     int                 time;
1773     DWORD               val;
1774     WINE_WAVEOUT*       wwo;
1775
1776     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1777
1778     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1779         WARN("bad device ID !\n");
1780         return MMSYSERR_BADDEVICEID;
1781     }
1782
1783     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1784
1785     wwo = &WOutDev[wDevID];
1786     ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1787     val = wwo->dwPlayedTotal;
1788
1789     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
1790           lpTime->wType, wwo->format.wBitsPerSample,
1791           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
1792           wwo->format.wf.nAvgBytesPerSec);
1793     TRACE("dwPlayedTotal=%lu\n", val);
1794
1795     switch (lpTime->wType) {
1796     case TIME_BYTES:
1797         lpTime->u.cb = val;
1798         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
1799         break;
1800     case TIME_SAMPLES:
1801         lpTime->u.sample = val * 8 / wwo->format.wBitsPerSample /wwo->format.wf.nChannels;
1802         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
1803         break;
1804     case TIME_SMPTE:
1805         time = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1806         lpTime->u.smpte.hour = time / (60 * 60 * 1000);
1807         time -= lpTime->u.smpte.hour * (60 * 60 * 1000);
1808         lpTime->u.smpte.min = time / (60 * 1000);
1809         time -= lpTime->u.smpte.min * (60 * 1000);
1810         lpTime->u.smpte.sec = time / 1000;
1811         time -= lpTime->u.smpte.sec * 1000;
1812         lpTime->u.smpte.frame = time * 30 / 1000;
1813         lpTime->u.smpte.fps = 30;
1814         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
1815               lpTime->u.smpte.hour, lpTime->u.smpte.min,
1816               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
1817         break;
1818     default:
1819         FIXME("Format %d not supported ! use TIME_MS !\n", lpTime->wType);
1820         lpTime->wType = TIME_MS;
1821     case TIME_MS:
1822         lpTime->u.ms = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1823         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
1824         break;
1825     }
1826     return MMSYSERR_NOERROR;
1827 }
1828
1829 /**************************************************************************
1830  *                              wodBreakLoop                    [internal]
1831  */
1832 static DWORD wodBreakLoop(WORD wDevID)
1833 {
1834     TRACE("(%u);\n", wDevID);
1835
1836     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1837         WARN("bad device ID !\n");
1838         return MMSYSERR_BADDEVICEID;
1839     }
1840     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
1841     return MMSYSERR_NOERROR;
1842 }
1843
1844 /**************************************************************************
1845  *                              wodGetVolume                    [internal]
1846  */
1847 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1848 {
1849     WORD               left, right;
1850     WINE_WAVEOUT*      wwo;
1851     int                count;
1852     long               min, max;
1853
1854     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1855     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1856         WARN("bad device ID !\n");
1857         return MMSYSERR_BADDEVICEID;
1858     }
1859     wwo = &WOutDev[wDevID];
1860     count = snd_ctl_elem_info_get_count(wwo->playback_einfo);
1861     min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
1862     max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
1863
1864 #define VOLUME_ALSA_TO_WIN(x) (((x)-min) * 65536 /(max-min))
1865     if (lpdwVol == NULL)
1866         return MMSYSERR_NOTENABLED;
1867
1868     switch (count)
1869     {
1870         case 2:
1871             left = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
1872             right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 1));
1873             break;
1874         case 1:
1875             left = right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
1876             break;
1877         default:
1878             WARN("%d channels mixer not supported\n", count);
1879             return MMSYSERR_NOERROR;
1880      }
1881 #undef VOLUME_ALSA_TO_WIN
1882
1883     TRACE("left=%d right=%d !\n", left, right);
1884     *lpdwVol = MAKELONG( left, right );
1885     return MMSYSERR_NOERROR;
1886 }
1887
1888 /**************************************************************************
1889  *                              wodSetVolume                    [internal]
1890  */
1891 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1892 {
1893     WORD               left, right;
1894     WINE_WAVEOUT*      wwo;
1895     int                count, err;
1896     long               min, max;
1897
1898     TRACE("(%u, %08lX);\n", wDevID, dwParam);
1899     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1900         WARN("bad device ID !\n");
1901         return MMSYSERR_BADDEVICEID;
1902     }
1903     wwo = &WOutDev[wDevID];
1904     count=snd_ctl_elem_info_get_count(wwo->playback_einfo);
1905     min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
1906     max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
1907
1908     left  = LOWORD(dwParam);
1909     right = HIWORD(dwParam);
1910
1911 #define VOLUME_WIN_TO_ALSA(x) ( (((x) * (max-min)) / 65536) + min )
1912     switch (count)
1913     {
1914         case 2:
1915             snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
1916             snd_ctl_elem_value_set_integer(wwo->playback_evalue, 1, VOLUME_WIN_TO_ALSA(right));
1917             break;
1918         case 1:
1919             snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
1920             break;
1921         default:
1922             WARN("%d channels mixer not supported\n", count);
1923      }
1924 #undef VOLUME_WIN_TO_ALSA
1925     if ( (err = snd_ctl_elem_write(wwo->ctl, wwo->playback_evalue)) < 0)
1926     {
1927         ERR("error writing snd_ctl_elem_value: %s\n", snd_strerror(err));
1928     }
1929     return MMSYSERR_NOERROR;
1930 }
1931
1932 /**************************************************************************
1933  *                              wodGetNumDevs                   [internal]
1934  */
1935 static  DWORD   wodGetNumDevs(void)
1936 {
1937     return ALSA_WodNumDevs;
1938 }
1939
1940 /**************************************************************************
1941  *                              wodDevInterfaceSize             [internal]
1942  */
1943 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1944 {
1945     TRACE("(%u, %p)\n", wDevID, dwParam1);
1946
1947     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].device, -1,
1948                                     NULL, 0 ) * sizeof(WCHAR);
1949     return MMSYSERR_NOERROR;
1950 }
1951
1952 /**************************************************************************
1953  *                              wodDevInterface                 [internal]
1954  */
1955 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1956 {
1957     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].device, -1,
1958                                         NULL, 0 ) * sizeof(WCHAR))
1959     {
1960         MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].device, -1,
1961                             dwParam1, dwParam2 / sizeof(WCHAR));
1962         return MMSYSERR_NOERROR;
1963     }
1964     return MMSYSERR_INVALPARAM;
1965 }
1966
1967 /**************************************************************************
1968  *                              wodMessage (WINEALSA.@)
1969  */
1970 DWORD WINAPI ALSA_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1971                              DWORD dwParam1, DWORD dwParam2)
1972 {
1973     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
1974           wDevID, wMsg, dwUser, dwParam1, dwParam2);
1975
1976     switch (wMsg) {
1977     case DRVM_INIT:
1978     case DRVM_EXIT:
1979     case DRVM_ENABLE:
1980     case DRVM_DISABLE:
1981         /* FIXME: Pretend this is supported */
1982         return 0;
1983     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1984     case WODM_CLOSE:            return wodClose         (wDevID);
1985     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSA)dwParam1,      dwParam2);
1986     case WODM_GETNUMDEVS:       return wodGetNumDevs    ();
1987     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1988     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1989     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1990     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1991     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1992     case WODM_PAUSE:            return wodPause         (wDevID);
1993     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
1994     case WODM_BREAKLOOP:        return wodBreakLoop     (wDevID);
1995     case WODM_PREPARE:          return wodPrepare       (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1996     case WODM_UNPREPARE:        return wodUnprepare     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1997     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
1998     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
1999     case WODM_RESTART:          return wodRestart       (wDevID);
2000     case WODM_RESET:            return wodReset         (wDevID);
2001     case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
2002     case DRV_QUERYDEVICEINTERFACE:     return wodDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
2003     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate      (wDevID, (PIDSDRIVER*)dwParam1);
2004     case DRV_QUERYDSOUNDDESC:   return wodDsDesc        (wDevID, (PDSDRIVERDESC)dwParam1);
2005     case DRV_QUERYDSOUNDGUID:   return wodDsGuid        (wDevID, (LPGUID)dwParam1);
2006
2007     default:
2008         FIXME("unknown message %d!\n", wMsg);
2009     }
2010     return MMSYSERR_NOTSUPPORTED;
2011 }
2012
2013 /*======================================================================*
2014  *                  Low level DSOUND implementation                     *
2015  *======================================================================*/
2016
2017 typedef struct IDsDriverImpl IDsDriverImpl;
2018 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
2019
2020 struct IDsDriverImpl
2021 {
2022     /* IUnknown fields */
2023     ICOM_VFIELD(IDsDriver);
2024     DWORD               ref;
2025     /* IDsDriverImpl fields */
2026     UINT                wDevID;
2027     IDsDriverBufferImpl*primary;
2028 };
2029
2030 struct IDsDriverBufferImpl
2031 {
2032     /* IUnknown fields */
2033     ICOM_VFIELD(IDsDriverBuffer);
2034     DWORD                     ref;
2035     /* IDsDriverBufferImpl fields */
2036     IDsDriverImpl*            drv;
2037
2038     CRITICAL_SECTION          mmap_crst;
2039     LPVOID                    mmap_buffer;
2040     DWORD                     mmap_buflen_bytes;
2041     snd_pcm_uframes_t         mmap_buflen_frames;
2042     snd_pcm_channel_area_t *  mmap_areas;
2043     snd_async_handler_t *     mmap_async_handler;
2044 };
2045
2046 static void DSDB_CheckXRUN(IDsDriverBufferImpl* pdbi)
2047 {
2048     WINE_WAVEOUT *     wwo = &(WOutDev[pdbi->drv->wDevID]);
2049     snd_pcm_state_t    state = snd_pcm_state(wwo->p_handle);
2050
2051     if ( state == SND_PCM_STATE_XRUN )
2052     {
2053         int            err = snd_pcm_prepare(wwo->p_handle);
2054         TRACE("xrun occurred\n");
2055         if ( err < 0 )
2056             ERR("recovery from xrun failed, prepare failed: %s\n", snd_strerror(err));
2057     }
2058     else if ( state == SND_PCM_STATE_SUSPENDED )
2059     {
2060         int            err = snd_pcm_resume(wwo->p_handle);
2061         TRACE("recovery from suspension occurred\n");
2062         if (err < 0 && err != -EAGAIN){
2063             err = snd_pcm_prepare(wwo->p_handle);
2064             if (err < 0)
2065                 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
2066         }
2067     }
2068 }
2069
2070 static void DSDB_MMAPCopy(IDsDriverBufferImpl* pdbi)
2071 {
2072     WINE_WAVEOUT *     wwo = &(WOutDev[pdbi->drv->wDevID]);
2073     int                channels;
2074     snd_pcm_format_t   format;
2075     snd_pcm_uframes_t  period_size;
2076     snd_pcm_sframes_t  avail;
2077
2078     if ( !pdbi->mmap_buffer || !wwo->hw_params || !wwo->p_handle)
2079         return;
2080
2081     channels = snd_pcm_hw_params_get_channels(wwo->hw_params);
2082     format = snd_pcm_hw_params_get_format(wwo->hw_params);
2083     period_size = snd_pcm_hw_params_get_period_size(wwo->hw_params, 0);
2084     avail = snd_pcm_avail_update(wwo->p_handle);
2085
2086     DSDB_CheckXRUN(pdbi);
2087
2088     TRACE("avail=%d format=%s channels=%d\n", (int)avail, snd_pcm_format_name(format), channels );
2089
2090     while (avail >= period_size)
2091     {
2092         const snd_pcm_channel_area_t *areas;
2093         snd_pcm_uframes_t     ofs;
2094         snd_pcm_uframes_t     frames;
2095         int                   err;
2096
2097         frames = avail / period_size * period_size; /* round down to a multiple of period_size */
2098
2099         EnterCriticalSection(&pdbi->mmap_crst);
2100
2101         snd_pcm_mmap_begin(wwo->p_handle, &areas, &ofs, &frames);
2102         snd_pcm_areas_copy(areas, ofs, pdbi->mmap_areas, ofs, channels, frames, format);
2103         err = snd_pcm_mmap_commit(wwo->p_handle, ofs, frames);
2104
2105         LeaveCriticalSection(&pdbi->mmap_crst);
2106
2107         if ( err != (snd_pcm_sframes_t) frames)
2108             ERR("mmap partially failed.\n");
2109
2110         avail = snd_pcm_avail_update(wwo->p_handle);
2111     }
2112  }
2113
2114 static void DSDB_PCMCallback(snd_async_handler_t *ahandler)
2115 {
2116     /* snd_pcm_t *               handle = snd_async_handler_get_pcm(ahandler); */
2117     IDsDriverBufferImpl*      pdbi = snd_async_handler_get_callback_private(ahandler);
2118     TRACE("callback called\n");
2119     DSDB_MMAPCopy(pdbi);
2120 }
2121
2122 static int DSDB_CreateMMAP(IDsDriverBufferImpl* pdbi)
2123  {
2124     WINE_WAVEOUT *            wwo = &(WOutDev[pdbi->drv->wDevID]);
2125     snd_pcm_format_t          format = snd_pcm_hw_params_get_format(wwo->hw_params);
2126     snd_pcm_uframes_t         frames = snd_pcm_hw_params_get_buffer_size(wwo->hw_params);
2127     int                       channels = snd_pcm_hw_params_get_channels(wwo->hw_params);
2128     unsigned int              bits_per_sample = snd_pcm_format_physical_width(format);
2129     unsigned int              bits_per_frame = bits_per_sample * channels;
2130     snd_pcm_channel_area_t *  a;
2131     unsigned int              c;
2132     int                       err;
2133
2134     if (TRACE_ON(wave))
2135         ALSA_TraceParameters(wwo->hw_params, NULL, FALSE);
2136
2137     TRACE("format=%s  frames=%ld  channels=%d  bits_per_sample=%d  bits_per_frame=%d\n",
2138           snd_pcm_format_name(format), frames, channels, bits_per_sample, bits_per_frame);
2139
2140     pdbi->mmap_buflen_frames = frames;
2141     pdbi->mmap_buflen_bytes = snd_pcm_frames_to_bytes( wwo->p_handle, frames );
2142     pdbi->mmap_buffer = HeapAlloc(GetProcessHeap(),0,pdbi->mmap_buflen_bytes);
2143     if (!pdbi->mmap_buffer)
2144         return DSERR_OUTOFMEMORY;
2145
2146     snd_pcm_format_set_silence(format, pdbi->mmap_buffer, frames );
2147
2148     TRACE("created mmap buffer of %ld frames (%ld bytes) at %p\n",
2149         frames, pdbi->mmap_buflen_bytes, pdbi->mmap_buffer);
2150
2151     pdbi->mmap_areas = HeapAlloc(GetProcessHeap(),0,channels*sizeof(snd_pcm_channel_area_t));
2152     if (!pdbi->mmap_areas)
2153         return DSERR_OUTOFMEMORY;
2154
2155     a = pdbi->mmap_areas;
2156     for (c = 0; c < channels; c++, a++)
2157     {
2158         a->addr = pdbi->mmap_buffer;
2159         a->first = bits_per_sample * c;
2160         a->step = bits_per_frame;
2161         TRACE("Area %d: addr=%p  first=%d  step=%d\n", c, a->addr, a->first, a->step);
2162     }
2163
2164     InitializeCriticalSection(&pdbi->mmap_crst);
2165
2166     err = snd_async_add_pcm_handler(&pdbi->mmap_async_handler, wwo->p_handle, DSDB_PCMCallback, pdbi);
2167     if ( err < 0 )
2168      {
2169         ERR("add_pcm_handler failed. reason: %s\n", snd_strerror(err));
2170         return DSERR_GENERIC;
2171      }
2172
2173     return DS_OK;
2174  }
2175
2176 static void DSDB_DestroyMMAP(IDsDriverBufferImpl* pdbi)
2177 {
2178     TRACE("mmap buffer %p destroyed\n", pdbi->mmap_buffer);
2179     HeapFree(GetProcessHeap(), 0, pdbi->mmap_areas);
2180     HeapFree(GetProcessHeap(), 0, pdbi->mmap_buffer);
2181     pdbi->mmap_areas = NULL;
2182     pdbi->mmap_buffer = NULL;
2183     DeleteCriticalSection(&pdbi->mmap_crst);
2184 }
2185
2186
2187 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
2188 {
2189     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2190     FIXME("(): stub!\n");
2191     return DSERR_UNSUPPORTED;
2192 }
2193
2194 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
2195 {
2196     ICOM_THIS(IDsDriverBufferImpl,iface);
2197     TRACE("(%p)\n",iface);
2198     return ++This->ref;
2199 }
2200
2201 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
2202 {
2203     ICOM_THIS(IDsDriverBufferImpl,iface);
2204     TRACE("(%p)\n",iface);
2205     if (--This->ref)
2206         return This->ref;
2207     if (This == This->drv->primary)
2208         This->drv->primary = NULL;
2209     DSDB_DestroyMMAP(This);
2210     HeapFree(GetProcessHeap(), 0, This);
2211     return 0;
2212 }
2213
2214 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
2215                                                LPVOID*ppvAudio1,LPDWORD pdwLen1,
2216                                                LPVOID*ppvAudio2,LPDWORD pdwLen2,
2217                                                DWORD dwWritePosition,DWORD dwWriteLen,
2218                                                DWORD dwFlags)
2219 {
2220     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2221     TRACE("(%p)\n",iface);
2222     return DSERR_UNSUPPORTED;
2223 }
2224
2225 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
2226                                                  LPVOID pvAudio1,DWORD dwLen1,
2227                                                  LPVOID pvAudio2,DWORD dwLen2)
2228 {
2229     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2230     TRACE("(%p)\n",iface);
2231     return DSERR_UNSUPPORTED;
2232 }
2233
2234 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
2235                                                     LPWAVEFORMATEX pwfx)
2236 {
2237     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2238     TRACE("(%p,%p)\n",iface,pwfx);
2239     return DSERR_BUFFERLOST;
2240 }
2241
2242 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
2243 {
2244     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2245     TRACE("(%p,%ld): stub\n",iface,dwFreq);
2246     return DSERR_UNSUPPORTED;
2247 }
2248
2249 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
2250 {
2251     DWORD vol;
2252     ICOM_THIS(IDsDriverBufferImpl,iface);
2253     TRACE("(%p,%p)\n",iface,pVolPan);
2254     vol = pVolPan->dwTotalLeftAmpFactor | (pVolPan->dwTotalRightAmpFactor << 16);
2255                                                                                 
2256     if (wodSetVolume(This->drv->wDevID, vol) != MMSYSERR_NOERROR) {
2257         WARN("wodSetVolume failed\n");
2258         return DSERR_INVALIDPARAM;
2259     }
2260
2261     return DS_OK;
2262 }
2263
2264 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
2265 {
2266     /* ICOM_THIS(IDsDriverImpl,iface); */
2267     TRACE("(%p,%ld): stub\n",iface,dwNewPos);
2268     return DSERR_UNSUPPORTED;
2269 }
2270
2271 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
2272                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
2273 {
2274     ICOM_THIS(IDsDriverBufferImpl,iface);
2275     WINE_WAVEOUT *      wwo = &(WOutDev[This->drv->wDevID]);
2276     snd_pcm_uframes_t   hw_ptr;
2277     snd_pcm_uframes_t   period_size;
2278
2279     if (wwo->hw_params == NULL) return DSERR_GENERIC;
2280
2281     period_size  = snd_pcm_hw_params_get_period_size(wwo->hw_params, 0);
2282
2283     if (wwo->p_handle == NULL) return DSERR_GENERIC;
2284     /** we need to track down buffer underruns */
2285     DSDB_CheckXRUN(This);
2286
2287     EnterCriticalSection(&This->mmap_crst);
2288     hw_ptr = _snd_pcm_mmap_hw_ptr(wwo->p_handle);
2289     if (lpdwPlay)
2290         *lpdwPlay = snd_pcm_frames_to_bytes(wwo->p_handle, hw_ptr/ period_size  * period_size) % This->mmap_buflen_bytes;
2291     if (lpdwWrite)
2292         *lpdwWrite = snd_pcm_frames_to_bytes(wwo->p_handle, (hw_ptr / period_size + 1) * period_size ) % This->mmap_buflen_bytes;
2293     LeaveCriticalSection(&This->mmap_crst);
2294
2295     TRACE("hw_ptr=0x%08x, playpos=%ld, writepos=%ld\n", (unsigned int)hw_ptr, lpdwPlay?*lpdwPlay:-1, lpdwWrite?*lpdwWrite:-1);
2296     return DS_OK;
2297 }
2298
2299 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
2300 {
2301     ICOM_THIS(IDsDriverBufferImpl,iface);
2302     WINE_WAVEOUT *       wwo = &(WOutDev[This->drv->wDevID]);
2303     snd_pcm_state_t      state;
2304     int                  err;
2305
2306     TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
2307
2308     if (wwo->p_handle == NULL) return DSERR_GENERIC;
2309
2310     state = snd_pcm_state(wwo->p_handle);
2311     if ( state == SND_PCM_STATE_SETUP )
2312     {
2313         err = snd_pcm_prepare(wwo->p_handle);
2314         state = snd_pcm_state(wwo->p_handle);
2315     }
2316     if ( state == SND_PCM_STATE_PREPARED )
2317      {
2318         DSDB_MMAPCopy(This);
2319         err = snd_pcm_start(wwo->p_handle);
2320      }
2321     return DS_OK;
2322 }
2323
2324 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
2325 {
2326     ICOM_THIS(IDsDriverBufferImpl,iface);
2327     WINE_WAVEOUT *    wwo = &(WOutDev[This->drv->wDevID]);
2328     int               err;
2329     DWORD             play;
2330     DWORD             write;
2331
2332     TRACE("(%p)\n",iface);
2333
2334     if (wwo->p_handle == NULL) return DSERR_GENERIC;
2335
2336     /* ring buffer wrap up detection */
2337     IDsDriverBufferImpl_GetPosition(iface, &play, &write);
2338     if ( play > write)
2339     {
2340         TRACE("writepos wrapper up\n");
2341         return DS_OK;
2342     }
2343
2344     if ( ( err = snd_pcm_drop(wwo->p_handle)) < 0 )
2345     {
2346         ERR("error while stopping pcm: %s\n", snd_strerror(err));
2347         return DSERR_GENERIC;
2348     }
2349     return DS_OK;
2350 }
2351
2352 static ICOM_VTABLE(IDsDriverBuffer) dsdbvt =
2353 {
2354     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
2355     IDsDriverBufferImpl_QueryInterface,
2356     IDsDriverBufferImpl_AddRef,
2357     IDsDriverBufferImpl_Release,
2358     IDsDriverBufferImpl_Lock,
2359     IDsDriverBufferImpl_Unlock,
2360     IDsDriverBufferImpl_SetFormat,
2361     IDsDriverBufferImpl_SetFrequency,
2362     IDsDriverBufferImpl_SetVolumePan,
2363     IDsDriverBufferImpl_SetPosition,
2364     IDsDriverBufferImpl_GetPosition,
2365     IDsDriverBufferImpl_Play,
2366     IDsDriverBufferImpl_Stop
2367 };
2368
2369 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
2370 {
2371     /* ICOM_THIS(IDsDriverImpl,iface); */
2372     FIXME("(%p): stub!\n",iface);
2373     return DSERR_UNSUPPORTED;
2374 }
2375
2376 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
2377 {
2378     ICOM_THIS(IDsDriverImpl,iface);
2379     TRACE("(%p)\n",iface);
2380     This->ref++;
2381     return This->ref;
2382 }
2383
2384 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
2385 {
2386     ICOM_THIS(IDsDriverImpl,iface);
2387     TRACE("(%p)\n",iface);
2388     if (--This->ref)
2389         return This->ref;
2390     HeapFree(GetProcessHeap(),0,This);
2391     return 0;
2392 }
2393
2394 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
2395 {
2396     ICOM_THIS(IDsDriverImpl,iface);
2397     TRACE("(%p,%p)\n",iface,pDesc);
2398     memcpy(pDesc, &(WOutDev[This->wDevID].ds_desc), sizeof(DSDRIVERDESC));
2399     pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
2400         DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK;
2401     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
2402     pDesc->wVxdId               = 0;
2403     pDesc->wReserved            = 0;
2404     pDesc->ulDeviceNum          = This->wDevID;
2405     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
2406     pDesc->pvDirectDrawHeap     = NULL;
2407     pDesc->dwMemStartAddress    = 0;
2408     pDesc->dwMemEndAddress      = 0;
2409     pDesc->dwMemAllocExtra      = 0;
2410     pDesc->pvReserved1          = NULL;
2411     pDesc->pvReserved2          = NULL;
2412     return DS_OK;
2413 }
2414
2415 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
2416 {
2417     /* ICOM_THIS(IDsDriverImpl,iface); */
2418     TRACE("(%p)\n",iface);
2419     return DS_OK;
2420 }
2421
2422 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
2423 {
2424     /* ICOM_THIS(IDsDriverImpl,iface); */
2425     TRACE("(%p)\n",iface);
2426     return DS_OK;
2427 }
2428
2429 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
2430 {
2431     ICOM_THIS(IDsDriverImpl,iface);
2432     TRACE("(%p,%p)\n",iface,pCaps);
2433     memset(pCaps, 0, sizeof(*pCaps));
2434
2435     pCaps->dwFlags = DSCAPS_PRIMARYMONO;
2436     if ( WOutDev[This->wDevID].caps.wChannels == 2 )
2437         pCaps->dwFlags |= DSCAPS_PRIMARYSTEREO;
2438
2439     if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 ) )
2440         pCaps->dwFlags |= DSCAPS_PRIMARY8BIT;
2441
2442     if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S16 | WAVE_FORMAT_2S16 | WAVE_FORMAT_4S16))
2443         pCaps->dwFlags |= DSCAPS_PRIMARY16BIT;
2444
2445     pCaps->dwPrimaryBuffers = 1;
2446     TRACE("caps=0x%X\n",(unsigned int)pCaps->dwFlags);
2447     pCaps->dwMinSecondarySampleRate = DSBFREQUENCY_MIN;
2448     pCaps->dwMaxSecondarySampleRate = DSBFREQUENCY_MAX;
2449
2450     /* the other fields only apply to secondary buffers, which we don't support
2451      * (unless we want to mess with wavetable synthesizers and MIDI) */
2452     return DS_OK;
2453 }
2454
2455 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
2456                                                       LPWAVEFORMATEX pwfx,
2457                                                       DWORD dwFlags, DWORD dwCardAddress,
2458                                                       LPDWORD pdwcbBufferSize,
2459                                                       LPBYTE *ppbBuffer,
2460                                                       LPVOID *ppvObj)
2461 {
2462     ICOM_THIS(IDsDriverImpl,iface);
2463     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
2464     int err;
2465
2466     TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
2467     /* we only support primary buffers */
2468     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
2469         return DSERR_UNSUPPORTED;
2470     if (This->primary)
2471         return DSERR_ALLOCATED;
2472     if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
2473         return DSERR_CONTROLUNAVAIL;
2474
2475     *ippdsdb = (IDsDriverBufferImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
2476     if (*ippdsdb == NULL)
2477         return DSERR_OUTOFMEMORY;
2478     (*ippdsdb)->lpVtbl  = &dsdbvt;
2479     (*ippdsdb)->ref     = 1;
2480     (*ippdsdb)->drv     = This;
2481
2482     err = DSDB_CreateMMAP((*ippdsdb));
2483     if ( err != DS_OK )
2484      {
2485         HeapFree(GetProcessHeap(), 0, *ippdsdb);
2486         *ippdsdb = NULL;
2487         return err;
2488      }
2489     *ppbBuffer = (*ippdsdb)->mmap_buffer;
2490     *pdwcbBufferSize = (*ippdsdb)->mmap_buflen_bytes;
2491
2492     This->primary = *ippdsdb;
2493
2494     /* buffer is ready to go */
2495     TRACE("buffer created at %p\n", *ippdsdb);
2496     return DS_OK;
2497 }
2498
2499 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
2500                                                          PIDSDRIVERBUFFER pBuffer,
2501                                                          LPVOID *ppvObj)
2502 {
2503     /* ICOM_THIS(IDsDriverImpl,iface); */
2504     TRACE("(%p,%p): stub\n",iface,pBuffer);
2505     return DSERR_INVALIDCALL;
2506 }
2507
2508 static ICOM_VTABLE(IDsDriver) dsdvt =
2509 {
2510     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
2511     IDsDriverImpl_QueryInterface,
2512     IDsDriverImpl_AddRef,
2513     IDsDriverImpl_Release,
2514     IDsDriverImpl_GetDriverDesc,
2515     IDsDriverImpl_Open,
2516     IDsDriverImpl_Close,
2517     IDsDriverImpl_GetCaps,
2518     IDsDriverImpl_CreateSoundBuffer,
2519     IDsDriverImpl_DuplicateSoundBuffer
2520 };
2521
2522 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
2523 {
2524     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
2525
2526     TRACE("driver created\n");
2527
2528     /* the HAL isn't much better than the HEL if we can't do mmap() */
2529     if (!(WOutDev[wDevID].caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
2530         ERR("DirectSound flag not set\n");
2531         MESSAGE("This sound card's driver does not support direct access\n");
2532         MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
2533         return MMSYSERR_NOTSUPPORTED;
2534     }
2535
2536     *idrv = (IDsDriverImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
2537     if (!*idrv)
2538         return MMSYSERR_NOMEM;
2539     (*idrv)->lpVtbl     = &dsdvt;
2540     (*idrv)->ref        = 1;
2541
2542     (*idrv)->wDevID     = wDevID;
2543     (*idrv)->primary    = NULL;
2544     return MMSYSERR_NOERROR;
2545 }
2546
2547 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2548 {
2549     memcpy(desc, &(WOutDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
2550     return MMSYSERR_NOERROR;
2551 }
2552
2553 static DWORD wodDsGuid(UINT wDevID, LPGUID pGuid)
2554 {
2555     TRACE("(%d,%p)\n",wDevID,pGuid);
2556
2557     memcpy(pGuid, &(WOutDev[wDevID].ds_guid), sizeof(GUID));
2558
2559     return MMSYSERR_NOERROR;
2560 }
2561
2562 /*======================================================================*
2563 *                  Low level WAVE IN implementation                     *
2564 *======================================================================*/
2565
2566 /**************************************************************************
2567 *                       widNotifyClient                 [internal]
2568 */
2569 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
2570 {
2571    TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
2572
2573    switch (wMsg) {
2574    case WIM_OPEN:
2575    case WIM_CLOSE:
2576    case WIM_DATA:
2577        if (wwi->wFlags != DCB_NULL &&
2578            !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags, (HDRVR)wwi->waveDesc.hWave,
2579                            wMsg, wwi->waveDesc.dwInstance, dwParam1, dwParam2)) {
2580            WARN("can't notify client !\n");
2581            return MMSYSERR_ERROR;
2582        }
2583        break;
2584    default:
2585        FIXME("Unknown callback message %u\n", wMsg);
2586        return MMSYSERR_INVALPARAM;
2587    }
2588    return MMSYSERR_NOERROR;
2589 }
2590
2591 /**************************************************************************
2592  *                      widGetDevCaps                           [internal]
2593  */
2594 static DWORD widGetDevCaps(WORD wDevID, LPWAVEOUTCAPSA lpCaps, DWORD dwSize)
2595 {
2596     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
2597
2598     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
2599
2600     if (wDevID >= MAX_WAVEINDRV) {
2601         TRACE("MAX_WAVOUTDRV reached !\n");
2602         return MMSYSERR_BADDEVICEID;
2603     }
2604
2605     memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
2606     return MMSYSERR_NOERROR;
2607 }
2608
2609 /**************************************************************************
2610  *                              widRecorder_ReadHeaders         [internal]
2611  */
2612 static void widRecorder_ReadHeaders(WINE_WAVEIN * wwi)
2613 {
2614     enum win_wm_message tmp_msg;
2615     DWORD               tmp_param;
2616     HANDLE              tmp_ev;
2617     WAVEHDR*            lpWaveHdr;
2618
2619     while (ALSA_RetrieveRingMessage(&wwi->msgRing, &tmp_msg, &tmp_param, &tmp_ev)) {
2620         if (tmp_msg == WINE_WM_HEADER) {
2621             LPWAVEHDR*  wh;
2622             lpWaveHdr = (LPWAVEHDR)tmp_param;
2623             lpWaveHdr->lpNext = 0;
2624
2625             if (wwi->lpQueuePtr == 0)
2626                 wwi->lpQueuePtr = lpWaveHdr;
2627             else {
2628                 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2629                 *wh = lpWaveHdr;
2630             }
2631         } else {
2632             ERR("should only have headers left\n");
2633         }
2634     }
2635 }
2636
2637 /**************************************************************************
2638  *                              widRecorder                     [internal]
2639  */
2640 static  DWORD   CALLBACK        widRecorder(LPVOID pmt)
2641 {
2642     WORD                uDevID = (DWORD)pmt;
2643     WINE_WAVEIN*        wwi = (WINE_WAVEIN*)&WInDev[uDevID];
2644     WAVEHDR*            lpWaveHdr;
2645     DWORD               dwSleepTime;
2646     DWORD               bytesRead;
2647     LPVOID              buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, wwi->dwPeriodSize);
2648     char               *pOffset = buffer;
2649     enum win_wm_message msg;
2650     DWORD               param;
2651     HANDLE              ev;
2652     DWORD               frames_per_period;
2653
2654     wwi->state = WINE_WS_STOPPED;
2655     wwi->dwTotalRecorded = 0;
2656     wwi->lpQueuePtr = NULL;
2657
2658     SetEvent(wwi->hStartUpEvent);
2659
2660     /* make sleep time to be # of ms to output a period */
2661     dwSleepTime = (1024/*wwi-dwPeriodSize => overrun!*/ * 1000) / wwi->format.wf.nAvgBytesPerSec;
2662     frames_per_period = snd_pcm_bytes_to_frames(wwi->p_handle, wwi->dwPeriodSize); 
2663     TRACE("sleeptime=%ld ms\n", dwSleepTime);
2664
2665     for (;;) {
2666         /* wait for dwSleepTime or an event in thread's queue */
2667         /* FIXME: could improve wait time depending on queue state,
2668          * ie, number of queued fragments
2669          */
2670         if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
2671         {
2672             int periods;
2673             DWORD frames;
2674             DWORD bytes;
2675             DWORD read;
2676
2677             lpWaveHdr = wwi->lpQueuePtr;
2678             /* read all the fragments accumulated so far */
2679             frames = snd_pcm_avail_update(wwi->p_handle);
2680             bytes = snd_pcm_frames_to_bytes(wwi->p_handle, frames);
2681             TRACE("frames = %ld  bytes = %ld\n", frames, bytes);
2682             periods = bytes / wwi->dwPeriodSize;
2683             while ((periods > 0) && (wwi->lpQueuePtr))
2684             {
2685                 periods--;
2686                 bytes = wwi->dwPeriodSize;
2687                 TRACE("bytes = %ld\n",bytes);
2688                 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwPeriodSize)
2689                 {
2690                     /* directly read fragment in wavehdr */
2691                     read = wwi->read(wwi->p_handle, lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded, frames_per_period);
2692                     bytesRead = snd_pcm_frames_to_bytes(wwi->p_handle, read);
2693                         
2694                     TRACE("bytesRead=%ld (direct)\n", bytesRead);
2695                     if (bytesRead != (DWORD) -1)
2696                     {
2697                         /* update number of bytes recorded in current buffer and by this device */
2698                         lpWaveHdr->dwBytesRecorded += bytesRead;
2699                         wwi->dwTotalRecorded       += bytesRead;
2700
2701                         /* buffer is full. notify client */
2702                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2703                         {
2704                             /* must copy the value of next waveHdr, because we have no idea of what
2705                              * will be done with the content of lpWaveHdr in callback
2706                              */
2707                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
2708
2709                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2710                             lpWaveHdr->dwFlags |=  WHDR_DONE;
2711
2712                             wwi->lpQueuePtr = lpNext;
2713                             widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2714                             lpWaveHdr = lpNext;
2715                         }
2716                     }
2717                 }
2718                 else
2719                 {
2720                     /* read the fragment in a local buffer */
2721                     read = wwi->read(wwi->p_handle, buffer, frames_per_period);
2722                     bytesRead = snd_pcm_frames_to_bytes(wwi->p_handle, read);
2723                     pOffset = buffer;
2724
2725                     TRACE("bytesRead=%ld (local)\n", bytesRead);
2726
2727                     /* copy data in client buffers */
2728                     while (bytesRead != (DWORD) -1 && bytesRead > 0)
2729                     {
2730                         DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
2731
2732                         memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2733                                pOffset,
2734                                dwToCopy);
2735
2736                         /* update number of bytes recorded in current buffer and by this device */
2737                         lpWaveHdr->dwBytesRecorded += dwToCopy;
2738                         wwi->dwTotalRecorded += dwToCopy;
2739                         bytesRead -= dwToCopy;
2740                         pOffset   += dwToCopy;
2741
2742                         /* client buffer is full. notify client */
2743                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2744                         {
2745                             /* must copy the value of next waveHdr, because we have no idea of what
2746                              * will be done with the content of lpWaveHdr in callback
2747                              */
2748                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
2749                             TRACE("lpNext=%p\n", lpNext);
2750
2751                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2752                             lpWaveHdr->dwFlags |=  WHDR_DONE;
2753
2754                             wwi->lpQueuePtr = lpNext;
2755                             widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2756
2757                             lpWaveHdr = lpNext;
2758                             if (!lpNext && bytesRead) {
2759                                 /* before we give up, check for more header messages */
2760                                 while (ALSA_PeekRingMessage(&wwi->msgRing, &msg, &param, &ev))
2761                                 {
2762                                     if (msg == WINE_WM_HEADER) {
2763                                         LPWAVEHDR hdr;
2764                                         ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev);
2765                                         hdr = ((LPWAVEHDR)param);
2766                                         TRACE("msg = %s, hdr = %p, ev = %p\n", wodPlayerCmdString[msg - WM_USER - 1], hdr, ev);
2767                                         hdr->lpNext = 0;
2768                                         if (lpWaveHdr == 0) {
2769                                             /* new head of queue */
2770                                             wwi->lpQueuePtr = lpWaveHdr = hdr;
2771                                         } else {
2772                                             /* insert buffer at the end of queue */
2773                                             LPWAVEHDR*  wh;
2774                                             for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2775                                             *wh = hdr;
2776                                         }
2777                                     } else
2778                                         break;
2779                                 }
2780
2781                                 if (lpWaveHdr == 0) {
2782                                     /* no more buffer to copy data to, but we did read more.
2783                                      * what hasn't been copied will be dropped
2784                                      */
2785                                     WARN("buffer under run! %lu bytes dropped.\n", bytesRead);
2786                                     wwi->lpQueuePtr = NULL;
2787                                     break;
2788                                 }
2789                             }
2790                         }
2791                     }
2792                 }
2793             }
2794         }
2795
2796         WAIT_OMR(&wwi->msgRing, dwSleepTime);
2797
2798         while (ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev))
2799         {
2800             TRACE("msg=%s param=0x%lx\n", wodPlayerCmdString[msg - WM_USER - 1], param);
2801             switch (msg) {
2802             case WINE_WM_PAUSING:
2803                 wwi->state = WINE_WS_PAUSED;
2804                 /*FIXME("Device should stop recording\n");*/
2805                 SetEvent(ev);
2806                 break;
2807             case WINE_WM_STARTING:
2808                 wwi->state = WINE_WS_PLAYING;
2809                 snd_pcm_start(wwi->p_handle);
2810                 SetEvent(ev);
2811                 break;
2812             case WINE_WM_HEADER:
2813                 lpWaveHdr = (LPWAVEHDR)param;
2814                 lpWaveHdr->lpNext = 0;
2815
2816                 /* insert buffer at the end of queue */
2817                 {
2818                     LPWAVEHDR*  wh;
2819                     for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2820                     *wh = lpWaveHdr;
2821                 }
2822                 break;
2823             case WINE_WM_STOPPING:
2824                 if (wwi->state != WINE_WS_STOPPED)
2825                 {
2826                     snd_pcm_drain(wwi->p_handle);
2827
2828                     /* read any headers in queue */
2829                     widRecorder_ReadHeaders(wwi);
2830
2831                     /* return current buffer to app */
2832                     lpWaveHdr = wwi->lpQueuePtr;
2833                     if (lpWaveHdr)
2834                     {
2835                         LPWAVEHDR       lpNext = lpWaveHdr->lpNext;
2836                         TRACE("stop %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
2837                         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2838                         lpWaveHdr->dwFlags |= WHDR_DONE;
2839                         wwi->lpQueuePtr = lpNext;
2840                         widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2841                     }
2842                 }
2843                 wwi->state = WINE_WS_STOPPED;
2844                 SetEvent(ev);
2845                 break;
2846             case WINE_WM_RESETTING:
2847                 if (wwi->state != WINE_WS_STOPPED)
2848                 {
2849                     snd_pcm_drain(wwi->p_handle);
2850                 }
2851                 wwi->state = WINE_WS_STOPPED;
2852                 wwi->dwTotalRecorded = 0;
2853
2854                 /* read any headers in queue */
2855                 widRecorder_ReadHeaders(wwi);
2856
2857                 /* return all buffers to the app */
2858                 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
2859                     TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
2860                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2861                     lpWaveHdr->dwFlags |= WHDR_DONE;
2862                     wwi->lpQueuePtr = lpWaveHdr->lpNext;
2863                     widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2864                 }
2865
2866                 wwi->lpQueuePtr = NULL;
2867                 SetEvent(ev);
2868                 break;
2869             case WINE_WM_CLOSING:
2870                 wwi->hThread = 0;
2871                 wwi->state = WINE_WS_CLOSED;
2872                 SetEvent(ev);
2873                 HeapFree(GetProcessHeap(), 0, buffer);
2874                 ExitThread(0);
2875                 /* shouldn't go here */
2876             case WINE_WM_UPDATE:
2877                 SetEvent(ev);
2878                 break;
2879
2880             default:
2881                 FIXME("unknown message %d\n", msg);
2882                 break;
2883             }
2884         }
2885     }
2886     ExitThread(0);
2887     /* just for not generating compilation warnings... should never be executed */
2888     return 0;
2889 }
2890
2891 /**************************************************************************
2892  *                              widOpen                         [internal]
2893  */
2894 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
2895 {
2896     WINE_WAVEIN*                wwi;
2897     snd_pcm_hw_params_t *       hw_params;
2898     snd_pcm_sw_params_t *       sw_params;
2899     snd_pcm_access_t            access;
2900     snd_pcm_format_t            format;
2901     int                         rate;
2902     unsigned int                buffer_time = 500000;
2903     unsigned int                period_time = 10000;
2904     int                         buffer_size;
2905     snd_pcm_uframes_t           period_size;
2906     int                         flags;
2907     snd_pcm_t *                 pcm;
2908     int                         err;
2909
2910     snd_pcm_hw_params_alloca(&hw_params);
2911     snd_pcm_sw_params_alloca(&sw_params);
2912
2913     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
2914     if (lpDesc == NULL) {
2915         WARN("Invalid Parameter !\n");
2916         return MMSYSERR_INVALPARAM;
2917     }
2918     if (wDevID >= MAX_WAVEOUTDRV) {
2919         TRACE("MAX_WAVOUTDRV reached !\n");
2920         return MMSYSERR_BADDEVICEID;
2921     }
2922
2923     /* only PCM format is supported so far... */
2924     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
2925         lpDesc->lpFormat->nChannels == 0 ||
2926         lpDesc->lpFormat->nSamplesPerSec == 0 ||
2927         (lpDesc->lpFormat->wBitsPerSample!=8 && lpDesc->lpFormat->wBitsPerSample!=16)) {
2928         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
2929              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
2930              lpDesc->lpFormat->nSamplesPerSec);
2931         return WAVERR_BADFORMAT;
2932     }
2933
2934     if (dwFlags & WAVE_FORMAT_QUERY) {
2935         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
2936              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
2937              lpDesc->lpFormat->nSamplesPerSec);
2938         return MMSYSERR_NOERROR;
2939     }
2940
2941     wwi = &WInDev[wDevID];
2942
2943     if ((dwFlags & WAVE_DIRECTSOUND) && !(wwi->caps.dwSupport & WAVECAPS_DIRECTSOUND))
2944         /* not supported, ignore it */
2945         dwFlags &= ~WAVE_DIRECTSOUND;
2946
2947     wwi->p_handle = 0;
2948     flags = SND_PCM_NONBLOCK;
2949     if ( dwFlags & WAVE_DIRECTSOUND )
2950         flags |= SND_PCM_ASYNC;
2951
2952     if ( (err=snd_pcm_open(&pcm, wwi->device, SND_PCM_STREAM_CAPTURE, dwFlags)) < 0 )
2953     {
2954         ERR("Error open: %s\n", snd_strerror(err));
2955         return MMSYSERR_NOTENABLED;
2956     }
2957
2958     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
2959
2960     memcpy(&wwi->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
2961     memcpy(&wwi->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
2962
2963     if (wwi->format.wBitsPerSample == 0) {
2964         WARN("Resetting zeroed wBitsPerSample\n");
2965         wwi->format.wBitsPerSample = 8 *
2966             (wwi->format.wf.nAvgBytesPerSec /
2967              wwi->format.wf.nSamplesPerSec) /
2968             wwi->format.wf.nChannels;
2969     }
2970
2971     snd_pcm_hw_params_any(pcm, hw_params);
2972
2973 #define EXIT_ON_ERROR(f,e,txt) do \
2974 { \
2975     int err; \
2976     if ( (err = (f) ) < 0) \
2977     { \
2978         ERR(txt ": %s\n", snd_strerror(err)); \
2979         snd_pcm_close(pcm); \
2980         return e; \
2981     } \
2982 } while(0)
2983
2984     access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
2985     if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
2986         WARN("mmap not available. switching to standard write.\n");
2987         access = SND_PCM_ACCESS_RW_INTERLEAVED;
2988         EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
2989         wwi->read = snd_pcm_readi;
2990     }
2991     else
2992         wwi->read = snd_pcm_mmap_readi;
2993
2994     EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwi->format.wf.nChannels), MMSYSERR_INVALPARAM, "unable to set required channels");
2995
2996     format = (wwi->format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE : SND_PCM_FORMAT_U8;
2997     EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), MMSYSERR_INVALPARAM, "unable to set required format");
2998
2999     rate = snd_pcm_hw_params_set_rate_near(pcm, hw_params, wwi->format.wf.nSamplesPerSec, 0);
3000     if (rate < 0) {
3001         ERR("Rate %ld Hz not available for playback: %s\n", wwi->format.wf.nSamplesPerSec, snd_strerror(rate));
3002         snd_pcm_close(pcm);
3003         return WAVERR_BADFORMAT;
3004     }
3005     if (rate != wwi->format.wf.nSamplesPerSec) {
3006         ERR("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwi->format.wf.nSamplesPerSec, rate);
3007         snd_pcm_close(pcm);
3008         return WAVERR_BADFORMAT;
3009     }
3010     
3011     EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, buffer_time, 0), MMSYSERR_INVALPARAM, "unable to set buffer time");
3012     EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, period_time, 0), MMSYSERR_INVALPARAM, "unable to set period time");
3013
3014     EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
3015     
3016     period_size = snd_pcm_hw_params_get_period_size(hw_params, 0);
3017     buffer_size = snd_pcm_hw_params_get_buffer_size(hw_params);
3018
3019     snd_pcm_sw_params_current(pcm, sw_params);
3020     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");
3021     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
3022     EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
3023     EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
3024     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
3025     EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
3026 #undef EXIT_ON_ERROR
3027
3028     snd_pcm_prepare(pcm);
3029
3030     if (TRACE_ON(wave))
3031         ALSA_TraceParameters(hw_params, sw_params, FALSE);
3032
3033     /* now, we can save all required data for later use... */
3034     if ( wwi->hw_params )
3035         snd_pcm_hw_params_free(wwi->hw_params);
3036     snd_pcm_hw_params_malloc(&(wwi->hw_params));
3037     snd_pcm_hw_params_copy(wwi->hw_params, hw_params);
3038
3039     wwi->dwBufferSize = buffer_size;
3040     wwi->lpQueuePtr = wwi->lpPlayPtr = wwi->lpLoopPtr = NULL;
3041     wwi->p_handle = pcm;
3042
3043     ALSA_InitRingMessage(&wwi->msgRing);
3044
3045     wwi->count = snd_pcm_poll_descriptors_count (wwi->p_handle);
3046     if (wwi->count <= 0) {
3047         ERR("Invalid poll descriptors count\n");
3048         return MMSYSERR_ERROR;
3049     }
3050
3051     wwi->ufds = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct pollfd) * wwi->count);
3052     if (wwi->ufds == NULL) {
3053         ERR("No enough memory\n");
3054         return MMSYSERR_NOMEM;
3055     }
3056     if ((err = snd_pcm_poll_descriptors(wwi->p_handle, wwi->ufds, wwi->count)) < 0) {
3057         ERR("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
3058         return MMSYSERR_ERROR;
3059     }
3060
3061     wwi->dwPeriodSize = period_size;
3062     /*if (wwi->dwFragmentSize % wwi->format.wf.nBlockAlign)
3063         ERR("Fragment doesn't contain an integral number of data blocks\n");
3064     */
3065     TRACE("dwPeriodSize=%lu\n", wwi->dwPeriodSize);
3066     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
3067           wwi->format.wBitsPerSample, wwi->format.wf.nAvgBytesPerSec,
3068           wwi->format.wf.nSamplesPerSec, wwi->format.wf.nChannels,
3069           wwi->format.wf.nBlockAlign);
3070
3071     if (!(dwFlags & WAVE_DIRECTSOUND)) {
3072         wwi->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
3073         wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
3074         WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
3075         CloseHandle(wwi->hStartUpEvent);
3076     } else {
3077         wwi->hThread = INVALID_HANDLE_VALUE;
3078         wwi->dwThreadID = 0;
3079     }
3080     wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
3081
3082     return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
3083 }
3084
3085
3086 /**************************************************************************
3087  *                              widClose                        [internal]
3088  */
3089 static DWORD widClose(WORD wDevID)
3090 {
3091     DWORD               ret = MMSYSERR_NOERROR;
3092     WINE_WAVEIN*        wwi;
3093
3094     TRACE("(%u);\n", wDevID);
3095
3096     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3097         WARN("bad device ID !\n");
3098         return MMSYSERR_BADDEVICEID;
3099     }
3100
3101     wwi = &WInDev[wDevID];
3102     if (wwi->lpQueuePtr) {
3103         WARN("buffers still playing !\n");
3104         ret = WAVERR_STILLPLAYING;
3105     } else {
3106         if (wwi->hThread != INVALID_HANDLE_VALUE) {
3107             ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
3108         }
3109         ALSA_DestroyRingMessage(&wwi->msgRing);
3110
3111         snd_pcm_hw_params_free(wwi->hw_params);
3112         wwi->hw_params = NULL;
3113
3114         snd_pcm_close(wwi->p_handle);
3115         wwi->p_handle = NULL;
3116
3117         ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
3118     }
3119
3120     HeapFree(GetProcessHeap(), 0, wwi->ufds);
3121     return ret;
3122 }
3123
3124 /**************************************************************************
3125  *                              widAddBuffer                    [internal]
3126  *
3127  */
3128 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3129 {
3130     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3131
3132     /* first, do the sanity checks... */
3133     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3134         WARN("bad dev ID !\n");
3135         return MMSYSERR_BADDEVICEID;
3136     }
3137
3138     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
3139         return WAVERR_UNPREPARED;
3140
3141     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3142         return WAVERR_STILLPLAYING;
3143
3144     lpWaveHdr->dwFlags &= ~WHDR_DONE;
3145     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
3146     lpWaveHdr->lpNext = 0;
3147
3148     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
3149
3150     return MMSYSERR_NOERROR;
3151 }
3152
3153 /**************************************************************************
3154  *                              widPrepare                      [internal]
3155  */
3156 static DWORD widPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3157 {
3158     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3159
3160     if (wDevID >= MAX_WAVEINDRV) {
3161         WARN("bad device ID !\n");
3162         return MMSYSERR_BADDEVICEID;
3163     }
3164
3165     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3166         return WAVERR_STILLPLAYING;
3167
3168     lpWaveHdr->dwFlags |= WHDR_PREPARED;
3169     lpWaveHdr->dwFlags &= ~WHDR_DONE;
3170     return MMSYSERR_NOERROR;
3171 }
3172
3173 /**************************************************************************
3174  *                              widUnprepare                    [internal]
3175  */
3176 static DWORD widUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3177 {
3178     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3179
3180     if (wDevID >= MAX_WAVEINDRV) {
3181         WARN("bad device ID !\n");
3182         return MMSYSERR_BADDEVICEID;
3183     }
3184
3185     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3186         return WAVERR_STILLPLAYING;
3187
3188     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
3189     lpWaveHdr->dwFlags |= WHDR_DONE;
3190
3191     return MMSYSERR_NOERROR;
3192 }
3193
3194 /**************************************************************************
3195  *                              widStart                        [internal]
3196  *
3197  */
3198 static DWORD widStart(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3199 {
3200     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3201
3202     /* first, do the sanity checks... */
3203     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3204         WARN("bad dev ID !\n");
3205         return MMSYSERR_BADDEVICEID;
3206     }
3207     
3208     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
3209
3210     Sleep(500);
3211
3212     return MMSYSERR_NOERROR;
3213 }
3214
3215 /**************************************************************************
3216  *                              widStop                 [internal]
3217  *
3218  */
3219 static DWORD widStop(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3220 {
3221     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3222
3223     /* first, do the sanity checks... */
3224     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3225         WARN("bad dev ID !\n");
3226         return MMSYSERR_BADDEVICEID;
3227     }
3228
3229     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
3230
3231     return MMSYSERR_NOERROR;
3232 }
3233
3234 /**************************************************************************
3235  *                      widReset                                [internal]
3236  */
3237 static DWORD widReset(WORD wDevID)
3238 {
3239     TRACE("(%u);\n", wDevID);
3240     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
3241         WARN("can't reset !\n");
3242         return MMSYSERR_INVALHANDLE;
3243     }
3244     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
3245     return MMSYSERR_NOERROR;
3246 }
3247
3248 /**************************************************************************
3249  *                              widGetPosition                  [internal]
3250  */
3251 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
3252 {
3253     int                 time;
3254     WINE_WAVEIN*        wwi;
3255
3256     FIXME("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
3257
3258     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
3259         WARN("can't get pos !\n");
3260         return MMSYSERR_INVALHANDLE;
3261     }
3262     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
3263
3264     wwi = &WInDev[wDevID];
3265     ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_UPDATE, 0, TRUE);
3266
3267     TRACE("wType=%04X !\n", lpTime->wType);
3268     TRACE("wBitsPerSample=%u\n", wwi->format.wBitsPerSample);
3269     TRACE("nSamplesPerSec=%lu\n", wwi->format.wf.nSamplesPerSec);
3270     TRACE("nChannels=%u\n", wwi->format.wf.nChannels);
3271     TRACE("nAvgBytesPerSec=%lu\n", wwi->format.wf.nAvgBytesPerSec);
3272     FIXME("dwTotalRecorded=%lu\n",wwi->dwTotalRecorded);
3273     switch (lpTime->wType) {
3274     case TIME_BYTES:
3275         lpTime->u.cb = wwi->dwTotalRecorded;
3276         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
3277         break;
3278     case TIME_SAMPLES:
3279         lpTime->u.sample = wwi->dwTotalRecorded * 8 /
3280             wwi->format.wBitsPerSample / wwi->format.wf.nChannels;
3281         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
3282         break;
3283     case TIME_SMPTE:
3284         time = wwi->dwTotalRecorded /
3285             (wwi->format.wf.nAvgBytesPerSec / 1000);
3286         lpTime->u.smpte.hour = time / (60 * 60 * 1000);
3287         time -= lpTime->u.smpte.hour * (60 * 60 * 1000);
3288         lpTime->u.smpte.min = time / (60 * 1000);
3289         time -= lpTime->u.smpte.min * (60 * 1000);
3290         lpTime->u.smpte.sec = time / 1000;
3291         time -= lpTime->u.smpte.sec * 1000;
3292         lpTime->u.smpte.frame = time * 30 / 1000;
3293         lpTime->u.smpte.fps = 30;
3294         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
3295               lpTime->u.smpte.hour, lpTime->u.smpte.min,
3296               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
3297         break;
3298     default:
3299         FIXME("format not supported (%u) ! use TIME_MS !\n", lpTime->wType);
3300         lpTime->wType = TIME_MS;
3301     case TIME_MS:
3302         lpTime->u.ms = wwi->dwTotalRecorded /
3303             (wwi->format.wf.nAvgBytesPerSec / 1000);
3304         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
3305         break;
3306     }
3307     return MMSYSERR_NOERROR;
3308 }
3309
3310 /**************************************************************************
3311  *                              widGetNumDevs                   [internal]
3312  */
3313 static  DWORD   widGetNumDevs(void)
3314 {
3315     return ALSA_WidNumDevs;
3316 }
3317
3318 /**************************************************************************
3319  *                              widMessage (WINEALSA.@)
3320  */
3321 DWORD WINAPI ALSA_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
3322                              DWORD dwParam1, DWORD dwParam2)
3323 {
3324     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
3325           wDevID, wMsg, dwUser, dwParam1, dwParam2);
3326
3327     switch (wMsg) {
3328     case DRVM_INIT:
3329     case DRVM_EXIT:
3330     case DRVM_ENABLE:
3331     case DRVM_DISABLE:
3332         /* FIXME: Pretend this is supported */
3333         return 0;
3334     case WIDM_OPEN:             return widOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
3335     case WIDM_CLOSE:            return widClose         (wDevID);
3336     case WIDM_ADDBUFFER:        return widAddBuffer     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
3337     case WIDM_PREPARE:          return widPrepare       (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
3338     case WIDM_UNPREPARE:        return widUnprepare     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
3339     case WIDM_GETDEVCAPS:       return widGetDevCaps    (wDevID, (LPWAVEOUTCAPSA)dwParam1,      dwParam2);
3340     case WIDM_GETNUMDEVS:       return widGetNumDevs    ();
3341     case WIDM_GETPOS:           return widGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
3342     case WIDM_RESET:            return widReset         (wDevID);
3343     case WIDM_START:            return widStart (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
3344     case WIDM_STOP:             return widStop  (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
3345     /*case DRV_QUERYDEVICEINTERFACESIZE: return wdDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
3346     case DRV_QUERYDEVICEINTERFACE:     return wdDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
3347     case DRV_QUERYDSOUNDIFACE:  return widDsCreate   (wDevID, (PIDSCDRIVER*)dwParam1);
3348     case DRV_QUERYDSOUNDDESC:   return widDsDesc     (wDevID, (PDSDRIVERDESC)dwParam1);
3349     case DRV_QUERYDSOUNDGUID:   return widDsGuid     (wDevID, (LPGUID)dwParam1);*/
3350     default:
3351         FIXME("unknown message %d!\n", wMsg);
3352     }
3353     return MMSYSERR_NOTSUPPORTED;
3354 }
3355
3356 #endif
3357
3358 #if !(defined(HAVE_ALSA) && ((SND_LIB_MAJOR == 0 && SND_LIB_MINOR >= 9) || SND_LIB_MAJOR >= 1))
3359
3360 /**************************************************************************
3361  *                              widMessage (WINEALSA.@)
3362  */
3363 DWORD WINAPI ALSA_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3364                              DWORD dwParam1, DWORD dwParam2)
3365 {
3366     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3367     return MMSYSERR_NOTENABLED;
3368 }
3369
3370 #endif
3371
3372 #ifndef HAVE_ALSA
3373
3374 /**************************************************************************
3375  *                              wodMessage (WINEALSA.@)
3376  */
3377 DWORD WINAPI ALSA_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3378                              DWORD dwParam1, DWORD dwParam2)
3379 {
3380     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3381     return MMSYSERR_NOTENABLED;
3382 }
3383
3384 #endif /* HAVE_ALSA */