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