Remove wine specific DRV_QUERYDSOUNDGUID message and calculate it in
[wine/multimedia.git] / dlls / winmm / winealsa / audio.c
blob53e06acdb75760255e19901523ecf10e941485bd
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
6 * Copyright 2002 Eric Pouech
7 * 2002 Marco Pietrobono
8 * 2003 Christian Costa : WaveIn support
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.
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.
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
25 /* unless someone makes a wineserver kernel module, Unix pipes are faster than win32 events */
26 #define USE_PIPE_SYNC
28 #include "config.h"
29 #include "wine/port.h"
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <string.h>
35 #ifdef HAVE_UNISTD_H
36 # include <unistd.h>
37 #endif
38 #include <errno.h>
39 #include <limits.h>
40 #include <fcntl.h>
41 #ifdef HAVE_SYS_IOCTL_H
42 # include <sys/ioctl.h>
43 #endif
44 #ifdef HAVE_SYS_MMAN_H
45 # include <sys/mman.h>
46 #endif
47 #include "windef.h"
48 #include "winbase.h"
49 #include "wingdi.h"
50 #include "winerror.h"
51 #include "winuser.h"
52 #include "winnls.h"
53 #include "winreg.h"
54 #include "mmddk.h"
55 #include "mmreg.h"
56 #include "dsound.h"
57 #include "dsdriver.h"
58 #include "ks.h"
59 #include "ksguid.h"
60 #include "ksmedia.h"
61 #define ALSA_PCM_NEW_HW_PARAMS_API
62 #define ALSA_PCM_NEW_SW_PARAMS_API
63 #include "alsa.h"
64 #include "wine/library.h"
65 #include "wine/debug.h"
67 WINE_DEFAULT_DEBUG_CHANNEL(wave);
70 #if defined(HAVE_ALSA) && ((SND_LIB_MAJOR == 0 && SND_LIB_MINOR >= 9) || SND_LIB_MAJOR >= 1)
72 /* internal ALSALIB functions */
73 snd_pcm_uframes_t _snd_pcm_mmap_hw_ptr(snd_pcm_t *pcm);
76 #define MAX_WAVEOUTDRV (1)
77 #define MAX_WAVEINDRV (1)
79 /* state diagram for waveOut writing:
81 * +---------+-------------+---------------+---------------------------------+
82 * | state | function | event | new state |
83 * +---------+-------------+---------------+---------------------------------+
84 * | | open() | | STOPPED |
85 * | PAUSED | write() | | PAUSED |
86 * | STOPPED | write() | <thrd create> | PLAYING |
87 * | PLAYING | write() | HEADER | PLAYING |
88 * | (other) | write() | <error> | |
89 * | (any) | pause() | PAUSING | PAUSED |
90 * | PAUSED | restart() | RESTARTING | PLAYING (if no thrd => STOPPED) |
91 * | (any) | reset() | RESETTING | STOPPED |
92 * | (any) | close() | CLOSING | CLOSED |
93 * +---------+-------------+---------------+---------------------------------+
96 /* states of the playing device */
97 #define WINE_WS_PLAYING 0
98 #define WINE_WS_PAUSED 1
99 #define WINE_WS_STOPPED 2
100 #define WINE_WS_CLOSED 3
102 /* events to be send to device */
103 enum win_wm_message {
104 WINE_WM_PAUSING = WM_USER + 1, WINE_WM_RESTARTING, WINE_WM_RESETTING, WINE_WM_HEADER,
105 WINE_WM_UPDATE, WINE_WM_BREAKLOOP, WINE_WM_CLOSING, WINE_WM_STARTING, WINE_WM_STOPPING
108 #ifdef USE_PIPE_SYNC
109 #define SIGNAL_OMR(omr) do { int x = 0; write((omr)->msg_pipe[1], &x, sizeof(x)); } while (0)
110 #define CLEAR_OMR(omr) do { int x = 0; read((omr)->msg_pipe[0], &x, sizeof(x)); } while (0)
111 #define RESET_OMR(omr) do { } while (0)
112 #define WAIT_OMR(omr, sleep) \
113 do { struct pollfd pfd; pfd.fd = (omr)->msg_pipe[0]; \
114 pfd.events = POLLIN; poll(&pfd, 1, sleep); } while (0)
115 #else
116 #define SIGNAL_OMR(omr) do { SetEvent((omr)->msg_event); } while (0)
117 #define CLEAR_OMR(omr) do { } while (0)
118 #define RESET_OMR(omr) do { ResetEvent((omr)->msg_event); } while (0)
119 #define WAIT_OMR(omr, sleep) \
120 do { WaitForSingleObject((omr)->msg_event, sleep); } while (0)
121 #endif
123 typedef struct {
124 enum win_wm_message msg; /* message identifier */
125 DWORD param; /* parameter for this message */
126 HANDLE hEvent; /* if message is synchronous, handle of event for synchro */
127 } ALSA_MSG;
129 /* implement an in-process message ring for better performance
130 * (compared to passing thru the server)
131 * this ring will be used by the input (resp output) record (resp playback) routine
133 #define ALSA_RING_BUFFER_INCREMENT 64
134 typedef struct {
135 ALSA_MSG * messages;
136 int ring_buffer_size;
137 int msg_tosave;
138 int msg_toget;
139 #ifdef USE_PIPE_SYNC
140 int msg_pipe[2];
141 #else
142 HANDLE msg_event;
143 #endif
144 CRITICAL_SECTION msg_crst;
145 } ALSA_MSG_RING;
147 typedef struct {
148 /* Windows information */
149 volatile int state; /* one of the WINE_WS_ manifest constants */
150 WAVEOPENDESC waveDesc;
151 WORD wFlags;
152 WAVEFORMATPCMEX format;
153 WAVEOUTCAPSA caps;
155 /* ALSA information (ALSA 0.9/1.x uses two different devices for playback/capture) */
156 char* device;
157 char interface_name[64];
158 snd_pcm_t* p_handle; /* handle to ALSA playback device */
159 snd_pcm_t* c_handle; /* handle to ALSA capture device */
160 snd_pcm_hw_params_t * hw_params; /* ALSA Hw params */
162 snd_ctl_t * ctl; /* control handle for the playback volume */
163 snd_ctl_elem_id_t * playback_eid; /* element id of the playback volume control */
164 snd_ctl_elem_value_t * playback_evalue; /* element value of the playback volume control */
165 snd_ctl_elem_info_t * playback_einfo; /* element info of the playback volume control */
167 snd_pcm_sframes_t (*write)(snd_pcm_t *, const void *, snd_pcm_uframes_t );
169 struct pollfd *ufds;
170 int count;
172 DWORD dwBufferSize; /* size of whole ALSA buffer in bytes */
173 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
174 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
175 DWORD dwPartialOffset; /* Offset of not yet written bytes in lpPlayPtr */
177 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
178 DWORD dwLoops; /* private copy of loop counter */
180 DWORD dwPlayedTotal; /* number of bytes actually played since opening */
181 DWORD dwWrittenTotal; /* number of bytes written to ALSA buffer since opening */
183 /* synchronization stuff */
184 HANDLE hStartUpEvent;
185 HANDLE hThread;
186 DWORD dwThreadID;
187 ALSA_MSG_RING msgRing;
189 /* DirectSound stuff */
190 DSDRIVERDESC ds_desc;
191 } WINE_WAVEOUT;
193 typedef struct {
194 /* Windows information */
195 volatile int state; /* one of the WINE_WS_ manifest constants */
196 WAVEOPENDESC waveDesc;
197 WORD wFlags;
198 WAVEFORMATPCMEX format;
199 WAVEOUTCAPSA caps;
201 /* ALSA information (ALSA 0.9/1.x uses two different devices for playback/capture) */
202 char* device;
203 char interface_name[64];
204 snd_pcm_t* p_handle; /* handle to ALSA playback device */
205 snd_pcm_t* c_handle; /* handle to ALSA capture device */
206 snd_pcm_hw_params_t * hw_params; /* ALSA Hw params */
208 snd_ctl_t * ctl; /* control handle for the playback volume */
209 snd_ctl_elem_id_t * playback_eid; /* element id of the playback volume control */
210 snd_ctl_elem_value_t * playback_evalue; /* element value of the playback volume control */
211 snd_ctl_elem_info_t * playback_einfo; /* element info of the playback volume control */
213 snd_pcm_sframes_t (*read)(snd_pcm_t *, void *, snd_pcm_uframes_t );
215 struct pollfd *ufds;
216 int count;
218 DWORD dwPeriodSize; /* size of OSS buffer period */
219 DWORD dwBufferSize; /* size of whole ALSA buffer in bytes */
220 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
221 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
223 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
224 DWORD dwLoops; /* private copy of loop counter */
226 /*DWORD dwPlayedTotal; */
227 DWORD dwTotalRecorded;
229 /* synchronization stuff */
230 HANDLE hStartUpEvent;
231 HANDLE hThread;
232 DWORD dwThreadID;
233 ALSA_MSG_RING msgRing;
235 /* DirectSound stuff */
236 DSDRIVERDESC ds_desc;
237 } WINE_WAVEIN;
239 static WINE_WAVEOUT WOutDev [MAX_WAVEOUTDRV];
240 static DWORD ALSA_WodNumDevs;
241 static WINE_WAVEIN WInDev [MAX_WAVEINDRV];
242 static DWORD ALSA_WidNumDevs;
244 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
245 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
247 /* These strings used only for tracing */
248 static const char * getCmdString(enum win_wm_message msg)
250 static char unknown[32];
251 #define MSG_TO_STR(x) case x: return #x
252 switch(msg) {
253 MSG_TO_STR(WINE_WM_PAUSING);
254 MSG_TO_STR(WINE_WM_RESTARTING);
255 MSG_TO_STR(WINE_WM_RESETTING);
256 MSG_TO_STR(WINE_WM_HEADER);
257 MSG_TO_STR(WINE_WM_UPDATE);
258 MSG_TO_STR(WINE_WM_BREAKLOOP);
259 MSG_TO_STR(WINE_WM_CLOSING);
260 MSG_TO_STR(WINE_WM_STARTING);
261 MSG_TO_STR(WINE_WM_STOPPING);
263 #undef MSG_TO_STR
264 sprintf(unknown, "UNKNOWN(0x%08x)", msg);
265 return unknown;
268 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
269 WAVEFORMATPCMEX* format)
271 TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
272 lpTime->wType, format->Format.wBitsPerSample, format->Format.nSamplesPerSec,
273 format->Format.nChannels, format->Format.nAvgBytesPerSec);
274 TRACE("Position in bytes=%lu\n", position);
276 switch (lpTime->wType) {
277 case TIME_SAMPLES:
278 lpTime->u.sample = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
279 TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
280 break;
281 case TIME_MS:
282 lpTime->u.ms = 1000.0 * position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels * format->Format.nSamplesPerSec);
283 TRACE("TIME_MS=%lu\n", lpTime->u.ms);
284 break;
285 case TIME_SMPTE:
286 position = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
287 lpTime->u.smpte.sec = position / format->Format.nSamplesPerSec;
288 position -= lpTime->u.smpte.sec * format->Format.nSamplesPerSec;
289 lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
290 lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
291 lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
292 lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
293 lpTime->u.smpte.fps = 30;
294 lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->Format.nSamplesPerSec;
295 position -= lpTime->u.smpte.frame * format->Format.nSamplesPerSec / lpTime->u.smpte.fps;
296 if (position != 0)
298 /* Round up */
299 lpTime->u.smpte.frame++;
301 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
302 lpTime->u.smpte.hour, lpTime->u.smpte.min,
303 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
304 break;
305 default:
306 FIXME("Format %d not supported ! use TIME_BYTES !\n", lpTime->wType);
307 lpTime->wType = TIME_BYTES;
308 /* fall through */
309 case TIME_BYTES:
310 lpTime->u.cb = position;
311 TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
312 break;
314 return MMSYSERR_NOERROR;
317 static BOOL supportedFormat(LPWAVEFORMATEX wf)
319 TRACE("(%p)\n",wf);
321 if (wf->nSamplesPerSec<DSBFREQUENCY_MIN||wf->nSamplesPerSec>DSBFREQUENCY_MAX)
322 return FALSE;
324 if (wf->wFormatTag == WAVE_FORMAT_PCM) {
325 if (wf->nChannels==1||wf->nChannels==2) {
326 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
327 return TRUE;
329 } else if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
330 WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE *)wf;
332 if (wf->cbSize == 22 && IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
333 if (wf->nChannels>=1 && wf->nChannels<=6) {
334 if (wf->wBitsPerSample==wfex->Samples.wValidBitsPerSample) {
335 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16||
336 wf->wBitsPerSample==24||wf->wBitsPerSample==32) {
337 return TRUE;
339 } else
340 WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
342 } else
343 WARN("only KSDATAFORMAT_SUBTYPE_PCM supported\n");
344 } else if (wf->wFormatTag == WAVE_FORMAT_MULAW || wf->wFormatTag == WAVE_FORMAT_ALAW) {
345 if (wf->wBitsPerSample==8)
346 return TRUE;
347 else
348 ERR("WAVE_FORMAT_MULAW and WAVE_FORMAT_ALAW wBitsPerSample must = 8\n");
350 } else if (wf->wFormatTag == WAVE_FORMAT_ADPCM) {
351 if (wf->wBitsPerSample==4)
352 return TRUE;
353 else
354 ERR("WAVE_FORMAT_ADPCM wBitsPerSample must = 4\n");
355 } else
356 WARN("only WAVE_FORMAT_PCM and WAVE_FORMAT_EXTENSIBLE supported\n");
358 return FALSE;
361 static void copy_format(LPWAVEFORMATEX wf1, LPWAVEFORMATPCMEX wf2)
363 ZeroMemory(wf2, sizeof(wf2));
364 if (wf1->wFormatTag == WAVE_FORMAT_PCM)
365 memcpy(wf2, wf1, sizeof(PCMWAVEFORMAT));
366 else if (wf1->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
367 memcpy(wf2, wf1, sizeof(WAVEFORMATPCMEX));
368 else
369 memcpy(wf2, wf1, sizeof(WAVEFORMATEX) + wf1->cbSize);
372 /*======================================================================*
373 * Low level WAVE implementation *
374 *======================================================================*/
376 /**************************************************************************
377 * ALSA_InitializeVolumeCtl [internal]
379 * used to initialize the PCM Volume Control
381 static int ALSA_InitializeVolumeCtl(WINE_WAVEOUT * wwo)
383 snd_ctl_t * ctl = NULL;
384 snd_ctl_card_info_t * cardinfo;
385 snd_ctl_elem_list_t * elemlist;
386 snd_ctl_elem_id_t * e_id;
387 snd_ctl_elem_info_t * einfo;
388 snd_hctl_t * hctl = NULL;
389 snd_hctl_elem_t * elem;
390 int nCtrls;
391 int i;
393 snd_ctl_card_info_alloca(&cardinfo);
394 memset(cardinfo,0,snd_ctl_card_info_sizeof());
396 snd_ctl_elem_list_alloca(&elemlist);
397 memset(elemlist,0,snd_ctl_elem_list_sizeof());
399 snd_ctl_elem_id_alloca(&e_id);
400 memset(e_id,0,snd_ctl_elem_id_sizeof());
402 snd_ctl_elem_info_alloca(&einfo);
403 memset(einfo,0,snd_ctl_elem_info_sizeof());
405 #define EXIT_ON_ERROR(f,txt) do \
407 int err; \
408 if ( (err = (f) ) < 0) \
410 ERR(txt ": %s\n", snd_strerror(err)); \
411 if (hctl) \
412 snd_hctl_close(hctl); \
413 if (ctl) \
414 snd_ctl_close(ctl); \
415 return -1; \
417 } while(0)
419 EXIT_ON_ERROR( snd_ctl_open(&ctl,"hw",0) , "ctl open failed" );
420 EXIT_ON_ERROR( snd_ctl_card_info(ctl, cardinfo), "card info failed");
421 EXIT_ON_ERROR( snd_ctl_elem_list(ctl, elemlist), "elem list failed");
423 nCtrls = snd_ctl_elem_list_get_count(elemlist);
425 EXIT_ON_ERROR( snd_hctl_open(&hctl,"hw",0), "hctl open failed");
426 EXIT_ON_ERROR( snd_hctl_load(hctl), "hctl load failed" );
428 elem=snd_hctl_first_elem(hctl);
429 for ( i= 0; i<nCtrls; i++) {
431 memset(e_id,0,snd_ctl_elem_id_sizeof());
433 snd_hctl_elem_get_id(elem,e_id);
435 TRACE("ctl: #%d '%s'%d\n",
436 snd_ctl_elem_id_get_numid(e_id),
437 snd_ctl_elem_id_get_name(e_id),
438 snd_ctl_elem_id_get_index(e_id));
440 if ( !strcmp("PCM Playback Volume", snd_ctl_elem_id_get_name(e_id)) )
442 EXIT_ON_ERROR( snd_hctl_elem_info(elem,einfo), "hctl elem info failed" );
444 /* few sanity checks... you'll never know... */
445 if ( snd_ctl_elem_info_get_type(einfo) != SND_CTL_ELEM_TYPE_INTEGER )
446 WARN("playback volume control is not an integer\n");
447 if ( !snd_ctl_elem_info_is_readable(einfo) )
448 WARN("playback volume control is readable\n");
449 if ( !snd_ctl_elem_info_is_writable(einfo) )
450 WARN("playback volume control is readable\n");
452 TRACE(" ctrl range: min=%ld max=%ld step=%ld\n",
453 snd_ctl_elem_info_get_min(einfo),
454 snd_ctl_elem_info_get_max(einfo),
455 snd_ctl_elem_info_get_step(einfo));
457 EXIT_ON_ERROR( snd_ctl_elem_id_malloc(&wwo->playback_eid), "elem id malloc failed" );
458 EXIT_ON_ERROR( snd_ctl_elem_info_malloc(&wwo->playback_einfo), "elem info malloc failed" );
459 EXIT_ON_ERROR( snd_ctl_elem_value_malloc(&wwo->playback_evalue), "elem value malloc failed" );
461 /* ok, now we can safely save these objects for later */
462 snd_ctl_elem_id_copy(wwo->playback_eid, e_id);
463 snd_ctl_elem_info_copy(wwo->playback_einfo, einfo);
464 snd_ctl_elem_value_set_id(wwo->playback_evalue, wwo->playback_eid);
465 wwo->ctl = ctl;
468 elem=snd_hctl_elem_next(elem);
470 snd_hctl_close(hctl);
471 #undef EXIT_ON_ERROR
472 return 0;
475 /**************************************************************************
476 * ALSA_XRUNRecovery [internal]
478 * used to recovery from XRUN errors (buffer underflow/overflow)
480 static int ALSA_XRUNRecovery(WINE_WAVEOUT * wwo, int err)
482 if (err == -EPIPE) { /* under-run */
483 err = snd_pcm_prepare(wwo->p_handle);
484 if (err < 0)
485 ERR( "underrun recovery failed. prepare failed: %s\n", snd_strerror(err));
486 return 0;
487 } else if (err == -ESTRPIPE) {
488 while ((err = snd_pcm_resume(wwo->p_handle)) == -EAGAIN)
489 sleep(1); /* wait until the suspend flag is released */
490 if (err < 0) {
491 err = snd_pcm_prepare(wwo->p_handle);
492 if (err < 0)
493 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
495 return 0;
497 return err;
500 /**************************************************************************
501 * ALSA_TraceParameters [internal]
503 * used to trace format changes, hw and sw parameters
505 static void ALSA_TraceParameters(snd_pcm_hw_params_t * hw_params, snd_pcm_sw_params_t * sw, int full)
507 int err;
508 snd_pcm_format_t format;
509 snd_pcm_access_t access;
511 err = snd_pcm_hw_params_get_access(hw_params, &access);
512 err = snd_pcm_hw_params_get_format(hw_params, &format);
514 #define X(x) ((x)? "true" : "false")
515 if (full)
516 TRACE("FLAGS: sampleres=%s overrng=%s pause=%s resume=%s syncstart=%s batch=%s block=%s double=%s "
517 "halfd=%s joint=%s \n",
518 X(snd_pcm_hw_params_can_mmap_sample_resolution(hw_params)),
519 X(snd_pcm_hw_params_can_overrange(hw_params)),
520 X(snd_pcm_hw_params_can_pause(hw_params)),
521 X(snd_pcm_hw_params_can_resume(hw_params)),
522 X(snd_pcm_hw_params_can_sync_start(hw_params)),
523 X(snd_pcm_hw_params_is_batch(hw_params)),
524 X(snd_pcm_hw_params_is_block_transfer(hw_params)),
525 X(snd_pcm_hw_params_is_double(hw_params)),
526 X(snd_pcm_hw_params_is_half_duplex(hw_params)),
527 X(snd_pcm_hw_params_is_joint_duplex(hw_params)));
528 #undef X
530 if (access >= 0)
531 TRACE("access=%s\n", snd_pcm_access_name(access));
532 else
534 snd_pcm_access_mask_t * acmask;
535 snd_pcm_access_mask_alloca(&acmask);
536 snd_pcm_hw_params_get_access_mask(hw_params, acmask);
537 for ( access = SND_PCM_ACCESS_MMAP_INTERLEAVED; access <= SND_PCM_ACCESS_LAST; access++)
538 if (snd_pcm_access_mask_test(acmask, access))
539 TRACE("access=%s\n", snd_pcm_access_name(access));
542 if (format >= 0)
544 TRACE("format=%s\n", snd_pcm_format_name(format));
547 else
549 snd_pcm_format_mask_t * fmask;
551 snd_pcm_format_mask_alloca(&fmask);
552 snd_pcm_hw_params_get_format_mask(hw_params, fmask);
553 for ( format = SND_PCM_FORMAT_S8; format <= SND_PCM_FORMAT_LAST ; format++)
554 if ( snd_pcm_format_mask_test(fmask, format) )
555 TRACE("format=%s\n", snd_pcm_format_name(format));
558 do {
559 int err=0;
560 unsigned int val=0;
561 err = snd_pcm_hw_params_get_channels(hw_params, &val);
562 if (err<0) {
563 unsigned int min = 0;
564 unsigned int max = 0;
565 err = snd_pcm_hw_params_get_channels_min(hw_params, &min),
566 err = snd_pcm_hw_params_get_channels_max(hw_params, &max);
567 TRACE("channels_min=%u, channels_min_max=%u\n", min, max);
568 } else {
569 TRACE("channels_min=%d\n", val);
571 } while(0);
572 do {
573 int err=0;
574 snd_pcm_uframes_t val=0;
575 err = snd_pcm_hw_params_get_buffer_size(hw_params, &val);
576 if (err<0) {
577 snd_pcm_uframes_t min = 0;
578 snd_pcm_uframes_t max = 0;
579 err = snd_pcm_hw_params_get_buffer_size_min(hw_params, &min),
580 err = snd_pcm_hw_params_get_buffer_size_max(hw_params, &max);
581 TRACE("buffer_size_min=%lu, buffer_size_min_max=%lu\n", min, max);
582 } else {
583 TRACE("buffer_size_min=%lu\n", val);
585 } while(0);
587 #define X(x) do { \
588 int err=0; \
589 int dir=0; \
590 unsigned int val=0; \
591 err = snd_pcm_hw_params_get_##x(hw_params,&val, &dir); \
592 if (err<0) { \
593 unsigned int min = 0; \
594 unsigned int max = 0; \
595 err = snd_pcm_hw_params_get_##x##_min(hw_params, &min, &dir); \
596 err = snd_pcm_hw_params_get_##x##_max(hw_params, &max, &dir); \
597 TRACE(#x "_min=%u " #x "_max=%u\n", min, max); \
598 } else \
599 TRACE(#x "=%d\n", val); \
600 } while(0)
602 X(rate);
603 X(buffer_time);
604 X(periods);
605 do {
606 int err=0;
607 int dir=0;
608 snd_pcm_uframes_t val=0;
609 err = snd_pcm_hw_params_get_period_size(hw_params, &val, &dir);
610 if (err<0) {
611 snd_pcm_uframes_t min = 0;
612 snd_pcm_uframes_t max = 0;
613 err = snd_pcm_hw_params_get_period_size_min(hw_params, &min, &dir),
614 err = snd_pcm_hw_params_get_period_size_max(hw_params, &max, &dir);
615 TRACE("period_size_min=%lu, period_size_min_max=%lu\n", min, max);
616 } else {
617 TRACE("period_size_min=%lu\n", val);
619 } while(0);
621 X(period_time);
622 X(tick_time);
623 #undef X
625 if (!sw)
626 return;
631 /* return a string duplicated on the win32 process heap, free with HeapFree */
632 static char* ALSA_strdup(char *s) {
633 char *result = HeapAlloc(GetProcessHeap(), 0, strlen(s)+1);
634 strcpy(result, s);
635 return result;
638 /******************************************************************
639 * ALSA_GetDeviceFromReg
641 * Returns either "default" or reads the registry so the user can
642 * override the playback/record device used.
644 char *ALSA_GetDeviceFromReg(char *value)
646 DWORD res;
647 DWORD type;
648 HKEY playbackKey = 0;
649 char *result = NULL;
650 DWORD resultSize;
652 res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\ALSA", 0, KEY_QUERY_VALUE, &playbackKey);
653 if (res != ERROR_SUCCESS) goto end;
655 res = RegQueryValueExA(playbackKey, value, NULL, &type, NULL, &resultSize);
656 if (res != ERROR_SUCCESS) goto end;
658 if (type != REG_SZ) {
659 ERR("Registry key [HKEY_LOCAL_MACHINE\\Software\\Wine\\Wine\\ALSA\\%s] must be a string\n", value);
660 goto end;
663 result = HeapAlloc(GetProcessHeap(), 0, resultSize);
664 res = RegQueryValueExA(playbackKey, value, NULL, NULL, result, &resultSize);
666 end:
667 if (!result) result = ALSA_strdup("default");
668 if (playbackKey) RegCloseKey(playbackKey);
669 return result;
672 /******************************************************************
673 * ALSA_WaveInit
675 * Initialize internal structures from ALSA information
677 LONG ALSA_WaveInit(void)
679 snd_pcm_t* h;
680 snd_pcm_info_t * info;
681 snd_pcm_hw_params_t * hw_params;
682 unsigned int ratemin=0;
683 unsigned int ratemax=0;
684 unsigned int chmin=0;
685 unsigned int chmax=0;
686 int dir=0;
687 int err=0;
688 WINE_WAVEOUT* wwo;
689 WINE_WAVEIN* wwi;
691 wwo = &WOutDev[0];
693 /* FIXME: use better values */
694 wwo->device = ALSA_GetDeviceFromReg("PlaybackDevice");
695 TRACE("using waveout device \"%s\"\n", wwo->device);
697 snprintf(wwo->interface_name, sizeof(wwo->interface_name), "winealsa: %s", wwo->device);
699 wwo->caps.wMid = 0x0002;
700 wwo->caps.wPid = 0x0104;
701 strcpy(wwo->caps.szPname, "SB16 Wave Out");
702 wwo->caps.vDriverVersion = 0x0100;
703 wwo->caps.dwFormats = 0x00000000;
704 wwo->caps.dwSupport = WAVECAPS_VOLUME;
705 strcpy(wwo->ds_desc.szDesc, "WineALSA DirectSound Driver");
706 strcpy(wwo->ds_desc.szDrvName, "winealsa.drv");
708 if (!wine_dlopen("libasound.so.2", RTLD_LAZY|RTLD_GLOBAL, NULL, 0))
710 ERR("Error: ALSA lib needs to be loaded with flags RTLD_LAZY and RTLD_GLOBAL.\n");
711 return -1;
714 snd_pcm_info_alloca(&info);
715 snd_pcm_hw_params_alloca(&hw_params);
717 #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)
719 h = NULL;
720 ALSA_WodNumDevs = 0;
721 EXIT_ON_ERROR( snd_pcm_open(&h, wwo->device, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK) , "open pcm" );
722 if (!h) return -1;
723 ALSA_WodNumDevs++;
725 EXIT_ON_ERROR( snd_pcm_info(h, info) , "pcm info" );
727 TRACE("dev=%d id=%s name=%s subdev=%d subdev_name=%s subdev_avail=%d subdev_num=%d stream=%s subclass=%s \n",
728 snd_pcm_info_get_device(info),
729 snd_pcm_info_get_id(info),
730 snd_pcm_info_get_name(info),
731 snd_pcm_info_get_subdevice(info),
732 snd_pcm_info_get_subdevice_name(info),
733 snd_pcm_info_get_subdevices_avail(info),
734 snd_pcm_info_get_subdevices_count(info),
735 snd_pcm_stream_name(snd_pcm_info_get_stream(info)),
736 (snd_pcm_info_get_subclass(info) == SND_PCM_SUBCLASS_GENERIC_MIX ? "GENERIC MIX": "MULTI MIX"));
738 EXIT_ON_ERROR( snd_pcm_hw_params_any(h, hw_params) , "pcm hw params" );
739 #undef EXIT_ON_ERROR
741 err = snd_pcm_hw_params_get_rate_min(hw_params, &ratemin, &dir);
742 err = snd_pcm_hw_params_get_rate_max(hw_params, &ratemax, &dir);
743 err = snd_pcm_hw_params_get_channels_min(hw_params, &chmin);
744 err = snd_pcm_hw_params_get_channels_max(hw_params, &chmax);
745 if (TRACE_ON(wave))
746 ALSA_TraceParameters(hw_params, NULL, TRUE);
749 snd_pcm_format_mask_t * fmask;
751 snd_pcm_format_mask_alloca(&fmask);
752 snd_pcm_hw_params_get_format_mask(hw_params, fmask);
754 #define X(r,v) \
755 if ( (r) >= ratemin && ( (r) <= ratemax || ratemax == -1) ) \
757 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_U8)) \
759 if (chmin <= 1 && 1 <= chmax) \
760 wwo->caps.dwFormats |= WAVE_FORMAT_##v##M08; \
761 if (chmin <= 2 && 2 <= chmax) \
762 wwo->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
764 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_S16_LE)) \
766 if (chmin <= 1 && 1 <= chmax) \
767 wwo->caps.dwFormats |= WAVE_FORMAT_##v##M16; \
768 if (chmin <= 2 && 2 <= chmax) \
769 wwo->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
772 X(11025,1);
773 X(22050,2);
774 X(44100,4);
775 X(48000,48);
776 X(96000,96);
777 #undef X
780 if ( chmin > 1) FIXME("-\n");
781 wwo->caps.wChannels = chmax;
782 if (chmin <= 2 && 2 <= chmax)
783 wwo->caps.dwSupport |= WAVECAPS_LRVOLUME;
785 /* FIXME: always true ? */
786 wwo->caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
789 snd_pcm_access_mask_t * acmask;
790 snd_pcm_access_mask_alloca(&acmask);
791 snd_pcm_hw_params_get_access_mask(hw_params, acmask);
793 /* FIXME: NONITERLEAVED and COMPLEX are not supported right now */
794 if ( snd_pcm_access_mask_test( acmask, SND_PCM_ACCESS_MMAP_INTERLEAVED ) )
795 wwo->caps.dwSupport |= WAVECAPS_DIRECTSOUND;
798 TRACE("Configured with dwFmts=%08lx dwSupport=%08lx\n",
799 wwo->caps.dwFormats, wwo->caps.dwSupport);
801 snd_pcm_close(h);
803 ALSA_InitializeVolumeCtl(wwo);
805 wwi = &WInDev[0];
807 /* FIXME: use better values */
808 wwi->device = ALSA_GetDeviceFromReg("RecordDevice");
809 TRACE("using wavein device \"%s\"\n", wwi->device);
811 snprintf(wwi->interface_name, sizeof(wwi->interface_name), "winealsa: %s", wwi->device);
813 wwi->caps.wMid = 0x0002;
814 wwi->caps.wPid = 0x0104;
815 strcpy(wwi->caps.szPname, "SB16 Wave In");
816 wwi->caps.vDriverVersion = 0x0100;
817 wwi->caps.dwFormats = 0x00000000;
818 wwi->caps.dwSupport = WAVECAPS_VOLUME;
819 strcpy(wwi->ds_desc.szDesc, "WineALSA DirectSound Driver");
820 strcpy(wwi->ds_desc.szDrvName, "winealsa.drv");
822 snd_pcm_info_alloca(&info);
823 snd_pcm_hw_params_alloca(&hw_params);
825 #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)
827 h = NULL;
828 ALSA_WidNumDevs = 0;
829 EXIT_ON_ERROR( snd_pcm_open(&h, wwi->device, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK) , "open pcm" );
830 if (!h) return -1;
831 ALSA_WidNumDevs++;
833 EXIT_ON_ERROR( snd_pcm_info(h, info) , "pcm info" );
835 TRACE("dev=%d id=%s name=%s subdev=%d subdev_name=%s subdev_avail=%d subdev_num=%d stream=%s subclass=%s \n",
836 snd_pcm_info_get_device(info),
837 snd_pcm_info_get_id(info),
838 snd_pcm_info_get_name(info),
839 snd_pcm_info_get_subdevice(info),
840 snd_pcm_info_get_subdevice_name(info),
841 snd_pcm_info_get_subdevices_avail(info),
842 snd_pcm_info_get_subdevices_count(info),
843 snd_pcm_stream_name(snd_pcm_info_get_stream(info)),
844 (snd_pcm_info_get_subclass(info) == SND_PCM_SUBCLASS_GENERIC_MIX ? "GENERIC MIX": "MULTI MIX"));
846 EXIT_ON_ERROR( snd_pcm_hw_params_any(h, hw_params) , "pcm hw params" );
847 #undef EXIT_ON_ERROR
848 err = snd_pcm_hw_params_get_rate_min(hw_params, &ratemin, &dir);
849 err = snd_pcm_hw_params_get_rate_max(hw_params, &ratemax, &dir);
850 err = snd_pcm_hw_params_get_channels_min(hw_params, &chmin);
851 err = snd_pcm_hw_params_get_channels_max(hw_params, &chmax);
853 if (TRACE_ON(wave))
854 ALSA_TraceParameters(hw_params, NULL, TRUE);
857 snd_pcm_format_mask_t * fmask;
859 snd_pcm_format_mask_alloca(&fmask);
860 snd_pcm_hw_params_get_format_mask(hw_params, fmask);
862 #define X(r,v) \
863 if ( (r) >= ratemin && ( (r) <= ratemax || ratemax == -1) ) \
865 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_U8)) \
867 if (chmin <= 1 && 1 <= chmax) \
868 wwi->caps.dwFormats |= WAVE_FORMAT_##v##M08; \
869 if (chmin <= 2 && 2 <= chmax) \
870 wwi->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
872 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_S16_LE)) \
874 if (chmin <= 1 && 1 <= chmax) \
875 wwi->caps.dwFormats |= WAVE_FORMAT_##v##M16; \
876 if (chmin <= 2 && 2 <= chmax) \
877 wwi->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
880 X(11025,1);
881 X(22050,2);
882 X(44100,4);
883 X(48000,48);
884 X(96000,96);
885 #undef X
888 if ( chmin > 1) FIXME("-\n");
889 wwi->caps.wChannels = chmax;
890 if (chmin <= 2 && 2 <= chmax)
891 wwi->caps.dwSupport |= WAVECAPS_LRVOLUME;
893 /* FIXME: always true ? */
894 wwi->caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
897 snd_pcm_access_mask_t * acmask;
898 snd_pcm_access_mask_alloca(&acmask);
899 snd_pcm_hw_params_get_access_mask(hw_params, acmask);
901 /* FIXME: NONITERLEAVED and COMPLEX are not supported right now */
902 if ( snd_pcm_access_mask_test( acmask, SND_PCM_ACCESS_MMAP_INTERLEAVED ) ) {
903 #if 0
904 wwi->caps.dwSupport |= WAVECAPS_DIRECTSOUND;
905 #endif
909 TRACE("Configured with dwFmts=%08lx dwSupport=%08lx\n",
910 wwi->caps.dwFormats, wwi->caps.dwSupport);
912 snd_pcm_close(h);
914 return 0;
917 /******************************************************************
918 * ALSA_InitRingMessage
920 * Initialize the ring of messages for passing between driver's caller and playback/record
921 * thread
923 static int ALSA_InitRingMessage(ALSA_MSG_RING* omr)
925 omr->msg_toget = 0;
926 omr->msg_tosave = 0;
927 #ifdef USE_PIPE_SYNC
928 if (pipe(omr->msg_pipe) < 0) {
929 omr->msg_pipe[0] = -1;
930 omr->msg_pipe[1] = -1;
931 ERR("could not create pipe, error=%s\n", strerror(errno));
933 #else
934 omr->msg_event = CreateEventA(NULL, FALSE, FALSE, NULL);
935 #endif
936 omr->ring_buffer_size = ALSA_RING_BUFFER_INCREMENT;
937 omr->messages = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,omr->ring_buffer_size * sizeof(ALSA_MSG));
939 InitializeCriticalSection(&omr->msg_crst);
940 return 0;
943 /******************************************************************
944 * ALSA_DestroyRingMessage
947 static int ALSA_DestroyRingMessage(ALSA_MSG_RING* omr)
949 #ifdef USE_PIPE_SYNC
950 close(omr->msg_pipe[0]);
951 close(omr->msg_pipe[1]);
952 #else
953 CloseHandle(omr->msg_event);
954 #endif
955 HeapFree(GetProcessHeap(),0,omr->messages);
956 DeleteCriticalSection(&omr->msg_crst);
957 return 0;
960 /******************************************************************
961 * ALSA_AddRingMessage
963 * Inserts a new message into the ring (should be called from DriverProc derivated routines)
965 static int ALSA_AddRingMessage(ALSA_MSG_RING* omr, enum win_wm_message msg, DWORD param, BOOL wait)
967 HANDLE hEvent = INVALID_HANDLE_VALUE;
969 EnterCriticalSection(&omr->msg_crst);
970 if ((omr->msg_toget == ((omr->msg_tosave + 1) % omr->ring_buffer_size)))
972 int old_ring_buffer_size = omr->ring_buffer_size;
973 omr->ring_buffer_size += ALSA_RING_BUFFER_INCREMENT;
974 TRACE("omr->ring_buffer_size=%d\n",omr->ring_buffer_size);
975 omr->messages = HeapReAlloc(GetProcessHeap(),0,omr->messages, omr->ring_buffer_size * sizeof(ALSA_MSG));
976 /* Now we need to rearrange the ring buffer so that the new
977 buffers just allocated are in between omr->msg_tosave and
978 omr->msg_toget.
980 if (omr->msg_tosave < omr->msg_toget)
982 memmove(&(omr->messages[omr->msg_toget + ALSA_RING_BUFFER_INCREMENT]),
983 &(omr->messages[omr->msg_toget]),
984 sizeof(ALSA_MSG)*(old_ring_buffer_size - omr->msg_toget)
986 omr->msg_toget += ALSA_RING_BUFFER_INCREMENT;
989 if (wait)
991 hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
992 if (hEvent == INVALID_HANDLE_VALUE)
994 ERR("can't create event !?\n");
995 LeaveCriticalSection(&omr->msg_crst);
996 return 0;
998 if (omr->msg_toget != omr->msg_tosave && omr->messages[omr->msg_toget].msg != WINE_WM_HEADER)
999 FIXME("two fast messages in the queue!!!! toget = %d(%s), tosave=%d(%s)\n",
1000 omr->msg_toget,getCmdString(omr->messages[omr->msg_toget].msg),
1001 omr->msg_tosave,getCmdString(omr->messages[omr->msg_tosave].msg));
1003 /* fast messages have to be added at the start of the queue */
1004 omr->msg_toget = (omr->msg_toget + omr->ring_buffer_size - 1) % omr->ring_buffer_size;
1006 omr->messages[omr->msg_toget].msg = msg;
1007 omr->messages[omr->msg_toget].param = param;
1008 omr->messages[omr->msg_toget].hEvent = hEvent;
1010 else
1012 omr->messages[omr->msg_tosave].msg = msg;
1013 omr->messages[omr->msg_tosave].param = param;
1014 omr->messages[omr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
1015 omr->msg_tosave = (omr->msg_tosave + 1) % omr->ring_buffer_size;
1017 LeaveCriticalSection(&omr->msg_crst);
1018 /* signal a new message */
1019 SIGNAL_OMR(omr);
1020 if (wait)
1022 /* wait for playback/record thread to have processed the message */
1023 WaitForSingleObject(hEvent, INFINITE);
1024 CloseHandle(hEvent);
1026 return 1;
1029 /******************************************************************
1030 * ALSA_RetrieveRingMessage
1032 * Get a message from the ring. Should be called by the playback/record thread.
1034 static int ALSA_RetrieveRingMessage(ALSA_MSG_RING* omr,
1035 enum win_wm_message *msg, DWORD *param, HANDLE *hEvent)
1037 EnterCriticalSection(&omr->msg_crst);
1039 if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
1041 LeaveCriticalSection(&omr->msg_crst);
1042 return 0;
1045 *msg = omr->messages[omr->msg_toget].msg;
1046 omr->messages[omr->msg_toget].msg = 0;
1047 *param = omr->messages[omr->msg_toget].param;
1048 *hEvent = omr->messages[omr->msg_toget].hEvent;
1049 omr->msg_toget = (omr->msg_toget + 1) % omr->ring_buffer_size;
1050 CLEAR_OMR(omr);
1051 LeaveCriticalSection(&omr->msg_crst);
1052 return 1;
1055 /******************************************************************
1056 * ALSA_PeekRingMessage
1058 * Peek at a message from the ring but do not remove it.
1059 * Should be called by the playback/record thread.
1061 static int ALSA_PeekRingMessage(ALSA_MSG_RING* omr,
1062 enum win_wm_message *msg,
1063 DWORD *param, HANDLE *hEvent)
1065 EnterCriticalSection(&omr->msg_crst);
1067 if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
1069 LeaveCriticalSection(&omr->msg_crst);
1070 return 0;
1073 *msg = omr->messages[omr->msg_toget].msg;
1074 *param = omr->messages[omr->msg_toget].param;
1075 *hEvent = omr->messages[omr->msg_toget].hEvent;
1076 LeaveCriticalSection(&omr->msg_crst);
1077 return 1;
1080 /*======================================================================*
1081 * Low level WAVE OUT implementation *
1082 *======================================================================*/
1084 /**************************************************************************
1085 * wodNotifyClient [internal]
1087 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1089 TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
1091 switch (wMsg) {
1092 case WOM_OPEN:
1093 case WOM_CLOSE:
1094 case WOM_DONE:
1095 if (wwo->wFlags != DCB_NULL &&
1096 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags, (HDRVR)wwo->waveDesc.hWave,
1097 wMsg, wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
1098 WARN("can't notify client !\n");
1099 return MMSYSERR_ERROR;
1101 break;
1102 default:
1103 FIXME("Unknown callback message %u\n", wMsg);
1104 return MMSYSERR_INVALPARAM;
1106 return MMSYSERR_NOERROR;
1109 /**************************************************************************
1110 * wodUpdatePlayedTotal [internal]
1113 static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo, snd_pcm_status_t* ps)
1115 snd_pcm_sframes_t delay = 0;
1116 snd_pcm_delay(wwo->p_handle, &delay);
1117 if (snd_pcm_state(wwo->p_handle) != SND_PCM_STATE_RUNNING)
1118 delay=0;
1119 wwo->dwPlayedTotal = wwo->dwWrittenTotal - snd_pcm_frames_to_bytes(wwo->p_handle, delay);
1120 return TRUE;
1123 /**************************************************************************
1124 * wodPlayer_BeginWaveHdr [internal]
1126 * Makes the specified lpWaveHdr the currently playing wave header.
1127 * If the specified wave header is a begin loop and we're not already in
1128 * a loop, setup the loop.
1130 static void wodPlayer_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1132 wwo->lpPlayPtr = lpWaveHdr;
1134 if (!lpWaveHdr) return;
1136 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
1137 if (wwo->lpLoopPtr) {
1138 WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1139 } else {
1140 TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1141 wwo->lpLoopPtr = lpWaveHdr;
1142 /* Windows does not touch WAVEHDR.dwLoops,
1143 * so we need to make an internal copy */
1144 wwo->dwLoops = lpWaveHdr->dwLoops;
1147 wwo->dwPartialOffset = 0;
1150 /**************************************************************************
1151 * wodPlayer_PlayPtrNext [internal]
1153 * Advance the play pointer to the next waveheader, looping if required.
1155 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEOUT* wwo)
1157 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1159 wwo->dwPartialOffset = 0;
1160 if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
1161 /* We're at the end of a loop, loop if required */
1162 if (--wwo->dwLoops > 0) {
1163 wwo->lpPlayPtr = wwo->lpLoopPtr;
1164 } else {
1165 /* Handle overlapping loops correctly */
1166 if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
1167 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
1168 /* shall we consider the END flag for the closing loop or for
1169 * the opening one or for both ???
1170 * code assumes for closing loop only
1172 } else {
1173 lpWaveHdr = lpWaveHdr->lpNext;
1175 wwo->lpLoopPtr = NULL;
1176 wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
1178 } else {
1179 /* We're not in a loop. Advance to the next wave header */
1180 wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
1183 return lpWaveHdr;
1186 /**************************************************************************
1187 * wodPlayer_DSPWait [internal]
1188 * Returns the number of milliseconds to wait for the DSP buffer to play a
1189 * period
1191 static DWORD wodPlayer_DSPWait(const WINE_WAVEOUT *wwo)
1193 /* time for one period to be played */
1194 unsigned int val=0;
1195 int dir=0;
1196 int err=0;
1197 err = snd_pcm_hw_params_get_period_time(wwo->hw_params, &val, &dir);
1198 return val / 1000;
1201 /**************************************************************************
1202 * wodPlayer_NotifyWait [internal]
1203 * Returns the number of milliseconds to wait before attempting to notify
1204 * completion of the specified wavehdr.
1205 * This is based on the number of bytes remaining to be written in the
1206 * wave.
1208 static DWORD wodPlayer_NotifyWait(const WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1210 DWORD dwMillis;
1212 if (lpWaveHdr->reserved < wwo->dwPlayedTotal) {
1213 dwMillis = 1;
1214 } else {
1215 dwMillis = (lpWaveHdr->reserved - wwo->dwPlayedTotal) * 1000 / wwo->format.Format.nAvgBytesPerSec;
1216 if (!dwMillis) dwMillis = 1;
1219 return dwMillis;
1223 /**************************************************************************
1224 * wodPlayer_WriteMaxFrags [internal]
1225 * Writes the maximum number of frames possible to the DSP and returns
1226 * the number of frames written.
1228 static int wodPlayer_WriteMaxFrags(WINE_WAVEOUT* wwo, DWORD* frames)
1230 /* Only attempt to write to free frames */
1231 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1232 DWORD dwLength = snd_pcm_bytes_to_frames(wwo->p_handle, lpWaveHdr->dwBufferLength - wwo->dwPartialOffset);
1233 int toWrite = min(dwLength, *frames);
1234 int written;
1236 TRACE("Writing wavehdr %p.%lu[%lu]\n", lpWaveHdr, wwo->dwPartialOffset, lpWaveHdr->dwBufferLength);
1238 written = (wwo->write)(wwo->p_handle, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
1239 if ( written < 0)
1241 /* XRUN occurred. let's try to recover */
1242 ALSA_XRUNRecovery(wwo, written);
1243 written = (wwo->write)(wwo->p_handle, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
1245 if (written <= 0)
1247 /* still in error */
1248 ERR("Error in writing wavehdr. Reason: %s\n", snd_strerror(written));
1249 return written;
1252 wwo->dwPartialOffset += snd_pcm_frames_to_bytes(wwo->p_handle, written);
1253 if ( wwo->dwPartialOffset >= lpWaveHdr->dwBufferLength) {
1254 /* this will be used to check if the given wave header has been fully played or not... */
1255 wwo->dwPartialOffset = lpWaveHdr->dwBufferLength;
1256 /* If we wrote all current wavehdr, skip to the next one */
1257 wodPlayer_PlayPtrNext(wwo);
1259 *frames -= written;
1260 wwo->dwWrittenTotal += snd_pcm_frames_to_bytes(wwo->p_handle, written);
1262 return written;
1266 /**************************************************************************
1267 * wodPlayer_NotifyCompletions [internal]
1269 * Notifies and remove from queue all wavehdrs which have been played to
1270 * the speaker (ie. they have cleared the ALSA buffer). If force is true,
1271 * we notify all wavehdrs and remove them all from the queue even if they
1272 * are unplayed or part of a loop.
1274 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1276 LPWAVEHDR lpWaveHdr;
1278 /* Start from lpQueuePtr and keep notifying until:
1279 * - we hit an unwritten wavehdr
1280 * - we hit the beginning of a running loop
1281 * - we hit a wavehdr which hasn't finished playing
1283 #if 0
1284 while ((lpWaveHdr = wwo->lpQueuePtr) &&
1285 (force ||
1286 (lpWaveHdr != wwo->lpPlayPtr &&
1287 lpWaveHdr != wwo->lpLoopPtr &&
1288 lpWaveHdr->reserved <= wwo->dwPlayedTotal))) {
1290 wwo->lpQueuePtr = lpWaveHdr->lpNext;
1292 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1293 lpWaveHdr->dwFlags |= WHDR_DONE;
1295 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1297 #else
1298 for (;;)
1300 lpWaveHdr = wwo->lpQueuePtr;
1301 if (!lpWaveHdr) {TRACE("Empty queue\n"); break;}
1302 if (!force)
1304 if (lpWaveHdr == wwo->lpPlayPtr) {TRACE("play %p\n", lpWaveHdr); break;}
1305 if (lpWaveHdr == wwo->lpLoopPtr) {TRACE("loop %p\n", lpWaveHdr); break;}
1306 if (lpWaveHdr->reserved > wwo->dwPlayedTotal){TRACE("still playing %p (%lu/%lu)\n", lpWaveHdr, lpWaveHdr->reserved, wwo->dwPlayedTotal);break;}
1308 wwo->lpQueuePtr = lpWaveHdr->lpNext;
1310 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1311 lpWaveHdr->dwFlags |= WHDR_DONE;
1313 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1315 #endif
1316 return (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
1317 wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
1321 void wait_for_poll(snd_pcm_t *handle, struct pollfd *ufds, unsigned int count)
1323 unsigned short revents;
1325 if (snd_pcm_state(handle) != SND_PCM_STATE_RUNNING)
1326 return;
1328 while (1) {
1329 poll(ufds, count, -1);
1330 snd_pcm_poll_descriptors_revents(handle, ufds, count, &revents);
1332 if (revents & POLLERR)
1333 return;
1335 /*if (revents & POLLOUT)
1336 return 0;*/
1341 /**************************************************************************
1342 * wodPlayer_Reset [internal]
1344 * wodPlayer helper. Resets current output stream.
1346 static void wodPlayer_Reset(WINE_WAVEOUT* wwo)
1348 enum win_wm_message msg;
1349 DWORD param;
1350 HANDLE ev;
1351 int err;
1353 /* flush all possible output */
1354 wait_for_poll(wwo->p_handle, wwo->ufds, wwo->count);
1356 wodUpdatePlayedTotal(wwo, NULL);
1357 /* updates current notify list */
1358 wodPlayer_NotifyCompletions(wwo, FALSE);
1360 if ( (err = snd_pcm_drop(wwo->p_handle)) < 0) {
1361 FIXME("flush: %s\n", snd_strerror(err));
1362 wwo->hThread = 0;
1363 wwo->state = WINE_WS_STOPPED;
1364 ExitThread(-1);
1366 if ( (err = snd_pcm_prepare(wwo->p_handle)) < 0 )
1367 ERR("pcm prepare failed: %s\n", snd_strerror(err));
1369 /* remove any buffer */
1370 wodPlayer_NotifyCompletions(wwo, TRUE);
1372 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1373 wwo->state = WINE_WS_STOPPED;
1374 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1375 /* Clear partial wavehdr */
1376 wwo->dwPartialOffset = 0;
1378 /* remove any existing message in the ring */
1379 EnterCriticalSection(&wwo->msgRing.msg_crst);
1380 /* return all pending headers in queue */
1381 while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
1383 if (msg != WINE_WM_HEADER)
1385 FIXME("shouldn't have headers left\n");
1386 SetEvent(ev);
1387 continue;
1389 ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
1390 ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
1392 wodNotifyClient(wwo, WOM_DONE, param, 0);
1394 RESET_OMR(&wwo->msgRing);
1395 LeaveCriticalSection(&wwo->msgRing.msg_crst);
1398 /**************************************************************************
1399 * wodPlayer_ProcessMessages [internal]
1401 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
1403 LPWAVEHDR lpWaveHdr;
1404 enum win_wm_message msg;
1405 DWORD param;
1406 HANDLE ev;
1407 int err;
1409 while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
1410 TRACE("Received %s %lx\n", getCmdString(msg), param);
1412 switch (msg) {
1413 case WINE_WM_PAUSING:
1414 if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_RUNNING )
1416 err = snd_pcm_pause(wwo->p_handle, 1);
1417 if ( err < 0 )
1418 ERR("pcm_pause failed: %s\n", snd_strerror(err));
1420 wwo->state = WINE_WS_PAUSED;
1421 SetEvent(ev);
1422 break;
1423 case WINE_WM_RESTARTING:
1424 if (wwo->state == WINE_WS_PAUSED)
1426 if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_PAUSED )
1428 err = snd_pcm_pause(wwo->p_handle, 0);
1429 if ( err < 0 )
1430 ERR("pcm_pause failed: %s\n", snd_strerror(err));
1432 wwo->state = WINE_WS_PLAYING;
1434 SetEvent(ev);
1435 break;
1436 case WINE_WM_HEADER:
1437 lpWaveHdr = (LPWAVEHDR)param;
1439 /* insert buffer at the end of queue */
1441 LPWAVEHDR* wh;
1442 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1443 *wh = lpWaveHdr;
1445 if (!wwo->lpPlayPtr)
1446 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
1447 if (wwo->state == WINE_WS_STOPPED)
1448 wwo->state = WINE_WS_PLAYING;
1449 break;
1450 case WINE_WM_RESETTING:
1451 wodPlayer_Reset(wwo);
1452 SetEvent(ev);
1453 break;
1454 case WINE_WM_UPDATE:
1455 wodUpdatePlayedTotal(wwo, NULL);
1456 SetEvent(ev);
1457 break;
1458 case WINE_WM_BREAKLOOP:
1459 if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
1460 /* ensure exit at end of current loop */
1461 wwo->dwLoops = 1;
1463 SetEvent(ev);
1464 break;
1465 case WINE_WM_CLOSING:
1466 /* sanity check: this should not happen since the device must have been reset before */
1467 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1468 wwo->hThread = 0;
1469 wwo->state = WINE_WS_CLOSED;
1470 SetEvent(ev);
1471 ExitThread(0);
1472 /* shouldn't go here */
1473 default:
1474 FIXME("unknown message %d\n", msg);
1475 break;
1480 /**************************************************************************
1481 * wodPlayer_FeedDSP [internal]
1482 * Feed as much sound data as we can into the DSP and return the number of
1483 * milliseconds before it will be necessary to feed the DSP again.
1485 static DWORD wodPlayer_FeedDSP(WINE_WAVEOUT* wwo)
1487 DWORD availInQ;
1489 wodUpdatePlayedTotal(wwo, NULL);
1490 availInQ = snd_pcm_avail_update(wwo->p_handle);
1492 #if 0
1493 /* input queue empty and output buffer with less than one fragment to play */
1494 if (!wwo->lpPlayPtr && wwo->dwBufferSize < availInQ + wwo->dwFragmentSize) {
1495 TRACE("Run out of wavehdr:s...\n");
1496 return INFINITE;
1498 #endif
1500 /* no more room... no need to try to feed */
1501 if (availInQ > 0) {
1502 /* Feed from partial wavehdr */
1503 if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0) {
1504 wodPlayer_WriteMaxFrags(wwo, &availInQ);
1507 /* Feed wavehdrs until we run out of wavehdrs or DSP space */
1508 if (wwo->dwPartialOffset == 0 && wwo->lpPlayPtr) {
1509 do {
1510 TRACE("Setting time to elapse for %p to %lu\n",
1511 wwo->lpPlayPtr, wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength);
1512 /* note the value that dwPlayedTotal will return when this wave finishes playing */
1513 wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
1514 } while (wodPlayer_WriteMaxFrags(wwo, &availInQ) && wwo->lpPlayPtr && availInQ > 0);
1518 return wodPlayer_DSPWait(wwo);
1521 /**************************************************************************
1522 * wodPlayer [internal]
1524 static DWORD CALLBACK wodPlayer(LPVOID pmt)
1526 WORD uDevID = (DWORD)pmt;
1527 WINE_WAVEOUT* wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
1528 DWORD dwNextFeedTime = INFINITE; /* Time before DSP needs feeding */
1529 DWORD dwNextNotifyTime = INFINITE; /* Time before next wave completion */
1530 DWORD dwSleepTime;
1532 wwo->state = WINE_WS_STOPPED;
1533 SetEvent(wwo->hStartUpEvent);
1535 for (;;) {
1536 /** Wait for the shortest time before an action is required. If there
1537 * are no pending actions, wait forever for a command.
1539 dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
1540 TRACE("waiting %lums (%lu,%lu)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
1541 WAIT_OMR(&wwo->msgRing, dwSleepTime);
1542 wodPlayer_ProcessMessages(wwo);
1543 if (wwo->state == WINE_WS_PLAYING) {
1544 dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1545 dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1546 if (dwNextFeedTime == INFINITE) {
1547 /* FeedDSP ran out of data, but before giving up, */
1548 /* check that a notification didn't give us more */
1549 wodPlayer_ProcessMessages(wwo);
1550 if (wwo->lpPlayPtr) {
1551 TRACE("recovering\n");
1552 dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1555 } else {
1556 dwNextFeedTime = dwNextNotifyTime = INFINITE;
1561 /**************************************************************************
1562 * wodGetDevCaps [internal]
1564 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSA lpCaps, DWORD dwSize)
1566 TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1568 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1570 if (wDevID >= MAX_WAVEOUTDRV) {
1571 TRACE("MAX_WAVOUTDRV reached !\n");
1572 return MMSYSERR_BADDEVICEID;
1575 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1576 return MMSYSERR_NOERROR;
1579 /**************************************************************************
1580 * wodOpen [internal]
1582 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1584 WINE_WAVEOUT* wwo;
1585 snd_pcm_hw_params_t * hw_params;
1586 snd_pcm_sw_params_t * sw_params;
1587 snd_pcm_access_t access;
1588 snd_pcm_format_t format = -1;
1589 unsigned int rate;
1590 unsigned int buffer_time = 500000;
1591 unsigned int period_time = 10000;
1592 snd_pcm_uframes_t buffer_size;
1593 snd_pcm_uframes_t period_size;
1594 int flags;
1595 snd_pcm_t * pcm;
1596 int err=0;
1597 int dir=0;
1599 snd_pcm_hw_params_alloca(&hw_params);
1600 snd_pcm_sw_params_alloca(&sw_params);
1602 TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
1603 if (lpDesc == NULL) {
1604 WARN("Invalid Parameter !\n");
1605 return MMSYSERR_INVALPARAM;
1607 if (wDevID >= MAX_WAVEOUTDRV) {
1608 TRACE("MAX_WAVOUTDRV reached !\n");
1609 return MMSYSERR_BADDEVICEID;
1612 /* only PCM format is supported so far... */
1613 if (!supportedFormat(lpDesc->lpFormat)) {
1614 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1615 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1616 lpDesc->lpFormat->nSamplesPerSec);
1617 return WAVERR_BADFORMAT;
1620 if (dwFlags & WAVE_FORMAT_QUERY) {
1621 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1622 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1623 lpDesc->lpFormat->nSamplesPerSec);
1624 return MMSYSERR_NOERROR;
1627 wwo = &WOutDev[wDevID];
1629 if ((dwFlags & WAVE_DIRECTSOUND) && !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
1630 /* not supported, ignore it */
1631 dwFlags &= ~WAVE_DIRECTSOUND;
1633 wwo->p_handle = 0;
1634 flags = SND_PCM_NONBLOCK;
1635 if ( dwFlags & WAVE_DIRECTSOUND )
1636 flags |= SND_PCM_ASYNC;
1638 if ( (err = snd_pcm_open(&pcm, wwo->device, SND_PCM_STREAM_PLAYBACK, flags)) < 0)
1640 ERR("Error open: %s\n", snd_strerror(err));
1641 return MMSYSERR_NOTENABLED;
1644 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1646 memcpy(&wwo->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
1647 copy_format(lpDesc->lpFormat, &wwo->format);
1649 if (wwo->format.Format.wBitsPerSample == 0) {
1650 WARN("Resetting zeroed wBitsPerSample\n");
1651 wwo->format.Format.wBitsPerSample = 8 *
1652 (wwo->format.Format.nAvgBytesPerSec /
1653 wwo->format.Format.nSamplesPerSec) /
1654 wwo->format.Format.nChannels;
1657 snd_pcm_hw_params_any(pcm, hw_params);
1659 #define EXIT_ON_ERROR(f,e,txt) do \
1661 int err; \
1662 if ( (err = (f) ) < 0) \
1664 ERR(txt ": %s\n", snd_strerror(err)); \
1665 snd_pcm_close(pcm); \
1666 return e; \
1668 } while(0)
1670 access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
1671 if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
1672 WARN("mmap not available. switching to standard write.\n");
1673 access = SND_PCM_ACCESS_RW_INTERLEAVED;
1674 EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
1675 wwo->write = snd_pcm_writei;
1677 else
1678 wwo->write = snd_pcm_mmap_writei;
1680 EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwo->format.Format.nChannels), MMSYSERR_INVALPARAM, "unable to set required channels");
1682 if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
1683 ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
1684 IsEqualGUID(&wwo->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
1685 format = (wwo->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
1686 (wwo->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
1687 (wwo->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
1688 (wwo->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
1689 } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
1690 FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
1691 snd_pcm_close(pcm);
1692 return WAVERR_BADFORMAT;
1693 } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
1694 FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
1695 snd_pcm_close(pcm);
1696 return WAVERR_BADFORMAT;
1697 } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
1698 FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
1699 snd_pcm_close(pcm);
1700 return WAVERR_BADFORMAT;
1701 } else {
1702 ERR("invalid format: %0x04x\n", wwo->format.Format.wFormatTag);
1703 snd_pcm_close(pcm);
1704 return WAVERR_BADFORMAT;
1707 EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), MMSYSERR_INVALPARAM, "unable to set required format");
1709 rate = wwo->format.Format.nSamplesPerSec;
1710 dir=0;
1711 err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
1712 if (err < 0) {
1713 ERR("Rate %ld Hz not available for playback: %s\n", wwo->format.Format.nSamplesPerSec, snd_strerror(rate));
1714 snd_pcm_close(pcm);
1715 return WAVERR_BADFORMAT;
1717 if (rate != wwo->format.Format.nSamplesPerSec) {
1718 ERR("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwo->format.Format.nSamplesPerSec, rate);
1719 snd_pcm_close(pcm);
1720 return WAVERR_BADFORMAT;
1722 dir=0;
1723 EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
1724 dir=0;
1725 EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
1727 EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
1729 err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
1730 err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
1732 snd_pcm_sw_params_current(pcm, sw_params);
1733 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");
1734 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
1735 EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
1736 EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
1737 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
1738 EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
1739 #undef EXIT_ON_ERROR
1741 snd_pcm_prepare(pcm);
1743 if (TRACE_ON(wave))
1744 ALSA_TraceParameters(hw_params, sw_params, FALSE);
1746 /* now, we can save all required data for later use... */
1747 if ( wwo->hw_params )
1748 snd_pcm_hw_params_free(wwo->hw_params);
1749 snd_pcm_hw_params_malloc(&(wwo->hw_params));
1750 snd_pcm_hw_params_copy(wwo->hw_params, hw_params);
1752 wwo->dwBufferSize = buffer_size;
1753 wwo->lpQueuePtr = wwo->lpPlayPtr = wwo->lpLoopPtr = NULL;
1754 wwo->p_handle = pcm;
1755 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1756 wwo->dwPartialOffset = 0;
1758 ALSA_InitRingMessage(&wwo->msgRing);
1760 wwo->count = snd_pcm_poll_descriptors_count (wwo->p_handle);
1761 if (wwo->count <= 0) {
1762 ERR("Invalid poll descriptors count\n");
1763 return MMSYSERR_ERROR;
1766 wwo->ufds = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct pollfd) * wwo->count);
1767 if (wwo->ufds == NULL) {
1768 ERR("No enough memory\n");
1769 return MMSYSERR_NOMEM;
1771 if ((err = snd_pcm_poll_descriptors(wwo->p_handle, wwo->ufds, wwo->count)) < 0) {
1772 ERR("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
1773 return MMSYSERR_ERROR;
1776 if (!(dwFlags & WAVE_DIRECTSOUND)) {
1777 wwo->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
1778 wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
1779 WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
1780 CloseHandle(wwo->hStartUpEvent);
1781 } else {
1782 wwo->hThread = INVALID_HANDLE_VALUE;
1783 wwo->dwThreadID = 0;
1785 wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
1787 TRACE("handle=%08lx \n", (DWORD)wwo->p_handle);
1788 /* if (wwo->dwFragmentSize % wwo->format.Format.nBlockAlign)
1789 ERR("Fragment doesn't contain an integral number of data blocks\n");
1791 TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
1792 wwo->format.Format.wBitsPerSample, wwo->format.Format.nAvgBytesPerSec,
1793 wwo->format.Format.nSamplesPerSec, wwo->format.Format.nChannels,
1794 wwo->format.Format.nBlockAlign);
1796 return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
1800 /**************************************************************************
1801 * wodClose [internal]
1803 static DWORD wodClose(WORD wDevID)
1805 DWORD ret = MMSYSERR_NOERROR;
1806 WINE_WAVEOUT* wwo;
1808 TRACE("(%u);\n", wDevID);
1810 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1811 WARN("bad device ID !\n");
1812 return MMSYSERR_BADDEVICEID;
1815 wwo = &WOutDev[wDevID];
1816 if (wwo->lpQueuePtr) {
1817 WARN("buffers still playing !\n");
1818 ret = WAVERR_STILLPLAYING;
1819 } else {
1820 if (wwo->hThread != INVALID_HANDLE_VALUE) {
1821 ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1823 ALSA_DestroyRingMessage(&wwo->msgRing);
1825 snd_pcm_hw_params_free(wwo->hw_params);
1826 wwo->hw_params = NULL;
1828 snd_pcm_close(wwo->p_handle);
1829 wwo->p_handle = NULL;
1831 ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1834 HeapFree(GetProcessHeap(), 0, wwo->ufds);
1835 return ret;
1839 /**************************************************************************
1840 * wodWrite [internal]
1843 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1845 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1847 /* first, do the sanity checks... */
1848 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1849 WARN("bad dev ID !\n");
1850 return MMSYSERR_BADDEVICEID;
1853 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1854 return WAVERR_UNPREPARED;
1856 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1857 return WAVERR_STILLPLAYING;
1859 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1860 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1861 lpWaveHdr->lpNext = 0;
1863 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1865 return MMSYSERR_NOERROR;
1868 /**************************************************************************
1869 * wodPrepare [internal]
1871 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1873 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1875 if (wDevID >= MAX_WAVEOUTDRV) {
1876 WARN("bad device ID !\n");
1877 return MMSYSERR_BADDEVICEID;
1880 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1881 return WAVERR_STILLPLAYING;
1883 lpWaveHdr->dwFlags |= WHDR_PREPARED;
1884 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1885 return MMSYSERR_NOERROR;
1888 /**************************************************************************
1889 * wodUnprepare [internal]
1891 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1893 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1895 if (wDevID >= MAX_WAVEOUTDRV) {
1896 WARN("bad device ID !\n");
1897 return MMSYSERR_BADDEVICEID;
1900 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1901 return WAVERR_STILLPLAYING;
1903 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1904 lpWaveHdr->dwFlags |= WHDR_DONE;
1906 return MMSYSERR_NOERROR;
1909 /**************************************************************************
1910 * wodPause [internal]
1912 static DWORD wodPause(WORD wDevID)
1914 TRACE("(%u);!\n", wDevID);
1916 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1917 WARN("bad device ID !\n");
1918 return MMSYSERR_BADDEVICEID;
1921 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1923 return MMSYSERR_NOERROR;
1926 /**************************************************************************
1927 * wodRestart [internal]
1929 static DWORD wodRestart(WORD wDevID)
1931 TRACE("(%u);\n", wDevID);
1933 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1934 WARN("bad device ID !\n");
1935 return MMSYSERR_BADDEVICEID;
1938 if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1939 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1942 /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1943 /* FIXME: Myst crashes with this ... hmm -MM
1944 return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1947 return MMSYSERR_NOERROR;
1950 /**************************************************************************
1951 * wodReset [internal]
1953 static DWORD wodReset(WORD wDevID)
1955 TRACE("(%u);\n", wDevID);
1957 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1958 WARN("bad device ID !\n");
1959 return MMSYSERR_BADDEVICEID;
1962 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1964 return MMSYSERR_NOERROR;
1967 /**************************************************************************
1968 * wodGetPosition [internal]
1970 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1972 WINE_WAVEOUT* wwo;
1974 TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1976 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1977 WARN("bad device ID !\n");
1978 return MMSYSERR_BADDEVICEID;
1981 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1983 wwo = &WOutDev[wDevID];
1984 ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1986 return bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->format);
1989 /**************************************************************************
1990 * wodBreakLoop [internal]
1992 static DWORD wodBreakLoop(WORD wDevID)
1994 TRACE("(%u);\n", wDevID);
1996 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1997 WARN("bad device ID !\n");
1998 return MMSYSERR_BADDEVICEID;
2000 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
2001 return MMSYSERR_NOERROR;
2004 /**************************************************************************
2005 * wodGetVolume [internal]
2007 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
2009 WORD left, right;
2010 WINE_WAVEOUT* wwo;
2011 int count;
2012 long min, max;
2014 TRACE("(%u, %p);\n", wDevID, lpdwVol);
2015 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
2016 WARN("bad device ID !\n");
2017 return MMSYSERR_BADDEVICEID;
2019 wwo = &WOutDev[wDevID];
2020 count = snd_ctl_elem_info_get_count(wwo->playback_einfo);
2021 min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
2022 max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
2024 #define VOLUME_ALSA_TO_WIN(x) (((x)-min) * 65536 /(max-min))
2025 if (lpdwVol == NULL)
2026 return MMSYSERR_NOTENABLED;
2028 switch (count)
2030 case 2:
2031 left = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
2032 right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 1));
2033 break;
2034 case 1:
2035 left = right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
2036 break;
2037 default:
2038 WARN("%d channels mixer not supported\n", count);
2039 return MMSYSERR_NOERROR;
2041 #undef VOLUME_ALSA_TO_WIN
2043 TRACE("left=%d right=%d !\n", left, right);
2044 *lpdwVol = MAKELONG( left, right );
2045 return MMSYSERR_NOERROR;
2048 /**************************************************************************
2049 * wodSetVolume [internal]
2051 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
2053 WORD left, right;
2054 WINE_WAVEOUT* wwo;
2055 int count, err;
2056 long min, max;
2058 TRACE("(%u, %08lX);\n", wDevID, dwParam);
2059 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
2060 WARN("bad device ID !\n");
2061 return MMSYSERR_BADDEVICEID;
2063 wwo = &WOutDev[wDevID];
2064 count=snd_ctl_elem_info_get_count(wwo->playback_einfo);
2065 min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
2066 max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
2068 left = LOWORD(dwParam);
2069 right = HIWORD(dwParam);
2071 #define VOLUME_WIN_TO_ALSA(x) ( (((x) * (max-min)) / 65536) + min )
2072 switch (count)
2074 case 2:
2075 snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
2076 snd_ctl_elem_value_set_integer(wwo->playback_evalue, 1, VOLUME_WIN_TO_ALSA(right));
2077 break;
2078 case 1:
2079 snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
2080 break;
2081 default:
2082 WARN("%d channels mixer not supported\n", count);
2084 #undef VOLUME_WIN_TO_ALSA
2085 if ( (err = snd_ctl_elem_write(wwo->ctl, wwo->playback_evalue)) < 0)
2087 ERR("error writing snd_ctl_elem_value: %s\n", snd_strerror(err));
2089 return MMSYSERR_NOERROR;
2092 /**************************************************************************
2093 * wodGetNumDevs [internal]
2095 static DWORD wodGetNumDevs(void)
2097 return ALSA_WodNumDevs;
2100 /**************************************************************************
2101 * wodDevInterfaceSize [internal]
2103 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2105 TRACE("(%u, %p)\n", wDevID, dwParam1);
2107 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2108 NULL, 0 ) * sizeof(WCHAR);
2109 return MMSYSERR_NOERROR;
2112 /**************************************************************************
2113 * wodDevInterface [internal]
2115 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2117 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2118 NULL, 0 ) * sizeof(WCHAR))
2120 MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2121 dwParam1, dwParam2 / sizeof(WCHAR));
2122 return MMSYSERR_NOERROR;
2124 return MMSYSERR_INVALPARAM;
2127 /**************************************************************************
2128 * wodMessage (WINEALSA.@)
2130 DWORD WINAPI ALSA_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
2131 DWORD dwParam1, DWORD dwParam2)
2133 TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
2134 wDevID, wMsg, dwUser, dwParam1, dwParam2);
2136 switch (wMsg) {
2137 case DRVM_INIT:
2138 case DRVM_EXIT:
2139 case DRVM_ENABLE:
2140 case DRVM_DISABLE:
2141 /* FIXME: Pretend this is supported */
2142 return 0;
2143 case WODM_OPEN: return wodOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2144 case WODM_CLOSE: return wodClose (wDevID);
2145 case WODM_GETDEVCAPS: return wodGetDevCaps (wDevID, (LPWAVEOUTCAPSA)dwParam1, dwParam2);
2146 case WODM_GETNUMDEVS: return wodGetNumDevs ();
2147 case WODM_GETPITCH: return MMSYSERR_NOTSUPPORTED;
2148 case WODM_SETPITCH: return MMSYSERR_NOTSUPPORTED;
2149 case WODM_GETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
2150 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
2151 case WODM_WRITE: return wodWrite (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2152 case WODM_PAUSE: return wodPause (wDevID);
2153 case WODM_GETPOS: return wodGetPosition (wDevID, (LPMMTIME)dwParam1, dwParam2);
2154 case WODM_BREAKLOOP: return wodBreakLoop (wDevID);
2155 case WODM_PREPARE: return wodPrepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2156 case WODM_UNPREPARE: return wodUnprepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2157 case WODM_GETVOLUME: return wodGetVolume (wDevID, (LPDWORD)dwParam1);
2158 case WODM_SETVOLUME: return wodSetVolume (wDevID, dwParam1);
2159 case WODM_RESTART: return wodRestart (wDevID);
2160 case WODM_RESET: return wodReset (wDevID);
2161 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2162 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2163 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
2164 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
2166 default:
2167 FIXME("unknown message %d!\n", wMsg);
2169 return MMSYSERR_NOTSUPPORTED;
2172 /*======================================================================*
2173 * Low level DSOUND implementation *
2174 *======================================================================*/
2176 typedef struct IDsDriverImpl IDsDriverImpl;
2177 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
2179 struct IDsDriverImpl
2181 /* IUnknown fields */
2182 IDsDriverVtbl *lpVtbl;
2183 DWORD ref;
2184 /* IDsDriverImpl fields */
2185 UINT wDevID;
2186 IDsDriverBufferImpl*primary;
2189 struct IDsDriverBufferImpl
2191 /* IUnknown fields */
2192 IDsDriverBufferVtbl *lpVtbl;
2193 DWORD ref;
2194 /* IDsDriverBufferImpl fields */
2195 IDsDriverImpl* drv;
2197 CRITICAL_SECTION mmap_crst;
2198 LPVOID mmap_buffer;
2199 DWORD mmap_buflen_bytes;
2200 snd_pcm_uframes_t mmap_buflen_frames;
2201 snd_pcm_channel_area_t * mmap_areas;
2202 snd_async_handler_t * mmap_async_handler;
2205 static void DSDB_CheckXRUN(IDsDriverBufferImpl* pdbi)
2207 WINE_WAVEOUT * wwo = &(WOutDev[pdbi->drv->wDevID]);
2208 snd_pcm_state_t state = snd_pcm_state(wwo->p_handle);
2210 if ( state == SND_PCM_STATE_XRUN )
2212 int err = snd_pcm_prepare(wwo->p_handle);
2213 TRACE("xrun occurred\n");
2214 if ( err < 0 )
2215 ERR("recovery from xrun failed, prepare failed: %s\n", snd_strerror(err));
2217 else if ( state == SND_PCM_STATE_SUSPENDED )
2219 int err = snd_pcm_resume(wwo->p_handle);
2220 TRACE("recovery from suspension occurred\n");
2221 if (err < 0 && err != -EAGAIN){
2222 err = snd_pcm_prepare(wwo->p_handle);
2223 if (err < 0)
2224 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
2229 static void DSDB_MMAPCopy(IDsDriverBufferImpl* pdbi)
2231 WINE_WAVEOUT * wwo = &(WOutDev[pdbi->drv->wDevID]);
2232 unsigned int channels;
2233 snd_pcm_format_t format;
2234 snd_pcm_uframes_t period_size;
2235 snd_pcm_sframes_t avail;
2236 int err;
2237 int dir=0;
2239 if ( !pdbi->mmap_buffer || !wwo->hw_params || !wwo->p_handle)
2240 return;
2242 err = snd_pcm_hw_params_get_channels(wwo->hw_params, &channels);
2243 err = snd_pcm_hw_params_get_format(wwo->hw_params, &format);
2244 dir=0;
2245 err = snd_pcm_hw_params_get_period_size(wwo->hw_params, &period_size, &dir);
2246 avail = snd_pcm_avail_update(wwo->p_handle);
2248 DSDB_CheckXRUN(pdbi);
2250 TRACE("avail=%d format=%s channels=%d\n", (int)avail, snd_pcm_format_name(format), channels );
2252 while (avail >= period_size)
2254 const snd_pcm_channel_area_t *areas;
2255 snd_pcm_uframes_t ofs;
2256 snd_pcm_uframes_t frames;
2257 int err;
2259 frames = avail / period_size * period_size; /* round down to a multiple of period_size */
2261 EnterCriticalSection(&pdbi->mmap_crst);
2263 snd_pcm_mmap_begin(wwo->p_handle, &areas, &ofs, &frames);
2264 snd_pcm_areas_copy(areas, ofs, pdbi->mmap_areas, ofs, channels, frames, format);
2265 err = snd_pcm_mmap_commit(wwo->p_handle, ofs, frames);
2267 LeaveCriticalSection(&pdbi->mmap_crst);
2269 if ( err != (snd_pcm_sframes_t) frames)
2270 ERR("mmap partially failed.\n");
2272 avail = snd_pcm_avail_update(wwo->p_handle);
2276 static void DSDB_PCMCallback(snd_async_handler_t *ahandler)
2278 /* snd_pcm_t * handle = snd_async_handler_get_pcm(ahandler); */
2279 IDsDriverBufferImpl* pdbi = snd_async_handler_get_callback_private(ahandler);
2280 TRACE("callback called\n");
2281 DSDB_MMAPCopy(pdbi);
2284 static int DSDB_CreateMMAP(IDsDriverBufferImpl* pdbi)
2286 WINE_WAVEOUT * wwo = &(WOutDev[pdbi->drv->wDevID]);
2287 snd_pcm_format_t format;
2288 snd_pcm_uframes_t frames;
2289 unsigned int channels;
2290 unsigned int bits_per_sample;
2291 unsigned int bits_per_frame;
2292 snd_pcm_channel_area_t * a;
2293 unsigned int c;
2294 int err;
2296 err = snd_pcm_hw_params_get_format(wwo->hw_params, &format);
2297 err = snd_pcm_hw_params_get_buffer_size(wwo->hw_params, &frames);
2298 err = snd_pcm_hw_params_get_channels(wwo->hw_params, &channels);
2299 bits_per_sample = snd_pcm_format_physical_width(format);
2300 bits_per_frame = bits_per_sample * channels;
2303 if (TRACE_ON(wave))
2304 ALSA_TraceParameters(wwo->hw_params, NULL, FALSE);
2306 TRACE("format=%s frames=%ld channels=%d bits_per_sample=%d bits_per_frame=%d\n",
2307 snd_pcm_format_name(format), frames, channels, bits_per_sample, bits_per_frame);
2309 pdbi->mmap_buflen_frames = frames;
2310 pdbi->mmap_buflen_bytes = snd_pcm_frames_to_bytes( wwo->p_handle, frames );
2311 pdbi->mmap_buffer = HeapAlloc(GetProcessHeap(),0,pdbi->mmap_buflen_bytes);
2312 if (!pdbi->mmap_buffer)
2313 return DSERR_OUTOFMEMORY;
2315 snd_pcm_format_set_silence(format, pdbi->mmap_buffer, frames );
2317 TRACE("created mmap buffer of %ld frames (%ld bytes) at %p\n",
2318 frames, pdbi->mmap_buflen_bytes, pdbi->mmap_buffer);
2320 pdbi->mmap_areas = HeapAlloc(GetProcessHeap(),0,channels*sizeof(snd_pcm_channel_area_t));
2321 if (!pdbi->mmap_areas)
2322 return DSERR_OUTOFMEMORY;
2324 a = pdbi->mmap_areas;
2325 for (c = 0; c < channels; c++, a++)
2327 a->addr = pdbi->mmap_buffer;
2328 a->first = bits_per_sample * c;
2329 a->step = bits_per_frame;
2330 TRACE("Area %d: addr=%p first=%d step=%d\n", c, a->addr, a->first, a->step);
2333 InitializeCriticalSection(&pdbi->mmap_crst);
2335 err = snd_async_add_pcm_handler(&pdbi->mmap_async_handler, wwo->p_handle, DSDB_PCMCallback, pdbi);
2336 if ( err < 0 )
2338 ERR("add_pcm_handler failed. reason: %s\n", snd_strerror(err));
2339 return DSERR_GENERIC;
2342 return DS_OK;
2345 static void DSDB_DestroyMMAP(IDsDriverBufferImpl* pdbi)
2347 TRACE("mmap buffer %p destroyed\n", pdbi->mmap_buffer);
2348 HeapFree(GetProcessHeap(), 0, pdbi->mmap_areas);
2349 HeapFree(GetProcessHeap(), 0, pdbi->mmap_buffer);
2350 pdbi->mmap_areas = NULL;
2351 pdbi->mmap_buffer = NULL;
2352 DeleteCriticalSection(&pdbi->mmap_crst);
2356 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
2358 /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2359 FIXME("(): stub!\n");
2360 return DSERR_UNSUPPORTED;
2363 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
2365 ICOM_THIS(IDsDriverBufferImpl,iface);
2366 TRACE("(%p)\n",iface);
2367 return ++This->ref;
2370 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
2372 ICOM_THIS(IDsDriverBufferImpl,iface);
2373 TRACE("(%p)\n",iface);
2374 if (--This->ref)
2375 return This->ref;
2376 if (This == This->drv->primary)
2377 This->drv->primary = NULL;
2378 DSDB_DestroyMMAP(This);
2379 HeapFree(GetProcessHeap(), 0, This);
2380 return 0;
2383 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
2384 LPVOID*ppvAudio1,LPDWORD pdwLen1,
2385 LPVOID*ppvAudio2,LPDWORD pdwLen2,
2386 DWORD dwWritePosition,DWORD dwWriteLen,
2387 DWORD dwFlags)
2389 /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2390 TRACE("(%p)\n",iface);
2391 return DSERR_UNSUPPORTED;
2394 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
2395 LPVOID pvAudio1,DWORD dwLen1,
2396 LPVOID pvAudio2,DWORD dwLen2)
2398 /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2399 TRACE("(%p)\n",iface);
2400 return DSERR_UNSUPPORTED;
2403 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
2404 LPWAVEFORMATEX pwfx)
2406 /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2407 TRACE("(%p,%p)\n",iface,pwfx);
2408 return DSERR_BUFFERLOST;
2411 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
2413 /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2414 TRACE("(%p,%ld): stub\n",iface,dwFreq);
2415 return DSERR_UNSUPPORTED;
2418 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
2420 DWORD vol;
2421 ICOM_THIS(IDsDriverBufferImpl,iface);
2422 TRACE("(%p,%p)\n",iface,pVolPan);
2423 vol = pVolPan->dwTotalLeftAmpFactor | (pVolPan->dwTotalRightAmpFactor << 16);
2425 if (wodSetVolume(This->drv->wDevID, vol) != MMSYSERR_NOERROR) {
2426 WARN("wodSetVolume failed\n");
2427 return DSERR_INVALIDPARAM;
2430 return DS_OK;
2433 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
2435 /* ICOM_THIS(IDsDriverImpl,iface); */
2436 TRACE("(%p,%ld): stub\n",iface,dwNewPos);
2437 return DSERR_UNSUPPORTED;
2440 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
2441 LPDWORD lpdwPlay, LPDWORD lpdwWrite)
2443 ICOM_THIS(IDsDriverBufferImpl,iface);
2444 WINE_WAVEOUT * wwo = &(WOutDev[This->drv->wDevID]);
2445 snd_pcm_uframes_t hw_ptr;
2446 snd_pcm_uframes_t period_size;
2447 int dir;
2448 int err;
2450 if (wwo->hw_params == NULL) return DSERR_GENERIC;
2452 dir=0;
2453 err = snd_pcm_hw_params_get_period_size(wwo->hw_params, &period_size, &dir);
2455 if (wwo->p_handle == NULL) return DSERR_GENERIC;
2456 /** we need to track down buffer underruns */
2457 DSDB_CheckXRUN(This);
2459 EnterCriticalSection(&This->mmap_crst);
2460 /* FIXME: snd_pcm_mmap_hw_ptr() should not be accessed by a user app. */
2461 /* It will NOT return what why want anyway. */
2462 hw_ptr = _snd_pcm_mmap_hw_ptr(wwo->p_handle);
2463 if (lpdwPlay)
2464 *lpdwPlay = snd_pcm_frames_to_bytes(wwo->p_handle, hw_ptr/ period_size * period_size) % This->mmap_buflen_bytes;
2465 if (lpdwWrite)
2466 *lpdwWrite = snd_pcm_frames_to_bytes(wwo->p_handle, (hw_ptr / period_size + 1) * period_size ) % This->mmap_buflen_bytes;
2467 LeaveCriticalSection(&This->mmap_crst);
2469 TRACE("hw_ptr=0x%08x, playpos=%ld, writepos=%ld\n", (unsigned int)hw_ptr, lpdwPlay?*lpdwPlay:-1, lpdwWrite?*lpdwWrite:-1);
2470 return DS_OK;
2473 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
2475 ICOM_THIS(IDsDriverBufferImpl,iface);
2476 WINE_WAVEOUT * wwo = &(WOutDev[This->drv->wDevID]);
2477 snd_pcm_state_t state;
2478 int err;
2480 TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
2482 if (wwo->p_handle == NULL) return DSERR_GENERIC;
2484 state = snd_pcm_state(wwo->p_handle);
2485 if ( state == SND_PCM_STATE_SETUP )
2487 err = snd_pcm_prepare(wwo->p_handle);
2488 state = snd_pcm_state(wwo->p_handle);
2490 if ( state == SND_PCM_STATE_PREPARED )
2492 DSDB_MMAPCopy(This);
2493 err = snd_pcm_start(wwo->p_handle);
2495 return DS_OK;
2498 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
2500 ICOM_THIS(IDsDriverBufferImpl,iface);
2501 WINE_WAVEOUT * wwo = &(WOutDev[This->drv->wDevID]);
2502 int err;
2503 DWORD play;
2504 DWORD write;
2506 TRACE("(%p)\n",iface);
2508 if (wwo->p_handle == NULL) return DSERR_GENERIC;
2510 /* ring buffer wrap up detection */
2511 IDsDriverBufferImpl_GetPosition(iface, &play, &write);
2512 if ( play > write)
2514 TRACE("writepos wrapper up\n");
2515 return DS_OK;
2518 if ( ( err = snd_pcm_drop(wwo->p_handle)) < 0 )
2520 ERR("error while stopping pcm: %s\n", snd_strerror(err));
2521 return DSERR_GENERIC;
2523 return DS_OK;
2526 static IDsDriverBufferVtbl dsdbvt =
2528 ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
2529 IDsDriverBufferImpl_QueryInterface,
2530 IDsDriverBufferImpl_AddRef,
2531 IDsDriverBufferImpl_Release,
2532 IDsDriverBufferImpl_Lock,
2533 IDsDriverBufferImpl_Unlock,
2534 IDsDriverBufferImpl_SetFormat,
2535 IDsDriverBufferImpl_SetFrequency,
2536 IDsDriverBufferImpl_SetVolumePan,
2537 IDsDriverBufferImpl_SetPosition,
2538 IDsDriverBufferImpl_GetPosition,
2539 IDsDriverBufferImpl_Play,
2540 IDsDriverBufferImpl_Stop
2543 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
2545 /* ICOM_THIS(IDsDriverImpl,iface); */
2546 FIXME("(%p): stub!\n",iface);
2547 return DSERR_UNSUPPORTED;
2550 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
2552 ICOM_THIS(IDsDriverImpl,iface);
2553 TRACE("(%p)\n",iface);
2554 This->ref++;
2555 return This->ref;
2558 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
2560 ICOM_THIS(IDsDriverImpl,iface);
2561 TRACE("(%p)\n",iface);
2562 if (--This->ref)
2563 return This->ref;
2564 HeapFree(GetProcessHeap(),0,This);
2565 return 0;
2568 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
2570 ICOM_THIS(IDsDriverImpl,iface);
2571 TRACE("(%p,%p)\n",iface,pDesc);
2572 memcpy(pDesc, &(WOutDev[This->wDevID].ds_desc), sizeof(DSDRIVERDESC));
2573 pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
2574 DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK;
2575 pDesc->dnDevNode = WOutDev[This->wDevID].waveDesc.dnDevNode;
2576 pDesc->wVxdId = 0;
2577 pDesc->wReserved = 0;
2578 pDesc->ulDeviceNum = This->wDevID;
2579 pDesc->dwHeapType = DSDHEAP_NOHEAP;
2580 pDesc->pvDirectDrawHeap = NULL;
2581 pDesc->dwMemStartAddress = 0;
2582 pDesc->dwMemEndAddress = 0;
2583 pDesc->dwMemAllocExtra = 0;
2584 pDesc->pvReserved1 = NULL;
2585 pDesc->pvReserved2 = NULL;
2586 return DS_OK;
2589 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
2591 /* ICOM_THIS(IDsDriverImpl,iface); */
2592 TRACE("(%p)\n",iface);
2593 return DS_OK;
2596 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
2598 /* ICOM_THIS(IDsDriverImpl,iface); */
2599 TRACE("(%p)\n",iface);
2600 return DS_OK;
2603 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
2605 ICOM_THIS(IDsDriverImpl,iface);
2606 TRACE("(%p,%p)\n",iface,pCaps);
2607 memset(pCaps, 0, sizeof(*pCaps));
2609 pCaps->dwFlags = DSCAPS_PRIMARYMONO;
2610 if ( WOutDev[This->wDevID].caps.wChannels == 2 )
2611 pCaps->dwFlags |= DSCAPS_PRIMARYSTEREO;
2613 if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 ) )
2614 pCaps->dwFlags |= DSCAPS_PRIMARY8BIT;
2616 if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S16 | WAVE_FORMAT_2S16 | WAVE_FORMAT_4S16))
2617 pCaps->dwFlags |= DSCAPS_PRIMARY16BIT;
2619 pCaps->dwPrimaryBuffers = 1;
2620 TRACE("caps=0x%X\n",(unsigned int)pCaps->dwFlags);
2621 pCaps->dwMinSecondarySampleRate = DSBFREQUENCY_MIN;
2622 pCaps->dwMaxSecondarySampleRate = DSBFREQUENCY_MAX;
2624 /* the other fields only apply to secondary buffers, which we don't support
2625 * (unless we want to mess with wavetable synthesizers and MIDI) */
2626 return DS_OK;
2629 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
2630 LPWAVEFORMATEX pwfx,
2631 DWORD dwFlags, DWORD dwCardAddress,
2632 LPDWORD pdwcbBufferSize,
2633 LPBYTE *ppbBuffer,
2634 LPVOID *ppvObj)
2636 ICOM_THIS(IDsDriverImpl,iface);
2637 IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
2638 int err;
2640 TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
2641 /* we only support primary buffers */
2642 if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
2643 return DSERR_UNSUPPORTED;
2644 if (This->primary)
2645 return DSERR_ALLOCATED;
2646 if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
2647 return DSERR_CONTROLUNAVAIL;
2649 *ippdsdb = (IDsDriverBufferImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
2650 if (*ippdsdb == NULL)
2651 return DSERR_OUTOFMEMORY;
2652 (*ippdsdb)->lpVtbl = &dsdbvt;
2653 (*ippdsdb)->ref = 1;
2654 (*ippdsdb)->drv = This;
2656 err = DSDB_CreateMMAP((*ippdsdb));
2657 if ( err != DS_OK )
2659 HeapFree(GetProcessHeap(), 0, *ippdsdb);
2660 *ippdsdb = NULL;
2661 return err;
2663 *ppbBuffer = (*ippdsdb)->mmap_buffer;
2664 *pdwcbBufferSize = (*ippdsdb)->mmap_buflen_bytes;
2666 This->primary = *ippdsdb;
2668 /* buffer is ready to go */
2669 TRACE("buffer created at %p\n", *ippdsdb);
2670 return DS_OK;
2673 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
2674 PIDSDRIVERBUFFER pBuffer,
2675 LPVOID *ppvObj)
2677 /* ICOM_THIS(IDsDriverImpl,iface); */
2678 TRACE("(%p,%p): stub\n",iface,pBuffer);
2679 return DSERR_INVALIDCALL;
2682 static IDsDriverVtbl dsdvt =
2684 ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
2685 IDsDriverImpl_QueryInterface,
2686 IDsDriverImpl_AddRef,
2687 IDsDriverImpl_Release,
2688 IDsDriverImpl_GetDriverDesc,
2689 IDsDriverImpl_Open,
2690 IDsDriverImpl_Close,
2691 IDsDriverImpl_GetCaps,
2692 IDsDriverImpl_CreateSoundBuffer,
2693 IDsDriverImpl_DuplicateSoundBuffer
2696 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
2698 IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
2700 TRACE("driver created\n");
2702 /* the HAL isn't much better than the HEL if we can't do mmap() */
2703 if (!(WOutDev[wDevID].caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
2704 ERR("DirectSound flag not set\n");
2705 MESSAGE("This sound card's driver does not support direct access\n");
2706 MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
2707 return MMSYSERR_NOTSUPPORTED;
2710 *idrv = (IDsDriverImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
2711 if (!*idrv)
2712 return MMSYSERR_NOMEM;
2713 (*idrv)->lpVtbl = &dsdvt;
2714 (*idrv)->ref = 1;
2716 (*idrv)->wDevID = wDevID;
2717 (*idrv)->primary = NULL;
2718 return MMSYSERR_NOERROR;
2721 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2723 memcpy(desc, &(WOutDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
2724 return MMSYSERR_NOERROR;
2727 /*======================================================================*
2728 * Low level WAVE IN implementation *
2729 *======================================================================*/
2731 /**************************************************************************
2732 * widNotifyClient [internal]
2734 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
2736 TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
2738 switch (wMsg) {
2739 case WIM_OPEN:
2740 case WIM_CLOSE:
2741 case WIM_DATA:
2742 if (wwi->wFlags != DCB_NULL &&
2743 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags, (HDRVR)wwi->waveDesc.hWave,
2744 wMsg, wwi->waveDesc.dwInstance, dwParam1, dwParam2)) {
2745 WARN("can't notify client !\n");
2746 return MMSYSERR_ERROR;
2748 break;
2749 default:
2750 FIXME("Unknown callback message %u\n", wMsg);
2751 return MMSYSERR_INVALPARAM;
2753 return MMSYSERR_NOERROR;
2756 /**************************************************************************
2757 * widGetDevCaps [internal]
2759 static DWORD widGetDevCaps(WORD wDevID, LPWAVEOUTCAPSA lpCaps, DWORD dwSize)
2761 TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
2763 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
2765 if (wDevID >= MAX_WAVEINDRV) {
2766 TRACE("MAX_WAVOUTDRV reached !\n");
2767 return MMSYSERR_BADDEVICEID;
2770 memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
2771 return MMSYSERR_NOERROR;
2774 /**************************************************************************
2775 * widRecorder_ReadHeaders [internal]
2777 static void widRecorder_ReadHeaders(WINE_WAVEIN * wwi)
2779 enum win_wm_message tmp_msg;
2780 DWORD tmp_param;
2781 HANDLE tmp_ev;
2782 WAVEHDR* lpWaveHdr;
2784 while (ALSA_RetrieveRingMessage(&wwi->msgRing, &tmp_msg, &tmp_param, &tmp_ev)) {
2785 if (tmp_msg == WINE_WM_HEADER) {
2786 LPWAVEHDR* wh;
2787 lpWaveHdr = (LPWAVEHDR)tmp_param;
2788 lpWaveHdr->lpNext = 0;
2790 if (wwi->lpQueuePtr == 0)
2791 wwi->lpQueuePtr = lpWaveHdr;
2792 else {
2793 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2794 *wh = lpWaveHdr;
2796 } else {
2797 ERR("should only have headers left\n");
2802 /**************************************************************************
2803 * widRecorder [internal]
2805 static DWORD CALLBACK widRecorder(LPVOID pmt)
2807 WORD uDevID = (DWORD)pmt;
2808 WINE_WAVEIN* wwi = (WINE_WAVEIN*)&WInDev[uDevID];
2809 WAVEHDR* lpWaveHdr;
2810 DWORD dwSleepTime;
2811 DWORD bytesRead;
2812 LPVOID buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, wwi->dwPeriodSize);
2813 char *pOffset = buffer;
2814 enum win_wm_message msg;
2815 DWORD param;
2816 HANDLE ev;
2817 DWORD frames_per_period;
2819 wwi->state = WINE_WS_STOPPED;
2820 wwi->dwTotalRecorded = 0;
2821 wwi->lpQueuePtr = NULL;
2823 SetEvent(wwi->hStartUpEvent);
2825 /* make sleep time to be # of ms to output a period */
2826 dwSleepTime = (1024/*wwi-dwPeriodSize => overrun!*/ * 1000) / wwi->format.Format.nAvgBytesPerSec;
2827 frames_per_period = snd_pcm_bytes_to_frames(wwi->p_handle, wwi->dwPeriodSize);
2828 TRACE("sleeptime=%ld ms\n", dwSleepTime);
2830 for (;;) {
2831 /* wait for dwSleepTime or an event in thread's queue */
2832 /* FIXME: could improve wait time depending on queue state,
2833 * ie, number of queued fragments
2835 if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
2837 int periods;
2838 DWORD frames;
2839 DWORD bytes;
2840 DWORD read;
2842 lpWaveHdr = wwi->lpQueuePtr;
2843 /* read all the fragments accumulated so far */
2844 frames = snd_pcm_avail_update(wwi->p_handle);
2845 bytes = snd_pcm_frames_to_bytes(wwi->p_handle, frames);
2846 TRACE("frames = %ld bytes = %ld\n", frames, bytes);
2847 periods = bytes / wwi->dwPeriodSize;
2848 while ((periods > 0) && (wwi->lpQueuePtr))
2850 periods--;
2851 bytes = wwi->dwPeriodSize;
2852 TRACE("bytes = %ld\n",bytes);
2853 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwPeriodSize)
2855 /* directly read fragment in wavehdr */
2856 read = wwi->read(wwi->p_handle, lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded, frames_per_period);
2857 bytesRead = snd_pcm_frames_to_bytes(wwi->p_handle, read);
2859 TRACE("bytesRead=%ld (direct)\n", bytesRead);
2860 if (bytesRead != (DWORD) -1)
2862 /* update number of bytes recorded in current buffer and by this device */
2863 lpWaveHdr->dwBytesRecorded += bytesRead;
2864 wwi->dwTotalRecorded += bytesRead;
2866 /* buffer is full. notify client */
2867 if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2869 /* must copy the value of next waveHdr, because we have no idea of what
2870 * will be done with the content of lpWaveHdr in callback
2872 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
2874 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2875 lpWaveHdr->dwFlags |= WHDR_DONE;
2877 wwi->lpQueuePtr = lpNext;
2878 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2879 lpWaveHdr = lpNext;
2881 } else {
2882 TRACE("read(%s, %p, %ld) failed (%s)\n", wwi->device,
2883 lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2884 frames_per_period, strerror(errno));
2887 else
2889 /* read the fragment in a local buffer */
2890 read = wwi->read(wwi->p_handle, buffer, frames_per_period);
2891 bytesRead = snd_pcm_frames_to_bytes(wwi->p_handle, read);
2892 pOffset = buffer;
2894 TRACE("bytesRead=%ld (local)\n", bytesRead);
2896 if (bytesRead == (DWORD) -1) {
2897 TRACE("read(%s, %p, %ld) failed (%s)\n", wwi->device,
2898 buffer, frames_per_period, strerror(errno));
2899 continue;
2902 /* copy data in client buffers */
2903 while (bytesRead != (DWORD) -1 && bytesRead > 0)
2905 DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
2907 memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2908 pOffset,
2909 dwToCopy);
2911 /* update number of bytes recorded in current buffer and by this device */
2912 lpWaveHdr->dwBytesRecorded += dwToCopy;
2913 wwi->dwTotalRecorded += dwToCopy;
2914 bytesRead -= dwToCopy;
2915 pOffset += dwToCopy;
2917 /* client buffer is full. notify client */
2918 if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2920 /* must copy the value of next waveHdr, because we have no idea of what
2921 * will be done with the content of lpWaveHdr in callback
2923 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
2924 TRACE("lpNext=%p\n", lpNext);
2926 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2927 lpWaveHdr->dwFlags |= WHDR_DONE;
2929 wwi->lpQueuePtr = lpNext;
2930 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2932 lpWaveHdr = lpNext;
2933 if (!lpNext && bytesRead) {
2934 /* before we give up, check for more header messages */
2935 while (ALSA_PeekRingMessage(&wwi->msgRing, &msg, &param, &ev))
2937 if (msg == WINE_WM_HEADER) {
2938 LPWAVEHDR hdr;
2939 ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev);
2940 hdr = ((LPWAVEHDR)param);
2941 TRACE("msg = %s, hdr = %p, ev = %p\n", getCmdString(msg), hdr, ev);
2942 hdr->lpNext = 0;
2943 if (lpWaveHdr == 0) {
2944 /* new head of queue */
2945 wwi->lpQueuePtr = lpWaveHdr = hdr;
2946 } else {
2947 /* insert buffer at the end of queue */
2948 LPWAVEHDR* wh;
2949 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2950 *wh = hdr;
2952 } else
2953 break;
2956 if (lpWaveHdr == 0) {
2957 /* no more buffer to copy data to, but we did read more.
2958 * what hasn't been copied will be dropped
2960 WARN("buffer under run! %lu bytes dropped.\n", bytesRead);
2961 wwi->lpQueuePtr = NULL;
2962 break;
2971 WAIT_OMR(&wwi->msgRing, dwSleepTime);
2973 while (ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev))
2975 TRACE("msg=%s param=0x%lx\n", getCmdString(msg), param);
2976 switch (msg) {
2977 case WINE_WM_PAUSING:
2978 wwi->state = WINE_WS_PAUSED;
2979 /*FIXME("Device should stop recording\n");*/
2980 SetEvent(ev);
2981 break;
2982 case WINE_WM_STARTING:
2983 wwi->state = WINE_WS_PLAYING;
2984 snd_pcm_start(wwi->p_handle);
2985 SetEvent(ev);
2986 break;
2987 case WINE_WM_HEADER:
2988 lpWaveHdr = (LPWAVEHDR)param;
2989 lpWaveHdr->lpNext = 0;
2991 /* insert buffer at the end of queue */
2993 LPWAVEHDR* wh;
2994 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2995 *wh = lpWaveHdr;
2997 break;
2998 case WINE_WM_STOPPING:
2999 if (wwi->state != WINE_WS_STOPPED)
3001 snd_pcm_drain(wwi->p_handle);
3003 /* read any headers in queue */
3004 widRecorder_ReadHeaders(wwi);
3006 /* return current buffer to app */
3007 lpWaveHdr = wwi->lpQueuePtr;
3008 if (lpWaveHdr)
3010 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
3011 TRACE("stop %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
3012 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
3013 lpWaveHdr->dwFlags |= WHDR_DONE;
3014 wwi->lpQueuePtr = lpNext;
3015 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
3018 wwi->state = WINE_WS_STOPPED;
3019 SetEvent(ev);
3020 break;
3021 case WINE_WM_RESETTING:
3022 if (wwi->state != WINE_WS_STOPPED)
3024 snd_pcm_drain(wwi->p_handle);
3026 wwi->state = WINE_WS_STOPPED;
3027 wwi->dwTotalRecorded = 0;
3029 /* read any headers in queue */
3030 widRecorder_ReadHeaders(wwi);
3032 /* return all buffers to the app */
3033 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
3034 TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
3035 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
3036 lpWaveHdr->dwFlags |= WHDR_DONE;
3037 wwi->lpQueuePtr = lpWaveHdr->lpNext;
3038 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
3041 wwi->lpQueuePtr = NULL;
3042 SetEvent(ev);
3043 break;
3044 case WINE_WM_CLOSING:
3045 wwi->hThread = 0;
3046 wwi->state = WINE_WS_CLOSED;
3047 SetEvent(ev);
3048 HeapFree(GetProcessHeap(), 0, buffer);
3049 ExitThread(0);
3050 /* shouldn't go here */
3051 case WINE_WM_UPDATE:
3052 SetEvent(ev);
3053 break;
3055 default:
3056 FIXME("unknown message %d\n", msg);
3057 break;
3061 ExitThread(0);
3062 /* just for not generating compilation warnings... should never be executed */
3063 return 0;
3066 /**************************************************************************
3067 * widOpen [internal]
3069 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
3071 WINE_WAVEIN* wwi;
3072 snd_pcm_hw_params_t * hw_params;
3073 snd_pcm_sw_params_t * sw_params;
3074 snd_pcm_access_t access;
3075 snd_pcm_format_t format;
3076 unsigned int rate;
3077 unsigned int buffer_time = 500000;
3078 unsigned int period_time = 10000;
3079 snd_pcm_uframes_t buffer_size;
3080 snd_pcm_uframes_t period_size;
3081 int flags;
3082 snd_pcm_t * pcm;
3083 int err;
3084 int dir;
3086 snd_pcm_hw_params_alloca(&hw_params);
3087 snd_pcm_sw_params_alloca(&sw_params);
3089 TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
3090 if (lpDesc == NULL) {
3091 WARN("Invalid Parameter !\n");
3092 return MMSYSERR_INVALPARAM;
3094 if (wDevID >= MAX_WAVEOUTDRV) {
3095 TRACE("MAX_WAVOUTDRV reached !\n");
3096 return MMSYSERR_BADDEVICEID;
3099 /* only PCM format is supported so far... */
3100 if (!supportedFormat(lpDesc->lpFormat)) {
3101 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
3102 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
3103 lpDesc->lpFormat->nSamplesPerSec);
3104 return WAVERR_BADFORMAT;
3107 if (dwFlags & WAVE_FORMAT_QUERY) {
3108 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
3109 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
3110 lpDesc->lpFormat->nSamplesPerSec);
3111 return MMSYSERR_NOERROR;
3114 wwi = &WInDev[wDevID];
3116 if ((dwFlags & WAVE_DIRECTSOUND) && !(wwi->caps.dwSupport & WAVECAPS_DIRECTSOUND))
3117 /* not supported, ignore it */
3118 dwFlags &= ~WAVE_DIRECTSOUND;
3120 wwi->p_handle = 0;
3121 flags = SND_PCM_NONBLOCK;
3122 if ( dwFlags & WAVE_DIRECTSOUND )
3123 flags |= SND_PCM_ASYNC;
3125 if ( (err=snd_pcm_open(&pcm, wwi->device, SND_PCM_STREAM_CAPTURE, dwFlags)) < 0 )
3127 ERR("Error open: %s\n", snd_strerror(err));
3128 return MMSYSERR_NOTENABLED;
3131 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
3133 memcpy(&wwi->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
3134 copy_format(lpDesc->lpFormat, &wwi->format);
3136 if (wwi->format.Format.wBitsPerSample == 0) {
3137 WARN("Resetting zeroed wBitsPerSample\n");
3138 wwi->format.Format.wBitsPerSample = 8 *
3139 (wwi->format.Format.nAvgBytesPerSec /
3140 wwi->format.Format.nSamplesPerSec) /
3141 wwi->format.Format.nChannels;
3144 snd_pcm_hw_params_any(pcm, hw_params);
3146 #define EXIT_ON_ERROR(f,e,txt) do \
3148 int err; \
3149 if ( (err = (f) ) < 0) \
3151 ERR(txt ": %s\n", snd_strerror(err)); \
3152 snd_pcm_close(pcm); \
3153 return e; \
3155 } while(0)
3157 access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
3158 if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
3159 WARN("mmap not available. switching to standard write.\n");
3160 access = SND_PCM_ACCESS_RW_INTERLEAVED;
3161 EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
3162 wwi->read = snd_pcm_readi;
3164 else
3165 wwi->read = snd_pcm_mmap_readi;
3167 EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwi->format.Format.nChannels), MMSYSERR_INVALPARAM, "unable to set required channels");
3169 if ((wwi->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
3170 ((wwi->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
3171 IsEqualGUID(&wwi->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
3172 format = (wwi->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
3173 (wwi->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
3174 (wwi->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
3175 (wwi->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
3176 } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
3177 FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
3178 snd_pcm_close(pcm);
3179 return WAVERR_BADFORMAT;
3180 } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
3181 FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
3182 snd_pcm_close(pcm);
3183 return WAVERR_BADFORMAT;
3184 } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
3185 FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
3186 snd_pcm_close(pcm);
3187 return WAVERR_BADFORMAT;
3188 } else {
3189 ERR("invalid format: %0x04x\n", wwi->format.Format.wFormatTag);
3190 snd_pcm_close(pcm);
3191 return WAVERR_BADFORMAT;
3194 EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), MMSYSERR_INVALPARAM, "unable to set required format");
3196 rate = wwi->format.Format.nSamplesPerSec;
3197 dir = 0;
3198 err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
3199 if (err < 0) {
3200 ERR("Rate %ld Hz not available for playback: %s\n", wwi->format.Format.nSamplesPerSec, snd_strerror(rate));
3201 snd_pcm_close(pcm);
3202 return WAVERR_BADFORMAT;
3204 if (rate != wwi->format.Format.nSamplesPerSec) {
3205 ERR("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwi->format.Format.nSamplesPerSec, rate);
3206 snd_pcm_close(pcm);
3207 return WAVERR_BADFORMAT;
3210 dir=0;
3211 EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
3212 dir=0;
3213 EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
3215 EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
3217 dir=0;
3218 err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
3219 err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
3221 snd_pcm_sw_params_current(pcm, sw_params);
3222 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");
3223 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
3224 EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
3225 EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
3226 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
3227 EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
3228 #undef EXIT_ON_ERROR
3230 snd_pcm_prepare(pcm);
3232 if (TRACE_ON(wave))
3233 ALSA_TraceParameters(hw_params, sw_params, FALSE);
3235 /* now, we can save all required data for later use... */
3236 if ( wwi->hw_params )
3237 snd_pcm_hw_params_free(wwi->hw_params);
3238 snd_pcm_hw_params_malloc(&(wwi->hw_params));
3239 snd_pcm_hw_params_copy(wwi->hw_params, hw_params);
3241 wwi->dwBufferSize = buffer_size;
3242 wwi->lpQueuePtr = wwi->lpPlayPtr = wwi->lpLoopPtr = NULL;
3243 wwi->p_handle = pcm;
3245 ALSA_InitRingMessage(&wwi->msgRing);
3247 wwi->count = snd_pcm_poll_descriptors_count (wwi->p_handle);
3248 if (wwi->count <= 0) {
3249 ERR("Invalid poll descriptors count\n");
3250 return MMSYSERR_ERROR;
3253 wwi->ufds = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct pollfd) * wwi->count);
3254 if (wwi->ufds == NULL) {
3255 ERR("No enough memory\n");
3256 return MMSYSERR_NOMEM;
3258 if ((err = snd_pcm_poll_descriptors(wwi->p_handle, wwi->ufds, wwi->count)) < 0) {
3259 ERR("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
3260 return MMSYSERR_ERROR;
3263 wwi->dwPeriodSize = period_size;
3264 /*if (wwi->dwFragmentSize % wwi->format.Format.nBlockAlign)
3265 ERR("Fragment doesn't contain an integral number of data blocks\n");
3267 TRACE("dwPeriodSize=%lu\n", wwi->dwPeriodSize);
3268 TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
3269 wwi->format.Format.wBitsPerSample, wwi->format.Format.nAvgBytesPerSec,
3270 wwi->format.Format.nSamplesPerSec, wwi->format.Format.nChannels,
3271 wwi->format.Format.nBlockAlign);
3273 if (!(dwFlags & WAVE_DIRECTSOUND)) {
3274 wwi->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
3275 wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
3276 WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
3277 CloseHandle(wwi->hStartUpEvent);
3278 } else {
3279 wwi->hThread = INVALID_HANDLE_VALUE;
3280 wwi->dwThreadID = 0;
3282 wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
3284 return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
3288 /**************************************************************************
3289 * widClose [internal]
3291 static DWORD widClose(WORD wDevID)
3293 DWORD ret = MMSYSERR_NOERROR;
3294 WINE_WAVEIN* wwi;
3296 TRACE("(%u);\n", wDevID);
3298 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3299 WARN("bad device ID !\n");
3300 return MMSYSERR_BADDEVICEID;
3303 wwi = &WInDev[wDevID];
3304 if (wwi->lpQueuePtr) {
3305 WARN("buffers still playing !\n");
3306 ret = WAVERR_STILLPLAYING;
3307 } else {
3308 if (wwi->hThread != INVALID_HANDLE_VALUE) {
3309 ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
3311 ALSA_DestroyRingMessage(&wwi->msgRing);
3313 snd_pcm_hw_params_free(wwi->hw_params);
3314 wwi->hw_params = NULL;
3316 snd_pcm_close(wwi->p_handle);
3317 wwi->p_handle = NULL;
3319 ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
3322 HeapFree(GetProcessHeap(), 0, wwi->ufds);
3323 return ret;
3326 /**************************************************************************
3327 * widAddBuffer [internal]
3330 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3332 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3334 /* first, do the sanity checks... */
3335 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3336 WARN("bad dev ID !\n");
3337 return MMSYSERR_BADDEVICEID;
3340 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
3341 return WAVERR_UNPREPARED;
3343 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3344 return WAVERR_STILLPLAYING;
3346 lpWaveHdr->dwFlags &= ~WHDR_DONE;
3347 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
3348 lpWaveHdr->lpNext = 0;
3350 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
3352 return MMSYSERR_NOERROR;
3355 /**************************************************************************
3356 * widPrepare [internal]
3358 static DWORD widPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3360 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3362 if (wDevID >= MAX_WAVEINDRV) {
3363 WARN("bad device ID !\n");
3364 return MMSYSERR_BADDEVICEID;
3367 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3368 return WAVERR_STILLPLAYING;
3370 lpWaveHdr->dwFlags |= WHDR_PREPARED;
3371 lpWaveHdr->dwFlags &= ~WHDR_DONE;
3372 return MMSYSERR_NOERROR;
3375 /**************************************************************************
3376 * widUnprepare [internal]
3378 static DWORD widUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3380 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3382 if (wDevID >= MAX_WAVEINDRV) {
3383 WARN("bad device ID !\n");
3384 return MMSYSERR_BADDEVICEID;
3387 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3388 return WAVERR_STILLPLAYING;
3390 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
3391 lpWaveHdr->dwFlags |= WHDR_DONE;
3393 return MMSYSERR_NOERROR;
3396 /**************************************************************************
3397 * widStart [internal]
3400 static DWORD widStart(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3402 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3404 /* first, do the sanity checks... */
3405 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3406 WARN("bad dev ID !\n");
3407 return MMSYSERR_BADDEVICEID;
3410 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
3412 Sleep(500);
3414 return MMSYSERR_NOERROR;
3417 /**************************************************************************
3418 * widStop [internal]
3421 static DWORD widStop(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3423 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3425 /* first, do the sanity checks... */
3426 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3427 WARN("bad dev ID !\n");
3428 return MMSYSERR_BADDEVICEID;
3431 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
3433 return MMSYSERR_NOERROR;
3436 /**************************************************************************
3437 * widReset [internal]
3439 static DWORD widReset(WORD wDevID)
3441 TRACE("(%u);\n", wDevID);
3442 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
3443 WARN("can't reset !\n");
3444 return MMSYSERR_INVALHANDLE;
3446 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
3447 return MMSYSERR_NOERROR;
3450 /**************************************************************************
3451 * widGetPosition [internal]
3453 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
3455 WINE_WAVEIN* wwi;
3457 TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
3459 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
3460 WARN("can't get pos !\n");
3461 return MMSYSERR_INVALHANDLE;
3464 if (lpTime == NULL) {
3465 WARN("invalid parameter: lpTime = NULL\n");
3466 return MMSYSERR_INVALPARAM;
3469 wwi = &WInDev[wDevID];
3470 ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_UPDATE, 0, TRUE);
3472 return bytes_to_mmtime(lpTime, wwi->dwTotalRecorded, &wwi->format);
3475 /**************************************************************************
3476 * widGetNumDevs [internal]
3478 static DWORD widGetNumDevs(void)
3480 return ALSA_WidNumDevs;
3483 /**************************************************************************
3484 * widDevInterfaceSize [internal]
3486 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
3488 TRACE("(%u, %p)\n", wDevID, dwParam1);
3490 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3491 NULL, 0 ) * sizeof(WCHAR);
3492 return MMSYSERR_NOERROR;
3495 /**************************************************************************
3496 * widDevInterface [internal]
3498 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
3500 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3501 NULL, 0 ) * sizeof(WCHAR))
3503 MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3504 dwParam1, dwParam2 / sizeof(WCHAR));
3505 return MMSYSERR_NOERROR;
3507 return MMSYSERR_INVALPARAM;
3510 /**************************************************************************
3511 * widDsCreate [internal]
3513 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
3515 TRACE("(%d,%p)\n",wDevID,drv);
3517 /* the HAL isn't much better than the HEL if we can't do mmap() */
3518 FIXME("DirectSoundCapture not implemented\n");
3519 MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
3520 return MMSYSERR_NOTSUPPORTED;
3523 /**************************************************************************
3524 * widDsDesc [internal]
3526 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
3528 memcpy(desc, &(WInDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
3529 return MMSYSERR_NOERROR;
3532 /**************************************************************************
3533 * widMessage (WINEALSA.@)
3535 DWORD WINAPI ALSA_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
3536 DWORD dwParam1, DWORD dwParam2)
3538 TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
3539 wDevID, wMsg, dwUser, dwParam1, dwParam2);
3541 switch (wMsg) {
3542 case DRVM_INIT:
3543 case DRVM_EXIT:
3544 case DRVM_ENABLE:
3545 case DRVM_DISABLE:
3546 /* FIXME: Pretend this is supported */
3547 return 0;
3548 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
3549 case WIDM_CLOSE: return widClose (wDevID);
3550 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3551 case WIDM_PREPARE: return widPrepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3552 case WIDM_UNPREPARE: return widUnprepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3553 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEOUTCAPSA)dwParam1, dwParam2);
3554 case WIDM_GETNUMDEVS: return widGetNumDevs ();
3555 case WIDM_GETPOS: return widGetPosition (wDevID, (LPMMTIME)dwParam1, dwParam2);
3556 case WIDM_RESET: return widReset (wDevID);
3557 case WIDM_START: return widStart (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3558 case WIDM_STOP: return widStop (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3559 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
3560 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
3561 case DRV_QUERYDSOUNDIFACE: return widDsCreate (wDevID, (PIDSCDRIVER*)dwParam1);
3562 case DRV_QUERYDSOUNDDESC: return widDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
3563 default:
3564 FIXME("unknown message %d!\n", wMsg);
3566 return MMSYSERR_NOTSUPPORTED;
3569 #endif
3571 #if !(defined(HAVE_ALSA) && ((SND_LIB_MAJOR == 0 && SND_LIB_MINOR >= 9) || SND_LIB_MAJOR >= 1))
3573 /**************************************************************************
3574 * widMessage (WINEALSA.@)
3576 DWORD WINAPI ALSA_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3577 DWORD dwParam1, DWORD dwParam2)
3579 FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3580 return MMSYSERR_NOTENABLED;
3583 #endif
3585 #ifndef HAVE_ALSA
3587 /**************************************************************************
3588 * wodMessage (WINEALSA.@)
3590 DWORD WINAPI ALSA_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3591 DWORD dwParam1, DWORD dwParam2)
3593 FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3594 return MMSYSERR_NOTENABLED;
3597 #endif /* HAVE_ALSA */