1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
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 */
29 #include "wine/port.h"
41 #ifdef HAVE_SYS_IOCTL_H
42 # include <sys/ioctl.h>
44 #ifdef HAVE_SYS_MMAN_H
45 # include <sys/mman.h>
61 #define ALSA_PCM_NEW_HW_PARAMS_API
62 #define ALSA_PCM_NEW_SW_PARAMS_API
64 #include "wine/library.h"
65 #include "wine/unicode.h"
66 #include "wine/debug.h"
68 WINE_DEFAULT_DEBUG_CHANNEL(wave);
73 /* internal ALSALIB functions */
74 snd_pcm_uframes_t _snd_pcm_mmap_hw_ptr(snd_pcm_t *pcm);
77 #define MAX_WAVEOUTDRV (1)
78 #define MAX_WAVEINDRV (1)
80 /* state diagram for waveOut writing:
82 * +---------+-------------+---------------+---------------------------------+
83 * | state | function | event | new state |
84 * +---------+-------------+---------------+---------------------------------+
85 * | | open() | | STOPPED |
86 * | PAUSED | write() | | PAUSED |
87 * | STOPPED | write() | <thrd create> | PLAYING |
88 * | PLAYING | write() | HEADER | PLAYING |
89 * | (other) | write() | <error> | |
90 * | (any) | pause() | PAUSING | PAUSED |
91 * | PAUSED | restart() | RESTARTING | PLAYING (if no thrd => STOPPED) |
92 * | (any) | reset() | RESETTING | STOPPED |
93 * | (any) | close() | CLOSING | CLOSED |
94 * +---------+-------------+---------------+---------------------------------+
97 /* states of the playing device */
98 #define WINE_WS_PLAYING 0
99 #define WINE_WS_PAUSED 1
100 #define WINE_WS_STOPPED 2
101 #define WINE_WS_CLOSED 3
103 /* events to be send to device */
104 enum win_wm_message {
105 WINE_WM_PAUSING = WM_USER + 1, WINE_WM_RESTARTING, WINE_WM_RESETTING, WINE_WM_HEADER,
106 WINE_WM_UPDATE, WINE_WM_BREAKLOOP, WINE_WM_CLOSING, WINE_WM_STARTING, WINE_WM_STOPPING
110 #define SIGNAL_OMR(omr) do { int x = 0; write((omr)->msg_pipe[1], &x, sizeof(x)); } while (0)
111 #define CLEAR_OMR(omr) do { int x = 0; read((omr)->msg_pipe[0], &x, sizeof(x)); } while (0)
112 #define RESET_OMR(omr) do { } while (0)
113 #define WAIT_OMR(omr, sleep) \
114 do { struct pollfd pfd; pfd.fd = (omr)->msg_pipe[0]; \
115 pfd.events = POLLIN; poll(&pfd, 1, sleep); } while (0)
117 #define SIGNAL_OMR(omr) do { SetEvent((omr)->msg_event); } while (0)
118 #define CLEAR_OMR(omr) do { } while (0)
119 #define RESET_OMR(omr) do { ResetEvent((omr)->msg_event); } while (0)
120 #define WAIT_OMR(omr, sleep) \
121 do { WaitForSingleObject((omr)->msg_event, sleep); } while (0)
125 enum win_wm_message msg; /* message identifier */
126 DWORD param; /* parameter for this message */
127 HANDLE hEvent; /* if message is synchronous, handle of event for synchro */
130 /* implement an in-process message ring for better performance
131 * (compared to passing thru the server)
132 * this ring will be used by the input (resp output) record (resp playback) routine
134 #define ALSA_RING_BUFFER_INCREMENT 64
137 int ring_buffer_size;
145 CRITICAL_SECTION msg_crst;
149 /* Windows information */
150 volatile int state; /* one of the WINE_WS_ manifest constants */
151 WAVEOPENDESC waveDesc;
153 WAVEFORMATPCMEX format;
156 /* ALSA information (ALSA 0.9/1.x uses two different devices for playback/capture) */
158 char interface_name[64];
159 snd_pcm_t* p_handle; /* handle to ALSA playback device */
160 snd_pcm_t* c_handle; /* handle to ALSA capture device */
161 snd_pcm_hw_params_t * hw_params; /* ALSA Hw params */
163 snd_ctl_t * ctl; /* control handle for the playback volume */
164 snd_ctl_elem_id_t * playback_eid; /* element id of the playback volume control */
165 snd_ctl_elem_value_t * playback_evalue; /* element value of the playback volume control */
166 snd_ctl_elem_info_t * playback_einfo; /* element info of the playback volume control */
168 snd_pcm_sframes_t (*write)(snd_pcm_t *, const void *, snd_pcm_uframes_t );
173 DWORD dwBufferSize; /* size of whole ALSA buffer in bytes */
174 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
175 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
176 DWORD dwPartialOffset; /* Offset of not yet written bytes in lpPlayPtr */
178 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
179 DWORD dwLoops; /* private copy of loop counter */
181 DWORD dwPlayedTotal; /* number of bytes actually played since opening */
182 DWORD dwWrittenTotal; /* number of bytes written to ALSA buffer since opening */
184 /* synchronization stuff */
185 HANDLE hStartUpEvent;
188 ALSA_MSG_RING msgRing;
190 /* DirectSound stuff */
191 DSDRIVERDESC ds_desc;
195 /* Windows information */
196 volatile int state; /* one of the WINE_WS_ manifest constants */
197 WAVEOPENDESC waveDesc;
199 WAVEFORMATPCMEX format;
202 /* ALSA information (ALSA 0.9/1.x uses two different devices for playback/capture) */
204 char interface_name[64];
205 snd_pcm_t* p_handle; /* handle to ALSA playback device */
206 snd_pcm_t* c_handle; /* handle to ALSA capture device */
207 snd_pcm_hw_params_t * hw_params; /* ALSA Hw params */
209 snd_ctl_t * ctl; /* control handle for the playback volume */
210 snd_ctl_elem_id_t * playback_eid; /* element id of the playback volume control */
211 snd_ctl_elem_value_t * playback_evalue; /* element value of the playback volume control */
212 snd_ctl_elem_info_t * playback_einfo; /* element info of the playback volume control */
214 snd_pcm_sframes_t (*read)(snd_pcm_t *, void *, snd_pcm_uframes_t );
219 DWORD dwPeriodSize; /* size of OSS buffer period */
220 DWORD dwBufferSize; /* size of whole ALSA buffer in bytes */
221 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
222 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
224 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
225 DWORD dwLoops; /* private copy of loop counter */
227 /*DWORD dwPlayedTotal; */
228 DWORD dwTotalRecorded;
230 /* synchronization stuff */
231 HANDLE hStartUpEvent;
234 ALSA_MSG_RING msgRing;
236 /* DirectSound stuff */
237 DSDRIVERDESC ds_desc;
240 static WINE_WAVEOUT WOutDev [MAX_WAVEOUTDRV];
241 static DWORD ALSA_WodNumDevs;
242 static WINE_WAVEIN WInDev [MAX_WAVEINDRV];
243 static DWORD ALSA_WidNumDevs;
245 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
246 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
248 /* These strings used only for tracing */
249 static const char * getCmdString(enum win_wm_message msg)
251 static char unknown[32];
252 #define MSG_TO_STR(x) case x: return #x
254 MSG_TO_STR(WINE_WM_PAUSING);
255 MSG_TO_STR(WINE_WM_RESTARTING);
256 MSG_TO_STR(WINE_WM_RESETTING);
257 MSG_TO_STR(WINE_WM_HEADER);
258 MSG_TO_STR(WINE_WM_UPDATE);
259 MSG_TO_STR(WINE_WM_BREAKLOOP);
260 MSG_TO_STR(WINE_WM_CLOSING);
261 MSG_TO_STR(WINE_WM_STARTING);
262 MSG_TO_STR(WINE_WM_STOPPING);
265 sprintf(unknown, "UNKNOWN(0x%08x)", msg);
269 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
270 WAVEFORMATPCMEX* format)
272 TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
273 lpTime->wType, format->Format.wBitsPerSample, format->Format.nSamplesPerSec,
274 format->Format.nChannels, format->Format.nAvgBytesPerSec);
275 TRACE("Position in bytes=%lu\n", position);
277 switch (lpTime->wType) {
279 lpTime->u.sample = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
280 TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
283 lpTime->u.ms = 1000.0 * position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels * format->Format.nSamplesPerSec);
284 TRACE("TIME_MS=%lu\n", lpTime->u.ms);
287 lpTime->u.smpte.fps = 30;
288 position = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
289 position += (format->Format.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
290 lpTime->u.smpte.sec = position / format->Format.nSamplesPerSec;
291 position -= lpTime->u.smpte.sec * format->Format.nSamplesPerSec;
292 lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
293 lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
294 lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
295 lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
296 lpTime->u.smpte.fps = 30;
297 lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->Format.nSamplesPerSec;
298 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
299 lpTime->u.smpte.hour, lpTime->u.smpte.min,
300 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
303 WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
304 lpTime->wType = TIME_BYTES;
307 lpTime->u.cb = position;
308 TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
311 return MMSYSERR_NOERROR;
314 static BOOL supportedFormat(LPWAVEFORMATEX wf)
318 if (wf->nSamplesPerSec<DSBFREQUENCY_MIN||wf->nSamplesPerSec>DSBFREQUENCY_MAX)
321 if (wf->wFormatTag == WAVE_FORMAT_PCM) {
322 if (wf->nChannels==1||wf->nChannels==2) {
323 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
326 } else if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
327 WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE *)wf;
329 if (wf->cbSize == 22 &&
330 (IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM) ||
331 IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))) {
332 if (wf->nChannels>=1 && wf->nChannels<=6) {
333 if (wf->wBitsPerSample==wfex->Samples.wValidBitsPerSample) {
334 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16||
335 wf->wBitsPerSample==24||wf->wBitsPerSample==32) {
339 WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
342 WARN("only KSDATAFORMAT_SUBTYPE_PCM and KSDATAFORMAT_SUBTYPE_IEEE_FLOAT "
344 } else if (wf->wFormatTag == WAVE_FORMAT_MULAW || wf->wFormatTag == WAVE_FORMAT_ALAW) {
345 if (wf->wBitsPerSample==8)
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)
354 ERR("WAVE_FORMAT_ADPCM wBitsPerSample must = 4\n");
356 WARN("only WAVE_FORMAT_PCM and WAVE_FORMAT_EXTENSIBLE supported\n");
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));
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;
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 \
408 if ( (err = (f) ) < 0) \
410 ERR(txt ": %s\n", snd_strerror(err)); \
412 snd_hctl_close(hctl); \
414 snd_ctl_close(ctl); \
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);
468 elem=snd_hctl_elem_next(elem);
470 snd_hctl_close(hctl);
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);
485 ERR( "underrun recovery failed. prepare failed: %s\n", snd_strerror(err));
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 */
491 err = snd_pcm_prepare(wwo->p_handle);
493 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(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)
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")
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)));
531 TRACE("access=%s\n", snd_pcm_access_name(access));
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));
544 TRACE("format=%s\n", snd_pcm_format_name(format));
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));
561 err = snd_pcm_hw_params_get_channels(hw_params, &val);
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);
569 TRACE("channels_min=%d\n", val);
574 snd_pcm_uframes_t val=0;
575 err = snd_pcm_hw_params_get_buffer_size(hw_params, &val);
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);
583 TRACE("buffer_size_min=%lu\n", val);
590 unsigned int val=0; \
591 err = snd_pcm_hw_params_get_##x(hw_params,&val, &dir); \
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); \
599 TRACE(#x "=%d\n", val); \
608 snd_pcm_uframes_t val=0;
609 err = snd_pcm_hw_params_get_period_size(hw_params, &val, &dir);
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);
617 TRACE("period_size_min=%lu\n", val);
629 /* return a string duplicated on the win32 process heap, free with HeapFree */
630 static char* ALSA_strdup(char *s) {
631 char *result = HeapAlloc(GetProcessHeap(), 0, strlen(s)+1);
636 /******************************************************************
637 * ALSA_GetDeviceFromReg
639 * Returns either "default" or reads the registry so the user can
640 * override the playback/record device used.
642 static char *ALSA_GetDeviceFromReg(const char *value)
646 HKEY playbackKey = 0;
650 res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\ALSA", 0, KEY_QUERY_VALUE, &playbackKey);
651 if (res != ERROR_SUCCESS) goto end;
653 res = RegQueryValueExA(playbackKey, value, NULL, &type, NULL, &resultSize);
654 if (res != ERROR_SUCCESS) goto end;
656 if (type != REG_SZ) {
657 ERR("Registry key [HKEY_LOCAL_MACHINE\\Software\\Wine\\Wine\\ALSA\\%s] must be a string\n", value);
661 result = HeapAlloc(GetProcessHeap(), 0, resultSize);
662 res = RegQueryValueExA(playbackKey, value, NULL, NULL, result, &resultSize);
665 if (!result) result = ALSA_strdup("default");
666 if (playbackKey) RegCloseKey(playbackKey);
670 /******************************************************************
673 * Initialize internal structures from ALSA information
675 LONG ALSA_WaveInit(void)
678 snd_pcm_info_t * info;
679 snd_pcm_hw_params_t * hw_params;
680 unsigned int ratemin=0;
681 unsigned int ratemax=0;
682 unsigned int chmin=0;
683 unsigned int chmax=0;
688 static const WCHAR init_out[] = {'S','B','1','6',' ','W','a','v','e',' ','O','u','t',0};
689 static const WCHAR init_in [] = {'S','B','1','6',' ','W','a','v','e',' ','I','n',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 strcpyW(wwo->caps.szPname, init_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");
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)
721 EXIT_ON_ERROR( snd_pcm_open(&h, wwo->device, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK) , "open pcm" );
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" );
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);
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);
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; \
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);
803 ALSA_InitializeVolumeCtl(wwo);
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 strcpyW(wwi->caps.szPname, init_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)
829 EXIT_ON_ERROR( snd_pcm_open(&h, wwi->device, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK) , "open pcm" );
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" );
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);
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);
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; \
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 ) ) {
904 wwi->caps.dwSupport |= WAVECAPS_DIRECTSOUND;
909 TRACE("Configured with dwFmts=%08lx dwSupport=%08lx\n",
910 wwi->caps.dwFormats, wwi->caps.dwSupport);
917 /******************************************************************
918 * ALSA_InitRingMessage
920 * Initialize the ring of messages for passing between driver's caller and playback/record
923 static int ALSA_InitRingMessage(ALSA_MSG_RING* omr)
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));
934 omr->msg_event = CreateEventW(NULL, FALSE, FALSE, NULL);
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);
943 /******************************************************************
944 * ALSA_DestroyRingMessage
947 static int ALSA_DestroyRingMessage(ALSA_MSG_RING* omr)
950 close(omr->msg_pipe[0]);
951 close(omr->msg_pipe[1]);
953 CloseHandle(omr->msg_event);
955 HeapFree(GetProcessHeap(),0,omr->messages);
956 DeleteCriticalSection(&omr->msg_crst);
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
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;
991 hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
992 if (hEvent == INVALID_HANDLE_VALUE)
994 ERR("can't create event !?\n");
995 LeaveCriticalSection(&omr->msg_crst);
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;
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 */
1022 /* wait for playback/record thread to have processed the message */
1023 WaitForSingleObject(hEvent, INFINITE);
1024 CloseHandle(hEvent);
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);
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;
1051 LeaveCriticalSection(&omr->msg_crst);
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);
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);
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);
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;
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)
1119 wwo->dwPlayedTotal = wwo->dwWrittenTotal - snd_pcm_frames_to_bytes(wwo->p_handle, delay);
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);
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;
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
1173 lpWaveHdr = lpWaveHdr->lpNext;
1175 wwo->lpLoopPtr = NULL;
1176 wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
1179 /* We're not in a loop. Advance to the next wave header */
1180 wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
1186 /**************************************************************************
1187 * wodPlayer_DSPWait [internal]
1188 * Returns the number of milliseconds to wait for the DSP buffer to play a
1191 static DWORD wodPlayer_DSPWait(const WINE_WAVEOUT *wwo)
1193 /* time for one period to be played */
1197 err = snd_pcm_hw_params_get_period_time(wwo->hw_params, &val, &dir);
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
1208 static DWORD wodPlayer_NotifyWait(const WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1212 if (lpWaveHdr->reserved < wwo->dwPlayedTotal) {
1215 dwMillis = (lpWaveHdr->reserved - wwo->dwPlayedTotal) * 1000 / wwo->format.Format.nAvgBytesPerSec;
1216 if (!dwMillis) dwMillis = 1;
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);
1236 TRACE("Writing wavehdr %p.%lu[%lu]\n", lpWaveHdr, wwo->dwPartialOffset, lpWaveHdr->dwBufferLength);
1239 written = (wwo->write)(wwo->p_handle, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
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);
1246 /* still in error */
1247 ERR("Error in writing wavehdr. Reason: %s\n", snd_strerror(written));
1253 wwo->dwPartialOffset += snd_pcm_frames_to_bytes(wwo->p_handle, written);
1254 if ( wwo->dwPartialOffset >= lpWaveHdr->dwBufferLength) {
1255 /* this will be used to check if the given wave header has been fully played or not... */
1256 wwo->dwPartialOffset = lpWaveHdr->dwBufferLength;
1257 /* If we wrote all current wavehdr, skip to the next one */
1258 wodPlayer_PlayPtrNext(wwo);
1261 wwo->dwWrittenTotal += snd_pcm_frames_to_bytes(wwo->p_handle, written);
1262 TRACE("dwWrittenTotal=%lu\n", wwo->dwWrittenTotal);
1268 /**************************************************************************
1269 * wodPlayer_NotifyCompletions [internal]
1271 * Notifies and remove from queue all wavehdrs which have been played to
1272 * the speaker (ie. they have cleared the ALSA buffer). If force is true,
1273 * we notify all wavehdrs and remove them all from the queue even if they
1274 * are unplayed or part of a loop.
1276 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1278 LPWAVEHDR lpWaveHdr;
1280 /* Start from lpQueuePtr and keep notifying until:
1281 * - we hit an unwritten wavehdr
1282 * - we hit the beginning of a running loop
1283 * - we hit a wavehdr which hasn't finished playing
1286 while ((lpWaveHdr = wwo->lpQueuePtr) &&
1288 (lpWaveHdr != wwo->lpPlayPtr &&
1289 lpWaveHdr != wwo->lpLoopPtr &&
1290 lpWaveHdr->reserved <= wwo->dwPlayedTotal))) {
1292 wwo->lpQueuePtr = lpWaveHdr->lpNext;
1294 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1295 lpWaveHdr->dwFlags |= WHDR_DONE;
1297 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1302 lpWaveHdr = wwo->lpQueuePtr;
1303 if (!lpWaveHdr) {TRACE("Empty queue\n"); break;}
1306 if (lpWaveHdr == wwo->lpPlayPtr) {TRACE("play %p\n", lpWaveHdr); break;}
1307 if (lpWaveHdr == wwo->lpLoopPtr) {TRACE("loop %p\n", lpWaveHdr); break;}
1308 if (lpWaveHdr->reserved > wwo->dwPlayedTotal){TRACE("still playing %p (%lu/%lu)\n", lpWaveHdr, lpWaveHdr->reserved, wwo->dwPlayedTotal);break;}
1310 wwo->lpQueuePtr = lpWaveHdr->lpNext;
1312 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1313 lpWaveHdr->dwFlags |= WHDR_DONE;
1315 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1318 return (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
1319 wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
1323 static void wait_for_poll(snd_pcm_t *handle, struct pollfd *ufds, unsigned int count)
1325 unsigned short revents;
1327 if (snd_pcm_state(handle) != SND_PCM_STATE_RUNNING)
1331 poll(ufds, count, -1);
1332 snd_pcm_poll_descriptors_revents(handle, ufds, count, &revents);
1334 if (revents & POLLERR)
1337 /*if (revents & POLLOUT)
1343 /**************************************************************************
1344 * wodPlayer_Reset [internal]
1346 * wodPlayer helper. Resets current output stream.
1348 static void wodPlayer_Reset(WINE_WAVEOUT* wwo)
1350 enum win_wm_message msg;
1355 /* flush all possible output */
1356 wait_for_poll(wwo->p_handle, wwo->ufds, wwo->count);
1358 wodUpdatePlayedTotal(wwo, NULL);
1359 /* updates current notify list */
1360 wodPlayer_NotifyCompletions(wwo, FALSE);
1362 if ( (err = snd_pcm_drop(wwo->p_handle)) < 0) {
1363 FIXME("flush: %s\n", snd_strerror(err));
1365 wwo->state = WINE_WS_STOPPED;
1368 if ( (err = snd_pcm_prepare(wwo->p_handle)) < 0 )
1369 ERR("pcm prepare failed: %s\n", snd_strerror(err));
1371 /* remove any buffer */
1372 wodPlayer_NotifyCompletions(wwo, TRUE);
1374 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1375 wwo->state = WINE_WS_STOPPED;
1376 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1377 /* Clear partial wavehdr */
1378 wwo->dwPartialOffset = 0;
1380 /* remove any existing message in the ring */
1381 EnterCriticalSection(&wwo->msgRing.msg_crst);
1382 /* return all pending headers in queue */
1383 while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, ¶m, &ev))
1385 if (msg != WINE_WM_HEADER)
1387 FIXME("shouldn't have headers left\n");
1391 ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
1392 ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
1394 wodNotifyClient(wwo, WOM_DONE, param, 0);
1396 RESET_OMR(&wwo->msgRing);
1397 LeaveCriticalSection(&wwo->msgRing.msg_crst);
1400 /**************************************************************************
1401 * wodPlayer_ProcessMessages [internal]
1403 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
1405 LPWAVEHDR lpWaveHdr;
1406 enum win_wm_message msg;
1411 while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, ¶m, &ev)) {
1412 TRACE("Received %s %lx\n", getCmdString(msg), param);
1415 case WINE_WM_PAUSING:
1416 if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_RUNNING )
1418 err = snd_pcm_pause(wwo->p_handle, 1);
1420 ERR("pcm_pause failed: %s\n", snd_strerror(err));
1422 wwo->state = WINE_WS_PAUSED;
1425 case WINE_WM_RESTARTING:
1426 if (wwo->state == WINE_WS_PAUSED)
1428 if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_PAUSED )
1430 err = snd_pcm_pause(wwo->p_handle, 0);
1432 ERR("pcm_pause failed: %s\n", snd_strerror(err));
1434 wwo->state = WINE_WS_PLAYING;
1438 case WINE_WM_HEADER:
1439 lpWaveHdr = (LPWAVEHDR)param;
1441 /* insert buffer at the end of queue */
1444 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1447 if (!wwo->lpPlayPtr)
1448 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
1449 if (wwo->state == WINE_WS_STOPPED)
1450 wwo->state = WINE_WS_PLAYING;
1452 case WINE_WM_RESETTING:
1453 wodPlayer_Reset(wwo);
1456 case WINE_WM_UPDATE:
1457 wodUpdatePlayedTotal(wwo, NULL);
1460 case WINE_WM_BREAKLOOP:
1461 if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
1462 /* ensure exit at end of current loop */
1467 case WINE_WM_CLOSING:
1468 /* sanity check: this should not happen since the device must have been reset before */
1469 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1471 wwo->state = WINE_WS_CLOSED;
1474 /* shouldn't go here */
1476 FIXME("unknown message %d\n", msg);
1482 /**************************************************************************
1483 * wodPlayer_FeedDSP [internal]
1484 * Feed as much sound data as we can into the DSP and return the number of
1485 * milliseconds before it will be necessary to feed the DSP again.
1487 static DWORD wodPlayer_FeedDSP(WINE_WAVEOUT* wwo)
1491 wodUpdatePlayedTotal(wwo, NULL);
1492 availInQ = snd_pcm_avail_update(wwo->p_handle);
1495 /* input queue empty and output buffer with less than one fragment to play */
1496 if (!wwo->lpPlayPtr && wwo->dwBufferSize < availInQ + wwo->dwFragmentSize) {
1497 TRACE("Run out of wavehdr:s...\n");
1502 /* no more room... no need to try to feed */
1504 /* Feed from partial wavehdr */
1505 if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0) {
1506 wodPlayer_WriteMaxFrags(wwo, &availInQ);
1509 /* Feed wavehdrs until we run out of wavehdrs or DSP space */
1510 if (wwo->dwPartialOffset == 0 && wwo->lpPlayPtr) {
1512 TRACE("Setting time to elapse for %p to %lu\n",
1513 wwo->lpPlayPtr, wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength);
1514 /* note the value that dwPlayedTotal will return when this wave finishes playing */
1515 wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
1516 } while (wodPlayer_WriteMaxFrags(wwo, &availInQ) && wwo->lpPlayPtr && availInQ > 0);
1520 return wodPlayer_DSPWait(wwo);
1523 /**************************************************************************
1524 * wodPlayer [internal]
1526 static DWORD CALLBACK wodPlayer(LPVOID pmt)
1528 WORD uDevID = (DWORD)pmt;
1529 WINE_WAVEOUT* wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
1530 DWORD dwNextFeedTime = INFINITE; /* Time before DSP needs feeding */
1531 DWORD dwNextNotifyTime = INFINITE; /* Time before next wave completion */
1534 wwo->state = WINE_WS_STOPPED;
1535 SetEvent(wwo->hStartUpEvent);
1538 /** Wait for the shortest time before an action is required. If there
1539 * are no pending actions, wait forever for a command.
1541 dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
1542 TRACE("waiting %lums (%lu,%lu)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
1543 WAIT_OMR(&wwo->msgRing, dwSleepTime);
1544 wodPlayer_ProcessMessages(wwo);
1545 if (wwo->state == WINE_WS_PLAYING) {
1546 dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1547 dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1548 if (dwNextFeedTime == INFINITE) {
1549 /* FeedDSP ran out of data, but before giving up, */
1550 /* check that a notification didn't give us more */
1551 wodPlayer_ProcessMessages(wwo);
1552 if (wwo->lpPlayPtr) {
1553 TRACE("recovering\n");
1554 dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1558 dwNextFeedTime = dwNextNotifyTime = INFINITE;
1563 /**************************************************************************
1564 * wodGetDevCaps [internal]
1566 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
1568 TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1570 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1572 if (wDevID >= MAX_WAVEOUTDRV) {
1573 TRACE("MAX_WAVOUTDRV reached !\n");
1574 return MMSYSERR_BADDEVICEID;
1577 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1578 return MMSYSERR_NOERROR;
1581 /**************************************************************************
1582 * wodOpen [internal]
1584 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1587 snd_pcm_hw_params_t * hw_params;
1588 snd_pcm_sw_params_t * sw_params;
1589 snd_pcm_access_t access;
1590 snd_pcm_format_t format = -1;
1592 unsigned int buffer_time = 500000;
1593 unsigned int period_time = 10000;
1594 snd_pcm_uframes_t buffer_size;
1595 snd_pcm_uframes_t period_size;
1601 snd_pcm_hw_params_alloca(&hw_params);
1602 snd_pcm_sw_params_alloca(&sw_params);
1604 TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
1605 if (lpDesc == NULL) {
1606 WARN("Invalid Parameter !\n");
1607 return MMSYSERR_INVALPARAM;
1609 if (wDevID >= MAX_WAVEOUTDRV) {
1610 TRACE("MAX_WAVOUTDRV reached !\n");
1611 return MMSYSERR_BADDEVICEID;
1614 /* only PCM format is supported so far... */
1615 if (!supportedFormat(lpDesc->lpFormat)) {
1616 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1617 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1618 lpDesc->lpFormat->nSamplesPerSec);
1619 return WAVERR_BADFORMAT;
1622 if (dwFlags & WAVE_FORMAT_QUERY) {
1623 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1624 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1625 lpDesc->lpFormat->nSamplesPerSec);
1626 return MMSYSERR_NOERROR;
1629 wwo = &WOutDev[wDevID];
1631 if ((dwFlags & WAVE_DIRECTSOUND) && !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
1632 /* not supported, ignore it */
1633 dwFlags &= ~WAVE_DIRECTSOUND;
1636 flags = SND_PCM_NONBLOCK;
1638 if ( dwFlags & WAVE_DIRECTSOUND )
1639 flags |= SND_PCM_ASYNC;
1642 if ( (err = snd_pcm_open(&pcm, wwo->device, SND_PCM_STREAM_PLAYBACK, flags)) < 0)
1644 ERR("Error open: %s\n", snd_strerror(err));
1645 return MMSYSERR_NOTENABLED;
1648 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1650 memcpy(&wwo->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
1651 copy_format(lpDesc->lpFormat, &wwo->format);
1653 if (wwo->format.Format.wBitsPerSample == 0) {
1654 WARN("Resetting zeroed wBitsPerSample\n");
1655 wwo->format.Format.wBitsPerSample = 8 *
1656 (wwo->format.Format.nAvgBytesPerSec /
1657 wwo->format.Format.nSamplesPerSec) /
1658 wwo->format.Format.nChannels;
1661 snd_pcm_hw_params_any(pcm, hw_params);
1663 #define EXIT_ON_ERROR(f,e,txt) do \
1666 if ( (err = (f) ) < 0) \
1668 ERR(txt ": %s\n", snd_strerror(err)); \
1669 snd_pcm_close(pcm); \
1674 access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
1675 if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
1676 WARN("mmap not available. switching to standard write.\n");
1677 access = SND_PCM_ACCESS_RW_INTERLEAVED;
1678 EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
1679 wwo->write = snd_pcm_writei;
1682 wwo->write = snd_pcm_mmap_writei;
1684 EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwo->format.Format.nChannels), MMSYSERR_INVALPARAM, "unable to set required channels");
1686 if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
1687 ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
1688 IsEqualGUID(&wwo->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
1689 format = (wwo->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
1690 (wwo->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
1691 (wwo->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
1692 (wwo->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
1693 } else if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
1694 IsEqualGUID(&wwo->format.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)){
1695 format = (wwo->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_FLOAT_LE : -1;
1696 } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
1697 FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
1699 return WAVERR_BADFORMAT;
1700 } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
1701 FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
1703 return WAVERR_BADFORMAT;
1704 } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
1705 FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
1707 return WAVERR_BADFORMAT;
1709 ERR("invalid format: %0x04x\n", wwo->format.Format.wFormatTag);
1711 return WAVERR_BADFORMAT;
1714 EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), MMSYSERR_INVALPARAM, "unable to set required format");
1716 rate = wwo->format.Format.nSamplesPerSec;
1718 err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
1720 ERR("Rate %ld Hz not available for playback: %s\n", wwo->format.Format.nSamplesPerSec, snd_strerror(rate));
1722 return WAVERR_BADFORMAT;
1724 if (rate != wwo->format.Format.nSamplesPerSec) {
1725 ERR("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwo->format.Format.nSamplesPerSec, rate);
1727 return WAVERR_BADFORMAT;
1730 EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
1732 EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
1734 EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
1736 err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
1737 err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
1739 snd_pcm_sw_params_current(pcm, sw_params);
1740 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");
1741 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
1742 EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
1743 EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
1744 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
1745 EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
1746 #undef EXIT_ON_ERROR
1748 snd_pcm_prepare(pcm);
1751 ALSA_TraceParameters(hw_params, sw_params, FALSE);
1753 /* now, we can save all required data for later use... */
1754 if ( wwo->hw_params )
1755 snd_pcm_hw_params_free(wwo->hw_params);
1756 snd_pcm_hw_params_malloc(&(wwo->hw_params));
1757 snd_pcm_hw_params_copy(wwo->hw_params, hw_params);
1759 wwo->dwBufferSize = buffer_size;
1760 wwo->lpQueuePtr = wwo->lpPlayPtr = wwo->lpLoopPtr = NULL;
1761 wwo->p_handle = pcm;
1762 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1763 wwo->dwPartialOffset = 0;
1765 ALSA_InitRingMessage(&wwo->msgRing);
1767 wwo->count = snd_pcm_poll_descriptors_count (wwo->p_handle);
1768 if (wwo->count <= 0) {
1769 ERR("Invalid poll descriptors count\n");
1770 return MMSYSERR_ERROR;
1773 wwo->ufds = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct pollfd) * wwo->count);
1774 if (wwo->ufds == NULL) {
1775 ERR("No enough memory\n");
1776 return MMSYSERR_NOMEM;
1778 if ((err = snd_pcm_poll_descriptors(wwo->p_handle, wwo->ufds, wwo->count)) < 0) {
1779 ERR("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
1780 return MMSYSERR_ERROR;
1783 if (!(dwFlags & WAVE_DIRECTSOUND)) {
1784 wwo->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1785 wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
1786 WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
1787 CloseHandle(wwo->hStartUpEvent);
1789 wwo->hThread = INVALID_HANDLE_VALUE;
1790 wwo->dwThreadID = 0;
1792 wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
1794 TRACE("handle=%08lx \n", (DWORD)wwo->p_handle);
1795 /* if (wwo->dwFragmentSize % wwo->format.Format.nBlockAlign)
1796 ERR("Fragment doesn't contain an integral number of data blocks\n");
1798 TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
1799 wwo->format.Format.wBitsPerSample, wwo->format.Format.nAvgBytesPerSec,
1800 wwo->format.Format.nSamplesPerSec, wwo->format.Format.nChannels,
1801 wwo->format.Format.nBlockAlign);
1803 return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
1807 /**************************************************************************
1808 * wodClose [internal]
1810 static DWORD wodClose(WORD wDevID)
1812 DWORD ret = MMSYSERR_NOERROR;
1815 TRACE("(%u);\n", wDevID);
1817 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1818 WARN("bad device ID !\n");
1819 return MMSYSERR_BADDEVICEID;
1822 wwo = &WOutDev[wDevID];
1823 if (wwo->lpQueuePtr) {
1824 WARN("buffers still playing !\n");
1825 ret = WAVERR_STILLPLAYING;
1827 if (wwo->hThread != INVALID_HANDLE_VALUE) {
1828 ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1830 ALSA_DestroyRingMessage(&wwo->msgRing);
1832 snd_pcm_hw_params_free(wwo->hw_params);
1833 wwo->hw_params = NULL;
1835 snd_pcm_close(wwo->p_handle);
1836 wwo->p_handle = NULL;
1838 ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1841 HeapFree(GetProcessHeap(), 0, wwo->ufds);
1846 /**************************************************************************
1847 * wodWrite [internal]
1850 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1852 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1854 /* first, do the sanity checks... */
1855 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1856 WARN("bad dev ID !\n");
1857 return MMSYSERR_BADDEVICEID;
1860 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1861 return WAVERR_UNPREPARED;
1863 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1864 return WAVERR_STILLPLAYING;
1866 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1867 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1868 lpWaveHdr->lpNext = 0;
1870 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1872 return MMSYSERR_NOERROR;
1875 /**************************************************************************
1876 * wodPrepare [internal]
1878 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1880 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1882 if (wDevID >= MAX_WAVEOUTDRV) {
1883 WARN("bad device ID !\n");
1884 return MMSYSERR_BADDEVICEID;
1887 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1888 return WAVERR_STILLPLAYING;
1890 lpWaveHdr->dwFlags |= WHDR_PREPARED;
1891 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1892 return MMSYSERR_NOERROR;
1895 /**************************************************************************
1896 * wodUnprepare [internal]
1898 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1900 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1902 if (wDevID >= MAX_WAVEOUTDRV) {
1903 WARN("bad device ID !\n");
1904 return MMSYSERR_BADDEVICEID;
1907 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1908 return WAVERR_STILLPLAYING;
1910 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1911 lpWaveHdr->dwFlags |= WHDR_DONE;
1913 return MMSYSERR_NOERROR;
1916 /**************************************************************************
1917 * wodPause [internal]
1919 static DWORD wodPause(WORD wDevID)
1921 TRACE("(%u);!\n", wDevID);
1923 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1924 WARN("bad device ID !\n");
1925 return MMSYSERR_BADDEVICEID;
1928 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1930 return MMSYSERR_NOERROR;
1933 /**************************************************************************
1934 * wodRestart [internal]
1936 static DWORD wodRestart(WORD wDevID)
1938 TRACE("(%u);\n", wDevID);
1940 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1941 WARN("bad device ID !\n");
1942 return MMSYSERR_BADDEVICEID;
1945 if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1946 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1949 /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1950 /* FIXME: Myst crashes with this ... hmm -MM
1951 return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1954 return MMSYSERR_NOERROR;
1957 /**************************************************************************
1958 * wodReset [internal]
1960 static DWORD wodReset(WORD wDevID)
1962 TRACE("(%u);\n", wDevID);
1964 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1965 WARN("bad device ID !\n");
1966 return MMSYSERR_BADDEVICEID;
1969 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1971 return MMSYSERR_NOERROR;
1974 /**************************************************************************
1975 * wodGetPosition [internal]
1977 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1981 TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1983 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1984 WARN("bad device ID !\n");
1985 return MMSYSERR_BADDEVICEID;
1988 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1990 wwo = &WOutDev[wDevID];
1991 ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1993 return bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->format);
1996 /**************************************************************************
1997 * wodBreakLoop [internal]
1999 static DWORD wodBreakLoop(WORD wDevID)
2001 TRACE("(%u);\n", wDevID);
2003 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
2004 WARN("bad device ID !\n");
2005 return MMSYSERR_BADDEVICEID;
2007 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
2008 return MMSYSERR_NOERROR;
2011 /**************************************************************************
2012 * wodGetVolume [internal]
2014 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
2021 TRACE("(%u, %p);\n", wDevID, lpdwVol);
2022 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
2023 WARN("bad device ID !\n");
2024 return MMSYSERR_BADDEVICEID;
2026 wwo = &WOutDev[wDevID];
2027 count = snd_ctl_elem_info_get_count(wwo->playback_einfo);
2028 min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
2029 max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
2031 #define VOLUME_ALSA_TO_WIN(x) (((x)-min) * 65536 /(max-min))
2032 if (lpdwVol == NULL)
2033 return MMSYSERR_NOTENABLED;
2038 left = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
2039 right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 1));
2042 left = right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
2045 WARN("%d channels mixer not supported\n", count);
2046 return MMSYSERR_NOERROR;
2048 #undef VOLUME_ALSA_TO_WIN
2050 TRACE("left=%d right=%d !\n", left, right);
2051 *lpdwVol = MAKELONG( left, right );
2052 return MMSYSERR_NOERROR;
2055 /**************************************************************************
2056 * wodSetVolume [internal]
2058 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
2065 TRACE("(%u, %08lX);\n", wDevID, dwParam);
2066 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
2067 WARN("bad device ID !\n");
2068 return MMSYSERR_BADDEVICEID;
2070 wwo = &WOutDev[wDevID];
2071 count=snd_ctl_elem_info_get_count(wwo->playback_einfo);
2072 min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
2073 max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
2075 left = LOWORD(dwParam);
2076 right = HIWORD(dwParam);
2078 #define VOLUME_WIN_TO_ALSA(x) ( (((x) * (max-min)) / 65536) + min )
2082 snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
2083 snd_ctl_elem_value_set_integer(wwo->playback_evalue, 1, VOLUME_WIN_TO_ALSA(right));
2086 snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
2089 WARN("%d channels mixer not supported\n", count);
2091 #undef VOLUME_WIN_TO_ALSA
2092 if ( (err = snd_ctl_elem_write(wwo->ctl, wwo->playback_evalue)) < 0)
2094 ERR("error writing snd_ctl_elem_value: %s\n", snd_strerror(err));
2096 return MMSYSERR_NOERROR;
2099 /**************************************************************************
2100 * wodGetNumDevs [internal]
2102 static DWORD wodGetNumDevs(void)
2104 return ALSA_WodNumDevs;
2107 /**************************************************************************
2108 * wodDevInterfaceSize [internal]
2110 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2112 TRACE("(%u, %p)\n", wDevID, dwParam1);
2114 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2115 NULL, 0 ) * sizeof(WCHAR);
2116 return MMSYSERR_NOERROR;
2119 /**************************************************************************
2120 * wodDevInterface [internal]
2122 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2124 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2125 NULL, 0 ) * sizeof(WCHAR))
2127 MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2128 dwParam1, dwParam2 / sizeof(WCHAR));
2129 return MMSYSERR_NOERROR;
2131 return MMSYSERR_INVALPARAM;
2134 /**************************************************************************
2135 * wodMessage (WINEALSA.@)
2137 DWORD WINAPI ALSA_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
2138 DWORD dwParam1, DWORD dwParam2)
2140 TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
2141 wDevID, wMsg, dwUser, dwParam1, dwParam2);
2148 /* FIXME: Pretend this is supported */
2150 case WODM_OPEN: return wodOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2151 case WODM_CLOSE: return wodClose (wDevID);
2152 case WODM_GETDEVCAPS: return wodGetDevCaps (wDevID, (LPWAVEOUTCAPSW)dwParam1, dwParam2);
2153 case WODM_GETNUMDEVS: return wodGetNumDevs ();
2154 case WODM_GETPITCH: return MMSYSERR_NOTSUPPORTED;
2155 case WODM_SETPITCH: return MMSYSERR_NOTSUPPORTED;
2156 case WODM_GETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
2157 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
2158 case WODM_WRITE: return wodWrite (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2159 case WODM_PAUSE: return wodPause (wDevID);
2160 case WODM_GETPOS: return wodGetPosition (wDevID, (LPMMTIME)dwParam1, dwParam2);
2161 case WODM_BREAKLOOP: return wodBreakLoop (wDevID);
2162 case WODM_PREPARE: return wodPrepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2163 case WODM_UNPREPARE: return wodUnprepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2164 case WODM_GETVOLUME: return wodGetVolume (wDevID, (LPDWORD)dwParam1);
2165 case WODM_SETVOLUME: return wodSetVolume (wDevID, dwParam1);
2166 case WODM_RESTART: return wodRestart (wDevID);
2167 case WODM_RESET: return wodReset (wDevID);
2168 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2169 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2170 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
2171 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
2174 FIXME("unknown message %d!\n", wMsg);
2176 return MMSYSERR_NOTSUPPORTED;
2179 /*======================================================================*
2180 * Low level DSOUND implementation *
2181 *======================================================================*/
2183 typedef struct IDsDriverImpl IDsDriverImpl;
2184 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
2186 struct IDsDriverImpl
2188 /* IUnknown fields */
2189 IDsDriverVtbl *lpVtbl;
2191 /* IDsDriverImpl fields */
2193 IDsDriverBufferImpl*primary;
2196 struct IDsDriverBufferImpl
2198 /* IUnknown fields */
2199 IDsDriverBufferVtbl *lpVtbl;
2201 /* IDsDriverBufferImpl fields */
2204 CRITICAL_SECTION mmap_crst;
2206 DWORD mmap_buflen_bytes;
2207 snd_pcm_uframes_t mmap_buflen_frames;
2208 snd_pcm_channel_area_t * mmap_areas;
2209 snd_async_handler_t * mmap_async_handler;
2212 static void DSDB_CheckXRUN(IDsDriverBufferImpl* pdbi)
2214 WINE_WAVEOUT * wwo = &(WOutDev[pdbi->drv->wDevID]);
2215 snd_pcm_state_t state = snd_pcm_state(wwo->p_handle);
2217 if ( state == SND_PCM_STATE_XRUN )
2219 int err = snd_pcm_prepare(wwo->p_handle);
2220 TRACE("xrun occurred\n");
2222 ERR("recovery from xrun failed, prepare failed: %s\n", snd_strerror(err));
2224 else if ( state == SND_PCM_STATE_SUSPENDED )
2226 int err = snd_pcm_resume(wwo->p_handle);
2227 TRACE("recovery from suspension occurred\n");
2228 if (err < 0 && err != -EAGAIN){
2229 err = snd_pcm_prepare(wwo->p_handle);
2231 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
2236 static void DSDB_MMAPCopy(IDsDriverBufferImpl* pdbi)
2238 WINE_WAVEOUT * wwo = &(WOutDev[pdbi->drv->wDevID]);
2239 unsigned int channels;
2240 snd_pcm_format_t format;
2241 snd_pcm_uframes_t period_size;
2242 snd_pcm_sframes_t avail;
2246 if ( !pdbi->mmap_buffer || !wwo->hw_params || !wwo->p_handle)
2249 err = snd_pcm_hw_params_get_channels(wwo->hw_params, &channels);
2250 err = snd_pcm_hw_params_get_format(wwo->hw_params, &format);
2252 err = snd_pcm_hw_params_get_period_size(wwo->hw_params, &period_size, &dir);
2253 avail = snd_pcm_avail_update(wwo->p_handle);
2255 DSDB_CheckXRUN(pdbi);
2257 TRACE("avail=%d format=%s channels=%d\n", (int)avail, snd_pcm_format_name(format), channels );
2259 while (avail >= period_size)
2261 const snd_pcm_channel_area_t *areas;
2262 snd_pcm_uframes_t ofs;
2263 snd_pcm_uframes_t frames;
2266 frames = avail / period_size * period_size; /* round down to a multiple of period_size */
2268 EnterCriticalSection(&pdbi->mmap_crst);
2270 snd_pcm_mmap_begin(wwo->p_handle, &areas, &ofs, &frames);
2271 snd_pcm_areas_copy(areas, ofs, pdbi->mmap_areas, ofs, channels, frames, format);
2272 err = snd_pcm_mmap_commit(wwo->p_handle, ofs, frames);
2274 LeaveCriticalSection(&pdbi->mmap_crst);
2276 if ( err != (snd_pcm_sframes_t) frames)
2277 ERR("mmap partially failed.\n");
2279 avail = snd_pcm_avail_update(wwo->p_handle);
2283 static void DSDB_PCMCallback(snd_async_handler_t *ahandler)
2285 /* snd_pcm_t * handle = snd_async_handler_get_pcm(ahandler); */
2286 IDsDriverBufferImpl* pdbi = snd_async_handler_get_callback_private(ahandler);
2287 TRACE("callback called\n");
2288 DSDB_MMAPCopy(pdbi);
2291 static int DSDB_CreateMMAP(IDsDriverBufferImpl* pdbi)
2293 WINE_WAVEOUT * wwo = &(WOutDev[pdbi->drv->wDevID]);
2294 snd_pcm_format_t format;
2295 snd_pcm_uframes_t frames;
2296 unsigned int channels;
2297 unsigned int bits_per_sample;
2298 unsigned int bits_per_frame;
2299 snd_pcm_channel_area_t * a;
2303 err = snd_pcm_hw_params_get_format(wwo->hw_params, &format);
2304 err = snd_pcm_hw_params_get_buffer_size(wwo->hw_params, &frames);
2305 err = snd_pcm_hw_params_get_channels(wwo->hw_params, &channels);
2306 bits_per_sample = snd_pcm_format_physical_width(format);
2307 bits_per_frame = bits_per_sample * channels;
2311 ALSA_TraceParameters(wwo->hw_params, NULL, FALSE);
2313 TRACE("format=%s frames=%ld channels=%d bits_per_sample=%d bits_per_frame=%d\n",
2314 snd_pcm_format_name(format), frames, channels, bits_per_sample, bits_per_frame);
2316 pdbi->mmap_buflen_frames = frames;
2317 pdbi->mmap_buflen_bytes = snd_pcm_frames_to_bytes( wwo->p_handle, frames );
2318 pdbi->mmap_buffer = HeapAlloc(GetProcessHeap(),0,pdbi->mmap_buflen_bytes);
2319 if (!pdbi->mmap_buffer)
2320 return DSERR_OUTOFMEMORY;
2322 snd_pcm_format_set_silence(format, pdbi->mmap_buffer, frames );
2324 TRACE("created mmap buffer of %ld frames (%ld bytes) at %p\n",
2325 frames, pdbi->mmap_buflen_bytes, pdbi->mmap_buffer);
2327 pdbi->mmap_areas = HeapAlloc(GetProcessHeap(),0,channels*sizeof(snd_pcm_channel_area_t));
2328 if (!pdbi->mmap_areas)
2329 return DSERR_OUTOFMEMORY;
2331 a = pdbi->mmap_areas;
2332 for (c = 0; c < channels; c++, a++)
2334 a->addr = pdbi->mmap_buffer;
2335 a->first = bits_per_sample * c;
2336 a->step = bits_per_frame;
2337 TRACE("Area %d: addr=%p first=%d step=%d\n", c, a->addr, a->first, a->step);
2340 InitializeCriticalSection(&pdbi->mmap_crst);
2342 err = snd_async_add_pcm_handler(&pdbi->mmap_async_handler, wwo->p_handle, DSDB_PCMCallback, pdbi);
2345 ERR("add_pcm_handler failed. reason: %s\n", snd_strerror(err));
2346 return DSERR_GENERIC;
2352 static void DSDB_DestroyMMAP(IDsDriverBufferImpl* pdbi)
2354 TRACE("mmap buffer %p destroyed\n", pdbi->mmap_buffer);
2355 HeapFree(GetProcessHeap(), 0, pdbi->mmap_areas);
2356 HeapFree(GetProcessHeap(), 0, pdbi->mmap_buffer);
2357 pdbi->mmap_areas = NULL;
2358 pdbi->mmap_buffer = NULL;
2359 DeleteCriticalSection(&pdbi->mmap_crst);
2363 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
2365 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2366 FIXME("(): stub!\n");
2367 return DSERR_UNSUPPORTED;
2370 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
2372 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2373 ULONG refCount = InterlockedIncrement(&This->ref);
2375 TRACE("(%p)->(ref before=%lu)\n",This, refCount - 1);
2380 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
2382 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2383 ULONG refCount = InterlockedDecrement(&This->ref);
2385 TRACE("(%p)->(ref before=%lu)\n",This, refCount + 1);
2389 if (This == This->drv->primary)
2390 This->drv->primary = NULL;
2391 DSDB_DestroyMMAP(This);
2392 HeapFree(GetProcessHeap(), 0, This);
2396 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
2397 LPVOID*ppvAudio1,LPDWORD pdwLen1,
2398 LPVOID*ppvAudio2,LPDWORD pdwLen2,
2399 DWORD dwWritePosition,DWORD dwWriteLen,
2402 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2403 TRACE("(%p)\n",iface);
2404 return DSERR_UNSUPPORTED;
2407 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
2408 LPVOID pvAudio1,DWORD dwLen1,
2409 LPVOID pvAudio2,DWORD dwLen2)
2411 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2412 TRACE("(%p)\n",iface);
2413 return DSERR_UNSUPPORTED;
2416 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
2417 LPWAVEFORMATEX pwfx)
2419 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2420 TRACE("(%p,%p)\n",iface,pwfx);
2421 return DSERR_BUFFERLOST;
2424 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
2426 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2427 TRACE("(%p,%ld): stub\n",iface,dwFreq);
2428 return DSERR_UNSUPPORTED;
2431 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
2434 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2435 TRACE("(%p,%p)\n",iface,pVolPan);
2436 vol = pVolPan->dwTotalLeftAmpFactor | (pVolPan->dwTotalRightAmpFactor << 16);
2438 if (wodSetVolume(This->drv->wDevID, vol) != MMSYSERR_NOERROR) {
2439 WARN("wodSetVolume failed\n");
2440 return DSERR_INVALIDPARAM;
2446 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
2448 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2449 TRACE("(%p,%ld): stub\n",iface,dwNewPos);
2450 return DSERR_UNSUPPORTED;
2453 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
2454 LPDWORD lpdwPlay, LPDWORD lpdwWrite)
2456 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2457 WINE_WAVEOUT * wwo = &(WOutDev[This->drv->wDevID]);
2458 snd_pcm_uframes_t hw_ptr;
2459 snd_pcm_uframes_t period_size;
2463 if (wwo->hw_params == NULL) return DSERR_GENERIC;
2466 err = snd_pcm_hw_params_get_period_size(wwo->hw_params, &period_size, &dir);
2468 if (wwo->p_handle == NULL) return DSERR_GENERIC;
2469 /** we need to track down buffer underruns */
2470 DSDB_CheckXRUN(This);
2472 EnterCriticalSection(&This->mmap_crst);
2473 /* FIXME: snd_pcm_mmap_hw_ptr() should not be accessed by a user app. */
2474 /* It will NOT return what why want anyway. */
2475 hw_ptr = _snd_pcm_mmap_hw_ptr(wwo->p_handle);
2477 *lpdwPlay = snd_pcm_frames_to_bytes(wwo->p_handle, hw_ptr/ period_size * period_size) % This->mmap_buflen_bytes;
2479 *lpdwWrite = snd_pcm_frames_to_bytes(wwo->p_handle, (hw_ptr / period_size + 1) * period_size ) % This->mmap_buflen_bytes;
2480 LeaveCriticalSection(&This->mmap_crst);
2482 TRACE("hw_ptr=0x%08x, playpos=%ld, writepos=%ld\n", (unsigned int)hw_ptr, lpdwPlay?*lpdwPlay:-1, lpdwWrite?*lpdwWrite:-1);
2486 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
2488 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2489 WINE_WAVEOUT * wwo = &(WOutDev[This->drv->wDevID]);
2490 snd_pcm_state_t state;
2493 TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
2495 if (wwo->p_handle == NULL) return DSERR_GENERIC;
2497 state = snd_pcm_state(wwo->p_handle);
2498 if ( state == SND_PCM_STATE_SETUP )
2500 err = snd_pcm_prepare(wwo->p_handle);
2501 state = snd_pcm_state(wwo->p_handle);
2503 if ( state == SND_PCM_STATE_PREPARED )
2505 DSDB_MMAPCopy(This);
2506 err = snd_pcm_start(wwo->p_handle);
2511 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
2513 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2514 WINE_WAVEOUT * wwo = &(WOutDev[This->drv->wDevID]);
2519 TRACE("(%p)\n",iface);
2521 if (wwo->p_handle == NULL) return DSERR_GENERIC;
2523 /* ring buffer wrap up detection */
2524 IDsDriverBufferImpl_GetPosition(iface, &play, &write);
2527 TRACE("writepos wrapper up\n");
2531 if ( ( err = snd_pcm_drop(wwo->p_handle)) < 0 )
2533 ERR("error while stopping pcm: %s\n", snd_strerror(err));
2534 return DSERR_GENERIC;
2539 static IDsDriverBufferVtbl dsdbvt =
2541 IDsDriverBufferImpl_QueryInterface,
2542 IDsDriverBufferImpl_AddRef,
2543 IDsDriverBufferImpl_Release,
2544 IDsDriverBufferImpl_Lock,
2545 IDsDriverBufferImpl_Unlock,
2546 IDsDriverBufferImpl_SetFormat,
2547 IDsDriverBufferImpl_SetFrequency,
2548 IDsDriverBufferImpl_SetVolumePan,
2549 IDsDriverBufferImpl_SetPosition,
2550 IDsDriverBufferImpl_GetPosition,
2551 IDsDriverBufferImpl_Play,
2552 IDsDriverBufferImpl_Stop
2555 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
2557 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2558 FIXME("(%p): stub!\n",iface);
2559 return DSERR_UNSUPPORTED;
2562 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
2564 IDsDriverImpl *This = (IDsDriverImpl *)iface;
2565 ULONG refCount = InterlockedIncrement(&This->ref);
2567 TRACE("(%p)->(ref before=%lu)\n",This, refCount - 1);
2572 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
2574 IDsDriverImpl *This = (IDsDriverImpl *)iface;
2575 ULONG refCount = InterlockedDecrement(&This->ref);
2577 TRACE("(%p)->(ref before=%lu)\n",This, refCount + 1);
2581 HeapFree(GetProcessHeap(),0,This);
2585 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
2587 IDsDriverImpl *This = (IDsDriverImpl *)iface;
2588 TRACE("(%p,%p)\n",iface,pDesc);
2589 memcpy(pDesc, &(WOutDev[This->wDevID].ds_desc), sizeof(DSDRIVERDESC));
2590 pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
2591 DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK;
2592 pDesc->dnDevNode = WOutDev[This->wDevID].waveDesc.dnDevNode;
2594 pDesc->wReserved = 0;
2595 pDesc->ulDeviceNum = This->wDevID;
2596 pDesc->dwHeapType = DSDHEAP_NOHEAP;
2597 pDesc->pvDirectDrawHeap = NULL;
2598 pDesc->dwMemStartAddress = 0;
2599 pDesc->dwMemEndAddress = 0;
2600 pDesc->dwMemAllocExtra = 0;
2601 pDesc->pvReserved1 = NULL;
2602 pDesc->pvReserved2 = NULL;
2606 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
2608 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2609 TRACE("(%p)\n",iface);
2613 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
2615 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2616 TRACE("(%p)\n",iface);
2620 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
2622 IDsDriverImpl *This = (IDsDriverImpl *)iface;
2623 TRACE("(%p,%p)\n",iface,pCaps);
2624 memset(pCaps, 0, sizeof(*pCaps));
2626 pCaps->dwFlags = DSCAPS_PRIMARYMONO;
2627 if ( WOutDev[This->wDevID].caps.wChannels == 2 )
2628 pCaps->dwFlags |= DSCAPS_PRIMARYSTEREO;
2630 if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 ) )
2631 pCaps->dwFlags |= DSCAPS_PRIMARY8BIT;
2633 if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S16 | WAVE_FORMAT_2S16 | WAVE_FORMAT_4S16))
2634 pCaps->dwFlags |= DSCAPS_PRIMARY16BIT;
2636 pCaps->dwPrimaryBuffers = 1;
2637 TRACE("caps=0x%X\n",(unsigned int)pCaps->dwFlags);
2638 pCaps->dwMinSecondarySampleRate = DSBFREQUENCY_MIN;
2639 pCaps->dwMaxSecondarySampleRate = DSBFREQUENCY_MAX;
2641 /* the other fields only apply to secondary buffers, which we don't support
2642 * (unless we want to mess with wavetable synthesizers and MIDI) */
2646 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
2647 LPWAVEFORMATEX pwfx,
2648 DWORD dwFlags, DWORD dwCardAddress,
2649 LPDWORD pdwcbBufferSize,
2653 IDsDriverImpl *This = (IDsDriverImpl *)iface;
2654 IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
2657 TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
2658 /* we only support primary buffers */
2659 if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
2660 return DSERR_UNSUPPORTED;
2662 return DSERR_ALLOCATED;
2663 if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
2664 return DSERR_CONTROLUNAVAIL;
2666 *ippdsdb = (IDsDriverBufferImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
2667 if (*ippdsdb == NULL)
2668 return DSERR_OUTOFMEMORY;
2669 (*ippdsdb)->lpVtbl = &dsdbvt;
2670 (*ippdsdb)->ref = 1;
2671 (*ippdsdb)->drv = This;
2673 err = DSDB_CreateMMAP((*ippdsdb));
2676 HeapFree(GetProcessHeap(), 0, *ippdsdb);
2680 *ppbBuffer = (*ippdsdb)->mmap_buffer;
2681 *pdwcbBufferSize = (*ippdsdb)->mmap_buflen_bytes;
2683 This->primary = *ippdsdb;
2685 /* buffer is ready to go */
2686 TRACE("buffer created at %p\n", *ippdsdb);
2690 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
2691 PIDSDRIVERBUFFER pBuffer,
2694 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2695 TRACE("(%p,%p): stub\n",iface,pBuffer);
2696 return DSERR_INVALIDCALL;
2699 static IDsDriverVtbl dsdvt =
2701 IDsDriverImpl_QueryInterface,
2702 IDsDriverImpl_AddRef,
2703 IDsDriverImpl_Release,
2704 IDsDriverImpl_GetDriverDesc,
2706 IDsDriverImpl_Close,
2707 IDsDriverImpl_GetCaps,
2708 IDsDriverImpl_CreateSoundBuffer,
2709 IDsDriverImpl_DuplicateSoundBuffer
2712 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
2714 IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
2716 TRACE("driver created\n");
2718 /* the HAL isn't much better than the HEL if we can't do mmap() */
2719 if (!(WOutDev[wDevID].caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
2720 ERR("DirectSound flag not set\n");
2721 MESSAGE("This sound card's driver does not support direct access\n");
2722 MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
2723 return MMSYSERR_NOTSUPPORTED;
2726 *idrv = (IDsDriverImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
2728 return MMSYSERR_NOMEM;
2729 (*idrv)->lpVtbl = &dsdvt;
2732 (*idrv)->wDevID = wDevID;
2733 (*idrv)->primary = NULL;
2734 return MMSYSERR_NOERROR;
2737 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2739 memcpy(desc, &(WOutDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
2740 return MMSYSERR_NOERROR;
2743 /*======================================================================*
2744 * Low level WAVE IN implementation *
2745 *======================================================================*/
2747 /**************************************************************************
2748 * widNotifyClient [internal]
2750 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
2752 TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
2758 if (wwi->wFlags != DCB_NULL &&
2759 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags, (HDRVR)wwi->waveDesc.hWave,
2760 wMsg, wwi->waveDesc.dwInstance, dwParam1, dwParam2)) {
2761 WARN("can't notify client !\n");
2762 return MMSYSERR_ERROR;
2766 FIXME("Unknown callback message %u\n", wMsg);
2767 return MMSYSERR_INVALPARAM;
2769 return MMSYSERR_NOERROR;
2772 /**************************************************************************
2773 * widGetDevCaps [internal]
2775 static DWORD widGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
2777 TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
2779 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
2781 if (wDevID >= MAX_WAVEINDRV) {
2782 TRACE("MAX_WAVOUTDRV reached !\n");
2783 return MMSYSERR_BADDEVICEID;
2786 memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
2787 return MMSYSERR_NOERROR;
2790 /**************************************************************************
2791 * widRecorder_ReadHeaders [internal]
2793 static void widRecorder_ReadHeaders(WINE_WAVEIN * wwi)
2795 enum win_wm_message tmp_msg;
2800 while (ALSA_RetrieveRingMessage(&wwi->msgRing, &tmp_msg, &tmp_param, &tmp_ev)) {
2801 if (tmp_msg == WINE_WM_HEADER) {
2803 lpWaveHdr = (LPWAVEHDR)tmp_param;
2804 lpWaveHdr->lpNext = 0;
2806 if (wwi->lpQueuePtr == 0)
2807 wwi->lpQueuePtr = lpWaveHdr;
2809 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2813 ERR("should only have headers left\n");
2818 /**************************************************************************
2819 * widRecorder [internal]
2821 static DWORD CALLBACK widRecorder(LPVOID pmt)
2823 WORD uDevID = (DWORD)pmt;
2824 WINE_WAVEIN* wwi = (WINE_WAVEIN*)&WInDev[uDevID];
2828 LPVOID buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, wwi->dwPeriodSize);
2829 char *pOffset = buffer;
2830 enum win_wm_message msg;
2833 DWORD frames_per_period;
2835 wwi->state = WINE_WS_STOPPED;
2836 wwi->dwTotalRecorded = 0;
2837 wwi->lpQueuePtr = NULL;
2839 SetEvent(wwi->hStartUpEvent);
2841 /* make sleep time to be # of ms to output a period */
2842 dwSleepTime = (1024/*wwi-dwPeriodSize => overrun!*/ * 1000) / wwi->format.Format.nAvgBytesPerSec;
2843 frames_per_period = snd_pcm_bytes_to_frames(wwi->p_handle, wwi->dwPeriodSize);
2844 TRACE("sleeptime=%ld ms\n", dwSleepTime);
2847 /* wait for dwSleepTime or an event in thread's queue */
2848 /* FIXME: could improve wait time depending on queue state,
2849 * ie, number of queued fragments
2851 if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
2858 lpWaveHdr = wwi->lpQueuePtr;
2859 /* read all the fragments accumulated so far */
2860 frames = snd_pcm_avail_update(wwi->p_handle);
2861 bytes = snd_pcm_frames_to_bytes(wwi->p_handle, frames);
2862 TRACE("frames = %ld bytes = %ld\n", frames, bytes);
2863 periods = bytes / wwi->dwPeriodSize;
2864 while ((periods > 0) && (wwi->lpQueuePtr))
2867 bytes = wwi->dwPeriodSize;
2868 TRACE("bytes = %ld\n",bytes);
2869 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwPeriodSize)
2871 /* directly read fragment in wavehdr */
2872 read = wwi->read(wwi->p_handle, lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded, frames_per_period);
2873 bytesRead = snd_pcm_frames_to_bytes(wwi->p_handle, read);
2875 TRACE("bytesRead=%ld (direct)\n", bytesRead);
2876 if (bytesRead != (DWORD) -1)
2878 /* update number of bytes recorded in current buffer and by this device */
2879 lpWaveHdr->dwBytesRecorded += bytesRead;
2880 wwi->dwTotalRecorded += bytesRead;
2882 /* buffer is full. notify client */
2883 if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2885 /* must copy the value of next waveHdr, because we have no idea of what
2886 * will be done with the content of lpWaveHdr in callback
2888 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
2890 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2891 lpWaveHdr->dwFlags |= WHDR_DONE;
2893 wwi->lpQueuePtr = lpNext;
2894 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2898 TRACE("read(%s, %p, %ld) failed (%s)\n", wwi->device,
2899 lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2900 frames_per_period, strerror(errno));
2905 /* read the fragment in a local buffer */
2906 read = wwi->read(wwi->p_handle, buffer, frames_per_period);
2907 bytesRead = snd_pcm_frames_to_bytes(wwi->p_handle, read);
2910 TRACE("bytesRead=%ld (local)\n", bytesRead);
2912 if (bytesRead == (DWORD) -1) {
2913 TRACE("read(%s, %p, %ld) failed (%s)\n", wwi->device,
2914 buffer, frames_per_period, strerror(errno));
2918 /* copy data in client buffers */
2919 while (bytesRead != (DWORD) -1 && bytesRead > 0)
2921 DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
2923 memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2927 /* update number of bytes recorded in current buffer and by this device */
2928 lpWaveHdr->dwBytesRecorded += dwToCopy;
2929 wwi->dwTotalRecorded += dwToCopy;
2930 bytesRead -= dwToCopy;
2931 pOffset += dwToCopy;
2933 /* client buffer is full. notify client */
2934 if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2936 /* must copy the value of next waveHdr, because we have no idea of what
2937 * will be done with the content of lpWaveHdr in callback
2939 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
2940 TRACE("lpNext=%p\n", lpNext);
2942 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2943 lpWaveHdr->dwFlags |= WHDR_DONE;
2945 wwi->lpQueuePtr = lpNext;
2946 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2949 if (!lpNext && bytesRead) {
2950 /* before we give up, check for more header messages */
2951 while (ALSA_PeekRingMessage(&wwi->msgRing, &msg, ¶m, &ev))
2953 if (msg == WINE_WM_HEADER) {
2955 ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, ¶m, &ev);
2956 hdr = ((LPWAVEHDR)param);
2957 TRACE("msg = %s, hdr = %p, ev = %p\n", getCmdString(msg), hdr, ev);
2959 if (lpWaveHdr == 0) {
2960 /* new head of queue */
2961 wwi->lpQueuePtr = lpWaveHdr = hdr;
2963 /* insert buffer at the end of queue */
2965 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2972 if (lpWaveHdr == 0) {
2973 /* no more buffer to copy data to, but we did read more.
2974 * what hasn't been copied will be dropped
2976 WARN("buffer under run! %lu bytes dropped.\n", bytesRead);
2977 wwi->lpQueuePtr = NULL;
2987 WAIT_OMR(&wwi->msgRing, dwSleepTime);
2989 while (ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, ¶m, &ev))
2991 TRACE("msg=%s param=0x%lx\n", getCmdString(msg), param);
2993 case WINE_WM_PAUSING:
2994 wwi->state = WINE_WS_PAUSED;
2995 /*FIXME("Device should stop recording\n");*/
2998 case WINE_WM_STARTING:
2999 wwi->state = WINE_WS_PLAYING;
3000 snd_pcm_start(wwi->p_handle);
3003 case WINE_WM_HEADER:
3004 lpWaveHdr = (LPWAVEHDR)param;
3005 lpWaveHdr->lpNext = 0;
3007 /* insert buffer at the end of queue */
3010 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
3014 case WINE_WM_STOPPING:
3015 if (wwi->state != WINE_WS_STOPPED)
3017 snd_pcm_drain(wwi->p_handle);
3019 /* read any headers in queue */
3020 widRecorder_ReadHeaders(wwi);
3022 /* return current buffer to app */
3023 lpWaveHdr = wwi->lpQueuePtr;
3026 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
3027 TRACE("stop %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
3028 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
3029 lpWaveHdr->dwFlags |= WHDR_DONE;
3030 wwi->lpQueuePtr = lpNext;
3031 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
3034 wwi->state = WINE_WS_STOPPED;
3037 case WINE_WM_RESETTING:
3038 if (wwi->state != WINE_WS_STOPPED)
3040 snd_pcm_drain(wwi->p_handle);
3042 wwi->state = WINE_WS_STOPPED;
3043 wwi->dwTotalRecorded = 0;
3045 /* read any headers in queue */
3046 widRecorder_ReadHeaders(wwi);
3048 /* return all buffers to the app */
3049 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
3050 TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
3051 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
3052 lpWaveHdr->dwFlags |= WHDR_DONE;
3053 wwi->lpQueuePtr = lpWaveHdr->lpNext;
3054 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
3057 wwi->lpQueuePtr = NULL;
3060 case WINE_WM_CLOSING:
3062 wwi->state = WINE_WS_CLOSED;
3064 HeapFree(GetProcessHeap(), 0, buffer);
3066 /* shouldn't go here */
3067 case WINE_WM_UPDATE:
3072 FIXME("unknown message %d\n", msg);
3078 /* just for not generating compilation warnings... should never be executed */
3082 /**************************************************************************
3083 * widOpen [internal]
3085 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
3088 snd_pcm_hw_params_t * hw_params;
3089 snd_pcm_sw_params_t * sw_params;
3090 snd_pcm_access_t access;
3091 snd_pcm_format_t format;
3093 unsigned int buffer_time = 500000;
3094 unsigned int period_time = 10000;
3095 snd_pcm_uframes_t buffer_size;
3096 snd_pcm_uframes_t period_size;
3102 snd_pcm_hw_params_alloca(&hw_params);
3103 snd_pcm_sw_params_alloca(&sw_params);
3105 TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
3106 if (lpDesc == NULL) {
3107 WARN("Invalid Parameter !\n");
3108 return MMSYSERR_INVALPARAM;
3110 if (wDevID >= MAX_WAVEOUTDRV) {
3111 TRACE("MAX_WAVOUTDRV reached !\n");
3112 return MMSYSERR_BADDEVICEID;
3115 /* only PCM format is supported so far... */
3116 if (!supportedFormat(lpDesc->lpFormat)) {
3117 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
3118 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
3119 lpDesc->lpFormat->nSamplesPerSec);
3120 return WAVERR_BADFORMAT;
3123 if (dwFlags & WAVE_FORMAT_QUERY) {
3124 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
3125 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
3126 lpDesc->lpFormat->nSamplesPerSec);
3127 return MMSYSERR_NOERROR;
3130 wwi = &WInDev[wDevID];
3132 if ((dwFlags & WAVE_DIRECTSOUND) && !(wwi->caps.dwSupport & WAVECAPS_DIRECTSOUND))
3133 /* not supported, ignore it */
3134 dwFlags &= ~WAVE_DIRECTSOUND;
3137 flags = SND_PCM_NONBLOCK;
3139 if ( dwFlags & WAVE_DIRECTSOUND )
3140 flags |= SND_PCM_ASYNC;
3143 if ( (err=snd_pcm_open(&pcm, wwi->device, SND_PCM_STREAM_CAPTURE, flags)) < 0 )
3145 ERR("Error open: %s\n", snd_strerror(err));
3146 return MMSYSERR_NOTENABLED;
3149 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
3151 memcpy(&wwi->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
3152 copy_format(lpDesc->lpFormat, &wwi->format);
3154 if (wwi->format.Format.wBitsPerSample == 0) {
3155 WARN("Resetting zeroed wBitsPerSample\n");
3156 wwi->format.Format.wBitsPerSample = 8 *
3157 (wwi->format.Format.nAvgBytesPerSec /
3158 wwi->format.Format.nSamplesPerSec) /
3159 wwi->format.Format.nChannels;
3162 snd_pcm_hw_params_any(pcm, hw_params);
3164 #define EXIT_ON_ERROR(f,e,txt) do \
3167 if ( (err = (f) ) < 0) \
3169 ERR(txt ": %s\n", snd_strerror(err)); \
3170 snd_pcm_close(pcm); \
3175 access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
3176 if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
3177 WARN("mmap not available. switching to standard write.\n");
3178 access = SND_PCM_ACCESS_RW_INTERLEAVED;
3179 EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
3180 wwi->read = snd_pcm_readi;
3183 wwi->read = snd_pcm_mmap_readi;
3185 EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwi->format.Format.nChannels), MMSYSERR_INVALPARAM, "unable to set required channels");
3187 if ((wwi->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
3188 ((wwi->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
3189 IsEqualGUID(&wwi->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
3190 format = (wwi->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
3191 (wwi->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
3192 (wwi->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
3193 (wwi->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
3194 } else if ((wwi->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
3195 IsEqualGUID(&wwi->format.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)){
3196 format = (wwi->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_FLOAT_LE : -1;
3197 } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
3198 FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
3200 return WAVERR_BADFORMAT;
3201 } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
3202 FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
3204 return WAVERR_BADFORMAT;
3205 } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
3206 FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
3208 return WAVERR_BADFORMAT;
3210 ERR("invalid format: %0x04x\n", wwi->format.Format.wFormatTag);
3212 return WAVERR_BADFORMAT;
3215 EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), MMSYSERR_INVALPARAM, "unable to set required format");
3217 rate = wwi->format.Format.nSamplesPerSec;
3219 err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
3221 ERR("Rate %ld Hz not available for playback: %s\n", wwi->format.Format.nSamplesPerSec, snd_strerror(rate));
3223 return WAVERR_BADFORMAT;
3225 if (rate != wwi->format.Format.nSamplesPerSec) {
3226 ERR("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwi->format.Format.nSamplesPerSec, rate);
3228 return WAVERR_BADFORMAT;
3232 EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
3234 EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
3236 EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
3239 err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
3240 err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
3242 snd_pcm_sw_params_current(pcm, sw_params);
3243 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");
3244 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
3245 EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
3246 EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
3247 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
3248 EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
3249 #undef EXIT_ON_ERROR
3251 snd_pcm_prepare(pcm);
3254 ALSA_TraceParameters(hw_params, sw_params, FALSE);
3256 /* now, we can save all required data for later use... */
3257 if ( wwi->hw_params )
3258 snd_pcm_hw_params_free(wwi->hw_params);
3259 snd_pcm_hw_params_malloc(&(wwi->hw_params));
3260 snd_pcm_hw_params_copy(wwi->hw_params, hw_params);
3262 wwi->dwBufferSize = buffer_size;
3263 wwi->lpQueuePtr = wwi->lpPlayPtr = wwi->lpLoopPtr = NULL;
3264 wwi->p_handle = pcm;
3266 ALSA_InitRingMessage(&wwi->msgRing);
3268 wwi->count = snd_pcm_poll_descriptors_count (wwi->p_handle);
3269 if (wwi->count <= 0) {
3270 ERR("Invalid poll descriptors count\n");
3271 return MMSYSERR_ERROR;
3274 wwi->ufds = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct pollfd) * wwi->count);
3275 if (wwi->ufds == NULL) {
3276 ERR("No enough memory\n");
3277 return MMSYSERR_NOMEM;
3279 if ((err = snd_pcm_poll_descriptors(wwi->p_handle, wwi->ufds, wwi->count)) < 0) {
3280 ERR("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
3281 return MMSYSERR_ERROR;
3284 wwi->dwPeriodSize = period_size;
3285 /*if (wwi->dwFragmentSize % wwi->format.Format.nBlockAlign)
3286 ERR("Fragment doesn't contain an integral number of data blocks\n");
3288 TRACE("dwPeriodSize=%lu\n", wwi->dwPeriodSize);
3289 TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
3290 wwi->format.Format.wBitsPerSample, wwi->format.Format.nAvgBytesPerSec,
3291 wwi->format.Format.nSamplesPerSec, wwi->format.Format.nChannels,
3292 wwi->format.Format.nBlockAlign);
3294 if (!(dwFlags & WAVE_DIRECTSOUND)) {
3295 wwi->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
3296 wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
3297 WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
3298 CloseHandle(wwi->hStartUpEvent);
3300 wwi->hThread = INVALID_HANDLE_VALUE;
3301 wwi->dwThreadID = 0;
3303 wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
3305 return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
3309 /**************************************************************************
3310 * widClose [internal]
3312 static DWORD widClose(WORD wDevID)
3314 DWORD ret = MMSYSERR_NOERROR;
3317 TRACE("(%u);\n", wDevID);
3319 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3320 WARN("bad device ID !\n");
3321 return MMSYSERR_BADDEVICEID;
3324 wwi = &WInDev[wDevID];
3325 if (wwi->lpQueuePtr) {
3326 WARN("buffers still playing !\n");
3327 ret = WAVERR_STILLPLAYING;
3329 if (wwi->hThread != INVALID_HANDLE_VALUE) {
3330 ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
3332 ALSA_DestroyRingMessage(&wwi->msgRing);
3334 snd_pcm_hw_params_free(wwi->hw_params);
3335 wwi->hw_params = NULL;
3337 snd_pcm_close(wwi->p_handle);
3338 wwi->p_handle = NULL;
3340 ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
3343 HeapFree(GetProcessHeap(), 0, wwi->ufds);
3347 /**************************************************************************
3348 * widAddBuffer [internal]
3351 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3353 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3355 /* first, do the sanity checks... */
3356 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3357 WARN("bad dev ID !\n");
3358 return MMSYSERR_BADDEVICEID;
3361 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
3362 return WAVERR_UNPREPARED;
3364 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3365 return WAVERR_STILLPLAYING;
3367 lpWaveHdr->dwFlags &= ~WHDR_DONE;
3368 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
3369 lpWaveHdr->lpNext = 0;
3371 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
3373 return MMSYSERR_NOERROR;
3376 /**************************************************************************
3377 * widPrepare [internal]
3379 static DWORD widPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3381 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3383 if (wDevID >= MAX_WAVEINDRV) {
3384 WARN("bad device ID !\n");
3385 return MMSYSERR_BADDEVICEID;
3388 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3389 return WAVERR_STILLPLAYING;
3391 lpWaveHdr->dwFlags |= WHDR_PREPARED;
3392 lpWaveHdr->dwFlags &= ~WHDR_DONE;
3393 return MMSYSERR_NOERROR;
3396 /**************************************************************************
3397 * widUnprepare [internal]
3399 static DWORD widUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3401 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3403 if (wDevID >= MAX_WAVEINDRV) {
3404 WARN("bad device ID !\n");
3405 return MMSYSERR_BADDEVICEID;
3408 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3409 return WAVERR_STILLPLAYING;
3411 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
3412 lpWaveHdr->dwFlags |= WHDR_DONE;
3414 return MMSYSERR_NOERROR;
3417 /**************************************************************************
3418 * widStart [internal]
3421 static DWORD widStart(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_STARTING, 0, TRUE);
3435 return MMSYSERR_NOERROR;
3438 /**************************************************************************
3439 * widStop [internal]
3442 static DWORD widStop(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3444 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3446 /* first, do the sanity checks... */
3447 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3448 WARN("bad dev ID !\n");
3449 return MMSYSERR_BADDEVICEID;
3452 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
3454 return MMSYSERR_NOERROR;
3457 /**************************************************************************
3458 * widReset [internal]
3460 static DWORD widReset(WORD wDevID)
3462 TRACE("(%u);\n", wDevID);
3463 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
3464 WARN("can't reset !\n");
3465 return MMSYSERR_INVALHANDLE;
3467 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
3468 return MMSYSERR_NOERROR;
3471 /**************************************************************************
3472 * widGetPosition [internal]
3474 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
3478 TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
3480 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
3481 WARN("can't get pos !\n");
3482 return MMSYSERR_INVALHANDLE;
3485 if (lpTime == NULL) {
3486 WARN("invalid parameter: lpTime = NULL\n");
3487 return MMSYSERR_INVALPARAM;
3490 wwi = &WInDev[wDevID];
3491 ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_UPDATE, 0, TRUE);
3493 return bytes_to_mmtime(lpTime, wwi->dwTotalRecorded, &wwi->format);
3496 /**************************************************************************
3497 * widGetNumDevs [internal]
3499 static DWORD widGetNumDevs(void)
3501 return ALSA_WidNumDevs;
3504 /**************************************************************************
3505 * widDevInterfaceSize [internal]
3507 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
3509 TRACE("(%u, %p)\n", wDevID, dwParam1);
3511 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3512 NULL, 0 ) * sizeof(WCHAR);
3513 return MMSYSERR_NOERROR;
3516 /**************************************************************************
3517 * widDevInterface [internal]
3519 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
3521 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3522 NULL, 0 ) * sizeof(WCHAR))
3524 MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3525 dwParam1, dwParam2 / sizeof(WCHAR));
3526 return MMSYSERR_NOERROR;
3528 return MMSYSERR_INVALPARAM;
3531 /**************************************************************************
3532 * widDsCreate [internal]
3534 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
3536 TRACE("(%d,%p)\n",wDevID,drv);
3538 /* the HAL isn't much better than the HEL if we can't do mmap() */
3539 FIXME("DirectSoundCapture not implemented\n");
3540 MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
3541 return MMSYSERR_NOTSUPPORTED;
3544 /**************************************************************************
3545 * widDsDesc [internal]
3547 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
3549 memcpy(desc, &(WInDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
3550 return MMSYSERR_NOERROR;
3553 /**************************************************************************
3554 * widMessage (WINEALSA.@)
3556 DWORD WINAPI ALSA_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
3557 DWORD dwParam1, DWORD dwParam2)
3559 TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
3560 wDevID, wMsg, dwUser, dwParam1, dwParam2);
3567 /* FIXME: Pretend this is supported */
3569 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
3570 case WIDM_CLOSE: return widClose (wDevID);
3571 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3572 case WIDM_PREPARE: return widPrepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3573 case WIDM_UNPREPARE: return widUnprepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3574 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEOUTCAPSW)dwParam1, dwParam2);
3575 case WIDM_GETNUMDEVS: return widGetNumDevs ();
3576 case WIDM_GETPOS: return widGetPosition (wDevID, (LPMMTIME)dwParam1, dwParam2);
3577 case WIDM_RESET: return widReset (wDevID);
3578 case WIDM_START: return widStart (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3579 case WIDM_STOP: return widStop (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3580 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
3581 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
3582 case DRV_QUERYDSOUNDIFACE: return widDsCreate (wDevID, (PIDSCDRIVER*)dwParam1);
3583 case DRV_QUERYDSOUNDDESC: return widDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
3585 FIXME("unknown message %d!\n", wMsg);
3587 return MMSYSERR_NOTSUPPORTED;
3592 /**************************************************************************
3593 * widMessage (WINEALSA.@)
3595 DWORD WINAPI ALSA_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3596 DWORD dwParam1, DWORD dwParam2)
3598 FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3599 return MMSYSERR_NOTENABLED;
3602 /**************************************************************************
3603 * wodMessage (WINEALSA.@)
3605 DWORD WINAPI ALSA_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3606 DWORD dwParam1, DWORD dwParam2)
3608 FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3609 return MMSYSERR_NOTENABLED;
3612 #endif /* HAVE_ALSA */