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 (6)
78 #define MAX_WAVEINDRV (6)
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;
203 /* ALSA information (ALSA 0.9/1.x uses two different devices for playback/capture) */
205 char interface_name[64];
206 snd_pcm_t* p_handle; /* handle to ALSA playback device */
207 snd_pcm_t* c_handle; /* handle to ALSA capture device */
208 snd_pcm_hw_params_t * hw_params; /* ALSA Hw params */
210 snd_pcm_sframes_t (*read)(snd_pcm_t *, void *, snd_pcm_uframes_t );
215 DWORD dwPeriodSize; /* size of OSS buffer period */
216 DWORD dwBufferSize; /* size of whole ALSA buffer in bytes */
217 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
218 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
220 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
221 DWORD dwLoops; /* private copy of loop counter */
223 /*DWORD dwPlayedTotal; */
224 DWORD dwTotalRecorded;
226 /* synchronization stuff */
227 HANDLE hStartUpEvent;
230 ALSA_MSG_RING msgRing;
232 /* DirectSound stuff */
233 DSDRIVERDESC ds_desc;
236 static WINE_WAVEOUT WOutDev [MAX_WAVEOUTDRV];
237 static DWORD ALSA_WodNumDevs;
238 static WINE_WAVEIN WInDev [MAX_WAVEINDRV];
239 static DWORD ALSA_WidNumDevs;
241 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
242 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
244 /* These strings used only for tracing */
245 static const char * getCmdString(enum win_wm_message msg)
247 static char unknown[32];
248 #define MSG_TO_STR(x) case x: return #x
250 MSG_TO_STR(WINE_WM_PAUSING);
251 MSG_TO_STR(WINE_WM_RESTARTING);
252 MSG_TO_STR(WINE_WM_RESETTING);
253 MSG_TO_STR(WINE_WM_HEADER);
254 MSG_TO_STR(WINE_WM_UPDATE);
255 MSG_TO_STR(WINE_WM_BREAKLOOP);
256 MSG_TO_STR(WINE_WM_CLOSING);
257 MSG_TO_STR(WINE_WM_STARTING);
258 MSG_TO_STR(WINE_WM_STOPPING);
261 sprintf(unknown, "UNKNOWN(0x%08x)", msg);
265 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
266 WAVEFORMATPCMEX* format)
268 TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
269 lpTime->wType, format->Format.wBitsPerSample, format->Format.nSamplesPerSec,
270 format->Format.nChannels, format->Format.nAvgBytesPerSec);
271 TRACE("Position in bytes=%lu\n", position);
273 switch (lpTime->wType) {
275 lpTime->u.sample = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
276 TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
279 lpTime->u.ms = 1000.0 * position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels * format->Format.nSamplesPerSec);
280 TRACE("TIME_MS=%lu\n", lpTime->u.ms);
283 lpTime->u.smpte.fps = 30;
284 position = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
285 position += (format->Format.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
286 lpTime->u.smpte.sec = position / format->Format.nSamplesPerSec;
287 position -= lpTime->u.smpte.sec * format->Format.nSamplesPerSec;
288 lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
289 lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
290 lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
291 lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
292 lpTime->u.smpte.fps = 30;
293 lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->Format.nSamplesPerSec;
294 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
295 lpTime->u.smpte.hour, lpTime->u.smpte.min,
296 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
299 WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
300 lpTime->wType = TIME_BYTES;
303 lpTime->u.cb = position;
304 TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
307 return MMSYSERR_NOERROR;
310 static BOOL supportedFormat(LPWAVEFORMATEX wf)
314 if (wf->nSamplesPerSec<DSBFREQUENCY_MIN||wf->nSamplesPerSec>DSBFREQUENCY_MAX)
317 if (wf->wFormatTag == WAVE_FORMAT_PCM) {
318 if (wf->nChannels==1||wf->nChannels==2) {
319 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
322 } else if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
323 WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE *)wf;
325 if (wf->cbSize == 22 &&
326 (IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM) ||
327 IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))) {
328 if (wf->nChannels>=1 && wf->nChannels<=6) {
329 if (wf->wBitsPerSample==wfex->Samples.wValidBitsPerSample) {
330 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16||
331 wf->wBitsPerSample==24||wf->wBitsPerSample==32) {
335 WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
338 WARN("only KSDATAFORMAT_SUBTYPE_PCM and KSDATAFORMAT_SUBTYPE_IEEE_FLOAT "
340 } else if (wf->wFormatTag == WAVE_FORMAT_MULAW || wf->wFormatTag == WAVE_FORMAT_ALAW) {
341 if (wf->wBitsPerSample==8)
344 ERR("WAVE_FORMAT_MULAW and WAVE_FORMAT_ALAW wBitsPerSample must = 8\n");
346 } else if (wf->wFormatTag == WAVE_FORMAT_ADPCM) {
347 if (wf->wBitsPerSample==4)
350 ERR("WAVE_FORMAT_ADPCM wBitsPerSample must = 4\n");
352 WARN("only WAVE_FORMAT_PCM and WAVE_FORMAT_EXTENSIBLE supported\n");
357 static void copy_format(LPWAVEFORMATEX wf1, LPWAVEFORMATPCMEX wf2)
359 ZeroMemory(wf2, sizeof(wf2));
360 if (wf1->wFormatTag == WAVE_FORMAT_PCM)
361 memcpy(wf2, wf1, sizeof(PCMWAVEFORMAT));
362 else if (wf1->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
363 memcpy(wf2, wf1, sizeof(WAVEFORMATPCMEX));
365 memcpy(wf2, wf1, sizeof(WAVEFORMATEX) + wf1->cbSize);
368 /*======================================================================*
369 * Low level WAVE implementation *
370 *======================================================================*/
372 /**************************************************************************
373 * ALSA_InitializeVolumeCtl [internal]
375 * used to initialize the PCM Volume Control
377 static int ALSA_InitializeVolumeCtl(WINE_WAVEOUT * wwo)
379 snd_ctl_t * ctl = NULL;
380 snd_ctl_card_info_t * cardinfo;
381 snd_ctl_elem_list_t * elemlist;
382 snd_ctl_elem_id_t * e_id;
383 snd_ctl_elem_info_t * einfo;
384 snd_hctl_t * hctl = NULL;
385 snd_hctl_elem_t * elem;
390 snd_ctl_card_info_alloca(&cardinfo);
391 memset(cardinfo,0,snd_ctl_card_info_sizeof());
393 snd_ctl_elem_list_alloca(&elemlist);
394 memset(elemlist,0,snd_ctl_elem_list_sizeof());
396 snd_ctl_elem_id_alloca(&e_id);
397 memset(e_id,0,snd_ctl_elem_id_sizeof());
399 snd_ctl_elem_info_alloca(&einfo);
400 memset(einfo,0,snd_ctl_elem_info_sizeof());
402 #define EXIT_ON_ERROR(f,txt) do \
405 if ( (err = (f) ) < 0) \
407 ERR(txt ": %s\n", snd_strerror(err)); \
409 snd_hctl_close(hctl); \
411 snd_ctl_close(ctl); \
416 sprintf(device, "hw:%ld", ALSA_WodNumDevs);
418 EXIT_ON_ERROR( snd_ctl_open(&ctl, device, 0) , "ctl open failed" );
419 EXIT_ON_ERROR( snd_ctl_card_info(ctl, cardinfo), "card info failed");
420 EXIT_ON_ERROR( snd_ctl_elem_list(ctl, elemlist), "elem list failed");
422 nCtrls = snd_ctl_elem_list_get_count(elemlist);
424 EXIT_ON_ERROR( snd_hctl_open(&hctl, device, 0), "hctl open failed");
425 EXIT_ON_ERROR( snd_hctl_load(hctl), "hctl load failed" );
427 elem=snd_hctl_first_elem(hctl);
428 for ( i= 0; i<nCtrls; i++) {
430 memset(e_id,0,snd_ctl_elem_id_sizeof());
432 snd_hctl_elem_get_id(elem,e_id);
434 TRACE("ctl: #%d '%s'%d\n",
435 snd_ctl_elem_id_get_numid(e_id),
436 snd_ctl_elem_id_get_name(e_id),
437 snd_ctl_elem_id_get_index(e_id));
439 if ( !strcmp("PCM Playback Volume", snd_ctl_elem_id_get_name(e_id)) )
441 EXIT_ON_ERROR( snd_hctl_elem_info(elem,einfo), "hctl elem info failed" );
443 /* few sanity checks... you'll never know... */
444 if ( snd_ctl_elem_info_get_type(einfo) != SND_CTL_ELEM_TYPE_INTEGER )
445 WARN("playback volume control is not an integer\n");
446 if ( !snd_ctl_elem_info_is_readable(einfo) )
447 WARN("playback volume control is readable\n");
448 if ( !snd_ctl_elem_info_is_writable(einfo) )
449 WARN("playback volume control is readable\n");
451 TRACE(" ctrl range: min=%ld max=%ld step=%ld\n",
452 snd_ctl_elem_info_get_min(einfo),
453 snd_ctl_elem_info_get_max(einfo),
454 snd_ctl_elem_info_get_step(einfo));
456 EXIT_ON_ERROR( snd_ctl_elem_id_malloc(&wwo->playback_eid), "elem id malloc failed" );
457 EXIT_ON_ERROR( snd_ctl_elem_info_malloc(&wwo->playback_einfo), "elem info malloc failed" );
458 EXIT_ON_ERROR( snd_ctl_elem_value_malloc(&wwo->playback_evalue), "elem value malloc failed" );
460 /* ok, now we can safely save these objects for later */
461 snd_ctl_elem_id_copy(wwo->playback_eid, e_id);
462 snd_ctl_elem_info_copy(wwo->playback_einfo, einfo);
463 snd_ctl_elem_value_set_id(wwo->playback_evalue, wwo->playback_eid);
467 elem=snd_hctl_elem_next(elem);
469 snd_hctl_close(hctl);
474 /**************************************************************************
475 * ALSA_XRUNRecovery [internal]
477 * used to recovery from XRUN errors (buffer underflow/overflow)
479 static int ALSA_XRUNRecovery(WINE_WAVEOUT * wwo, int err)
481 if (err == -EPIPE) { /* under-run */
482 err = snd_pcm_prepare(wwo->p_handle);
484 ERR( "underrun recovery failed. prepare failed: %s\n", snd_strerror(err));
486 } else if (err == -ESTRPIPE) {
487 while ((err = snd_pcm_resume(wwo->p_handle)) == -EAGAIN)
488 sleep(1); /* wait until the suspend flag is released */
490 err = snd_pcm_prepare(wwo->p_handle);
492 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
499 /**************************************************************************
500 * ALSA_TraceParameters [internal]
502 * used to trace format changes, hw and sw parameters
504 static void ALSA_TraceParameters(snd_pcm_hw_params_t * hw_params, snd_pcm_sw_params_t * sw, int full)
507 snd_pcm_format_t format;
508 snd_pcm_access_t access;
510 err = snd_pcm_hw_params_get_access(hw_params, &access);
511 err = snd_pcm_hw_params_get_format(hw_params, &format);
513 #define X(x) ((x)? "true" : "false")
515 TRACE("FLAGS: sampleres=%s overrng=%s pause=%s resume=%s syncstart=%s batch=%s block=%s double=%s "
516 "halfd=%s joint=%s \n",
517 X(snd_pcm_hw_params_can_mmap_sample_resolution(hw_params)),
518 X(snd_pcm_hw_params_can_overrange(hw_params)),
519 X(snd_pcm_hw_params_can_pause(hw_params)),
520 X(snd_pcm_hw_params_can_resume(hw_params)),
521 X(snd_pcm_hw_params_can_sync_start(hw_params)),
522 X(snd_pcm_hw_params_is_batch(hw_params)),
523 X(snd_pcm_hw_params_is_block_transfer(hw_params)),
524 X(snd_pcm_hw_params_is_double(hw_params)),
525 X(snd_pcm_hw_params_is_half_duplex(hw_params)),
526 X(snd_pcm_hw_params_is_joint_duplex(hw_params)));
530 TRACE("access=%s\n", snd_pcm_access_name(access));
533 snd_pcm_access_mask_t * acmask;
534 snd_pcm_access_mask_alloca(&acmask);
535 snd_pcm_hw_params_get_access_mask(hw_params, acmask);
536 for ( access = SND_PCM_ACCESS_MMAP_INTERLEAVED; access <= SND_PCM_ACCESS_LAST; access++)
537 if (snd_pcm_access_mask_test(acmask, access))
538 TRACE("access=%s\n", snd_pcm_access_name(access));
543 TRACE("format=%s\n", snd_pcm_format_name(format));
548 snd_pcm_format_mask_t * fmask;
550 snd_pcm_format_mask_alloca(&fmask);
551 snd_pcm_hw_params_get_format_mask(hw_params, fmask);
552 for ( format = SND_PCM_FORMAT_S8; format <= SND_PCM_FORMAT_LAST ; format++)
553 if ( snd_pcm_format_mask_test(fmask, format) )
554 TRACE("format=%s\n", snd_pcm_format_name(format));
560 err = snd_pcm_hw_params_get_channels(hw_params, &val);
562 unsigned int min = 0;
563 unsigned int max = 0;
564 err = snd_pcm_hw_params_get_channels_min(hw_params, &min),
565 err = snd_pcm_hw_params_get_channels_max(hw_params, &max);
566 TRACE("channels_min=%u, channels_min_max=%u\n", min, max);
568 TRACE("channels_min=%d\n", val);
573 snd_pcm_uframes_t val=0;
574 err = snd_pcm_hw_params_get_buffer_size(hw_params, &val);
576 snd_pcm_uframes_t min = 0;
577 snd_pcm_uframes_t max = 0;
578 err = snd_pcm_hw_params_get_buffer_size_min(hw_params, &min),
579 err = snd_pcm_hw_params_get_buffer_size_max(hw_params, &max);
580 TRACE("buffer_size_min=%lu, buffer_size_min_max=%lu\n", min, max);
582 TRACE("buffer_size_min=%lu\n", val);
589 unsigned int val=0; \
590 err = snd_pcm_hw_params_get_##x(hw_params,&val, &dir); \
592 unsigned int min = 0; \
593 unsigned int max = 0; \
594 err = snd_pcm_hw_params_get_##x##_min(hw_params, &min, &dir); \
595 err = snd_pcm_hw_params_get_##x##_max(hw_params, &max, &dir); \
596 TRACE(#x "_min=%u " #x "_max=%u\n", min, max); \
598 TRACE(#x "=%d\n", val); \
607 snd_pcm_uframes_t val=0;
608 err = snd_pcm_hw_params_get_period_size(hw_params, &val, &dir);
610 snd_pcm_uframes_t min = 0;
611 snd_pcm_uframes_t max = 0;
612 err = snd_pcm_hw_params_get_period_size_min(hw_params, &min, &dir),
613 err = snd_pcm_hw_params_get_period_size_max(hw_params, &max, &dir);
614 TRACE("period_size_min=%lu, period_size_min_max=%lu\n", min, max);
616 TRACE("period_size_min=%lu\n", val);
628 /* return a string duplicated on the win32 process heap, free with HeapFree */
629 static char* ALSA_strdup(char *s) {
630 char *result = HeapAlloc(GetProcessHeap(), 0, strlen(s)+1);
635 /******************************************************************
636 * ALSA_GetDeviceFromReg
638 * Returns either "plug:hw" or reads the registry so the user can
639 * override the playback/record device used.
641 static char *ALSA_GetDeviceFromReg(const char *value)
649 res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\ALSA", 0, KEY_QUERY_VALUE, &key);
650 if (res != ERROR_SUCCESS) goto end;
652 res = RegQueryValueExA(key, value, NULL, &type, NULL, &resultSize);
653 if (res != ERROR_SUCCESS) goto end;
655 if (type != REG_SZ) {
656 ERR("Registry key [HKEY_LOCAL_MACHINE\\Software\\Wine\\Wine\\ALSA\\%s] must be a string\n", value);
660 result = HeapAlloc(GetProcessHeap(), 0, resultSize);
661 res = RegQueryValueExA(key, value, NULL, NULL, result, &resultSize);
665 result = ALSA_strdup("plug:hw");
673 /******************************************************************
676 * Initialize internal structures from ALSA information
678 LONG ALSA_WaveInit(void)
681 snd_pcm_info_t * info;
682 snd_pcm_hw_params_t * hw_params;
683 unsigned int ratemin=0;
684 unsigned int ratemax=0;
685 unsigned int chmin=0;
686 unsigned int chmax=0;
693 if (!wine_dlopen("libasound.so.2", RTLD_LAZY|RTLD_GLOBAL, NULL, 0))
695 ERR("Error: ALSA lib needs to be loaded with flags RTLD_LAZY and RTLD_GLOBAL.\n");
701 for (i = 0; i < MAX_WAVEOUTDRV; i++)
706 snd_pcm_format_mask_t * fmask;
707 snd_pcm_access_mask_t * acmask;
709 wwo = &WOutDev[ALSA_WodNumDevs];
711 regdev = ALSA_GetDeviceFromReg("PlaybackDevice");
712 sprintf(device, "%s:%d", regdev, i);
713 HeapFree(GetProcessHeap(), 0, regdev);
714 wwo->device = HeapAlloc(GetProcessHeap(), 0, strlen(device));
715 strcpy(wwo->device, device);
716 TRACE("using waveout device \"%s\"\n", wwo->device);
718 snprintf(wwo->interface_name, sizeof(wwo->interface_name), "winealsa: %s", wwo->device);
720 wwo->caps.wMid = 0x0002;
721 wwo->caps.wPid = 0x0104;
722 wwo->caps.vDriverVersion = 0x0100;
723 wwo->caps.dwFormats = 0x00000000;
724 wwo->caps.dwSupport = 0;
725 strcpy(wwo->ds_desc.szDrvname, "winealsa.drv");
727 snd_pcm_info_alloca(&info);
728 snd_pcm_hw_params_alloca(&hw_params);
730 #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)
733 snd_pcm_open(&h, wwo->device, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
737 EXIT_ON_ERROR( snd_pcm_info(h, info) , "pcm info" );
739 TRACE("dev=%d id=%s name=%s subdev=%d subdev_name=%s subdev_avail=%d subdev_num=%d stream=%s subclass=%s \n",
740 snd_pcm_info_get_device(info),
741 snd_pcm_info_get_id(info),
742 snd_pcm_info_get_name(info),
743 snd_pcm_info_get_subdevice(info),
744 snd_pcm_info_get_subdevice_name(info),
745 snd_pcm_info_get_subdevices_avail(info),
746 snd_pcm_info_get_subdevices_count(info),
747 snd_pcm_stream_name(snd_pcm_info_get_stream(info)),
748 (snd_pcm_info_get_subclass(info) == SND_PCM_SUBCLASS_GENERIC_MIX ? "GENERIC MIX": "MULTI MIX"));
750 strcpy(wwo->ds_desc.szDesc, snd_pcm_info_get_name(info));
751 MultiByteToWideChar(CP_ACP, 0, wwo->ds_desc.szDesc, -1, nameW, sizeof(nameW)/sizeof(WCHAR));
752 strcpyW(wwo->caps.szPname, nameW);
753 EXIT_ON_ERROR( snd_pcm_hw_params_any(h, hw_params) , "pcm hw params" );
756 err = snd_pcm_hw_params_get_rate_min(hw_params, &ratemin, &dir);
757 err = snd_pcm_hw_params_get_rate_max(hw_params, &ratemax, &dir);
758 err = snd_pcm_hw_params_get_channels_min(hw_params, &chmin);
759 err = snd_pcm_hw_params_get_channels_max(hw_params, &chmax);
761 ALSA_TraceParameters(hw_params, NULL, TRUE);
763 snd_pcm_format_mask_alloca(&fmask);
764 snd_pcm_hw_params_get_format_mask(hw_params, fmask);
767 if ( (r) >= ratemin && ( (r) <= ratemax || ratemax == -1) ) \
769 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_U8)) \
771 if (chmin <= 1 && 1 <= chmax) \
772 wwo->caps.dwFormats |= WAVE_FORMAT_##v##M08; \
773 if (chmin <= 2 && 2 <= chmax) \
774 wwo->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
776 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_S16_LE)) \
778 if (chmin <= 1 && 1 <= chmax) \
779 wwo->caps.dwFormats |= WAVE_FORMAT_##v##M16; \
780 if (chmin <= 2 && 2 <= chmax) \
781 wwo->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
793 wwo->caps.wChannels = chmax;
795 /* FIXME: always true ? */
796 wwo->caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
798 snd_pcm_access_mask_alloca(&acmask);
799 snd_pcm_hw_params_get_access_mask(hw_params, acmask);
801 /* FIXME: NONITERLEAVED and COMPLEX are not supported right now */
802 if ( snd_pcm_access_mask_test( acmask, SND_PCM_ACCESS_MMAP_INTERLEAVED ) )
803 wwo->caps.dwSupport |= WAVECAPS_DIRECTSOUND;
805 TRACE("Configured with dwFmts=%08lx dwSupport=%08lx\n",
806 wwo->caps.dwFormats, wwo->caps.dwSupport);
810 ALSA_InitializeVolumeCtl(wwo);
812 /* check for volume control support */
814 wwo->caps.dwSupport |= WAVECAPS_VOLUME;
816 if (chmin <= 2 && 2 <= chmax)
817 wwo->caps.dwSupport |= WAVECAPS_LRVOLUME;
825 for (i = 0; i < MAX_WAVEINDRV; i++)
830 snd_pcm_format_mask_t * fmask;
831 snd_pcm_access_mask_t * acmask;
833 wwi = &WInDev[ALSA_WidNumDevs];
835 regdev = ALSA_GetDeviceFromReg("CaptureDevice");
836 sprintf(device, "%s:%d", regdev, i);
837 HeapFree(GetProcessHeap(), 0, regdev);
838 wwi->device = HeapAlloc(GetProcessHeap(), 0, strlen(device));
839 strcpy(wwi->device, device);
841 TRACE("using wavein device \"%s\"\n", wwi->device);
843 snprintf(wwi->interface_name, sizeof(wwi->interface_name), "winealsa: %s", wwi->device);
845 wwi->caps.wMid = 0x0002;
846 wwi->caps.wPid = 0x0104;
847 wwi->caps.vDriverVersion = 0x0100;
848 wwi->caps.dwFormats = 0x00000000;
849 strcpy(wwi->ds_desc.szDrvname, "winealsa.drv");
852 snd_pcm_info_alloca(&info);
853 snd_pcm_hw_params_alloca(&hw_params);
855 #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)
858 snd_pcm_open(&h, wwi->device, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
862 EXIT_ON_ERROR( snd_pcm_info(h, info) , "pcm info" );
864 TRACE("dev=%d id=%s name=%s subdev=%d subdev_name=%s subdev_avail=%d subdev_num=%d stream=%s subclass=%s \n",
865 snd_pcm_info_get_device(info),
866 snd_pcm_info_get_id(info),
867 snd_pcm_info_get_name(info),
868 snd_pcm_info_get_subdevice(info),
869 snd_pcm_info_get_subdevice_name(info),
870 snd_pcm_info_get_subdevices_avail(info),
871 snd_pcm_info_get_subdevices_count(info),
872 snd_pcm_stream_name(snd_pcm_info_get_stream(info)),
873 (snd_pcm_info_get_subclass(info) == SND_PCM_SUBCLASS_GENERIC_MIX ? "GENERIC MIX": "MULTI MIX"));
875 strcpy(wwi->ds_desc.szDesc, snd_pcm_info_get_name(info));
876 MultiByteToWideChar(CP_ACP, 0, wwi->ds_desc.szDesc, -1, nameW, sizeof(nameW)/sizeof(WCHAR));
877 strcpyW(wwi->caps.szPname, nameW);
878 EXIT_ON_ERROR( snd_pcm_hw_params_any(h, hw_params) , "pcm hw params" );
880 err = snd_pcm_hw_params_get_rate_min(hw_params, &ratemin, &dir);
881 err = snd_pcm_hw_params_get_rate_max(hw_params, &ratemax, &dir);
882 err = snd_pcm_hw_params_get_channels_min(hw_params, &chmin);
883 err = snd_pcm_hw_params_get_channels_max(hw_params, &chmax);
886 ALSA_TraceParameters(hw_params, NULL, TRUE);
888 snd_pcm_format_mask_alloca(&fmask);
889 snd_pcm_hw_params_get_format_mask(hw_params, fmask);
892 if ( (r) >= ratemin && ( (r) <= ratemax || ratemax == -1) ) \
894 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_U8)) \
896 if (chmin <= 1 && 1 <= chmax) \
897 wwi->caps.dwFormats |= WAVE_FORMAT_##v##M08; \
898 if (chmin <= 2 && 2 <= chmax) \
899 wwi->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
901 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_S16_LE)) \
903 if (chmin <= 1 && 1 <= chmax) \
904 wwi->caps.dwFormats |= WAVE_FORMAT_##v##M16; \
905 if (chmin <= 2 && 2 <= chmax) \
906 wwi->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
918 wwi->caps.wChannels = chmax;
920 snd_pcm_access_mask_alloca(&acmask);
921 snd_pcm_hw_params_get_access_mask(hw_params, acmask);
923 /* FIXME: NONITERLEAVED and COMPLEX are not supported right now */
924 if ( snd_pcm_access_mask_test( acmask, SND_PCM_ACCESS_MMAP_INTERLEAVED ) ) {
926 wwi->dwSupport |= WAVECAPS_DIRECTSOUND;
930 TRACE("Configured with dwFmts=%08lx\n", wwi->caps.dwFormats);
940 /******************************************************************
941 * ALSA_InitRingMessage
943 * Initialize the ring of messages for passing between driver's caller and playback/record
946 static int ALSA_InitRingMessage(ALSA_MSG_RING* omr)
951 if (pipe(omr->msg_pipe) < 0) {
952 omr->msg_pipe[0] = -1;
953 omr->msg_pipe[1] = -1;
954 ERR("could not create pipe, error=%s\n", strerror(errno));
957 omr->msg_event = CreateEventW(NULL, FALSE, FALSE, NULL);
959 omr->ring_buffer_size = ALSA_RING_BUFFER_INCREMENT;
960 omr->messages = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,omr->ring_buffer_size * sizeof(ALSA_MSG));
962 InitializeCriticalSection(&omr->msg_crst);
966 /******************************************************************
967 * ALSA_DestroyRingMessage
970 static int ALSA_DestroyRingMessage(ALSA_MSG_RING* omr)
973 close(omr->msg_pipe[0]);
974 close(omr->msg_pipe[1]);
976 CloseHandle(omr->msg_event);
978 HeapFree(GetProcessHeap(),0,omr->messages);
979 DeleteCriticalSection(&omr->msg_crst);
983 /******************************************************************
984 * ALSA_AddRingMessage
986 * Inserts a new message into the ring (should be called from DriverProc derivated routines)
988 static int ALSA_AddRingMessage(ALSA_MSG_RING* omr, enum win_wm_message msg, DWORD param, BOOL wait)
990 HANDLE hEvent = INVALID_HANDLE_VALUE;
992 EnterCriticalSection(&omr->msg_crst);
993 if ((omr->msg_toget == ((omr->msg_tosave + 1) % omr->ring_buffer_size)))
995 int old_ring_buffer_size = omr->ring_buffer_size;
996 omr->ring_buffer_size += ALSA_RING_BUFFER_INCREMENT;
997 TRACE("omr->ring_buffer_size=%d\n",omr->ring_buffer_size);
998 omr->messages = HeapReAlloc(GetProcessHeap(),0,omr->messages, omr->ring_buffer_size * sizeof(ALSA_MSG));
999 /* Now we need to rearrange the ring buffer so that the new
1000 buffers just allocated are in between omr->msg_tosave and
1003 if (omr->msg_tosave < omr->msg_toget)
1005 memmove(&(omr->messages[omr->msg_toget + ALSA_RING_BUFFER_INCREMENT]),
1006 &(omr->messages[omr->msg_toget]),
1007 sizeof(ALSA_MSG)*(old_ring_buffer_size - omr->msg_toget)
1009 omr->msg_toget += ALSA_RING_BUFFER_INCREMENT;
1014 hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1015 if (hEvent == INVALID_HANDLE_VALUE)
1017 ERR("can't create event !?\n");
1018 LeaveCriticalSection(&omr->msg_crst);
1021 if (omr->msg_toget != omr->msg_tosave && omr->messages[omr->msg_toget].msg != WINE_WM_HEADER)
1022 FIXME("two fast messages in the queue!!!! toget = %d(%s), tosave=%d(%s)\n",
1023 omr->msg_toget,getCmdString(omr->messages[omr->msg_toget].msg),
1024 omr->msg_tosave,getCmdString(omr->messages[omr->msg_tosave].msg));
1026 /* fast messages have to be added at the start of the queue */
1027 omr->msg_toget = (omr->msg_toget + omr->ring_buffer_size - 1) % omr->ring_buffer_size;
1029 omr->messages[omr->msg_toget].msg = msg;
1030 omr->messages[omr->msg_toget].param = param;
1031 omr->messages[omr->msg_toget].hEvent = hEvent;
1035 omr->messages[omr->msg_tosave].msg = msg;
1036 omr->messages[omr->msg_tosave].param = param;
1037 omr->messages[omr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
1038 omr->msg_tosave = (omr->msg_tosave + 1) % omr->ring_buffer_size;
1040 LeaveCriticalSection(&omr->msg_crst);
1041 /* signal a new message */
1045 /* wait for playback/record thread to have processed the message */
1046 WaitForSingleObject(hEvent, INFINITE);
1047 CloseHandle(hEvent);
1052 /******************************************************************
1053 * ALSA_RetrieveRingMessage
1055 * Get a message from the ring. Should be called by the playback/record thread.
1057 static int ALSA_RetrieveRingMessage(ALSA_MSG_RING* omr,
1058 enum win_wm_message *msg, DWORD *param, HANDLE *hEvent)
1060 EnterCriticalSection(&omr->msg_crst);
1062 if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
1064 LeaveCriticalSection(&omr->msg_crst);
1068 *msg = omr->messages[omr->msg_toget].msg;
1069 omr->messages[omr->msg_toget].msg = 0;
1070 *param = omr->messages[omr->msg_toget].param;
1071 *hEvent = omr->messages[omr->msg_toget].hEvent;
1072 omr->msg_toget = (omr->msg_toget + 1) % omr->ring_buffer_size;
1074 LeaveCriticalSection(&omr->msg_crst);
1078 /******************************************************************
1079 * ALSA_PeekRingMessage
1081 * Peek at a message from the ring but do not remove it.
1082 * Should be called by the playback/record thread.
1084 static int ALSA_PeekRingMessage(ALSA_MSG_RING* omr,
1085 enum win_wm_message *msg,
1086 DWORD *param, HANDLE *hEvent)
1088 EnterCriticalSection(&omr->msg_crst);
1090 if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
1092 LeaveCriticalSection(&omr->msg_crst);
1096 *msg = omr->messages[omr->msg_toget].msg;
1097 *param = omr->messages[omr->msg_toget].param;
1098 *hEvent = omr->messages[omr->msg_toget].hEvent;
1099 LeaveCriticalSection(&omr->msg_crst);
1103 /*======================================================================*
1104 * Low level WAVE OUT implementation *
1105 *======================================================================*/
1107 /**************************************************************************
1108 * wodNotifyClient [internal]
1110 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1112 TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
1118 if (wwo->wFlags != DCB_NULL &&
1119 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags, (HDRVR)wwo->waveDesc.hWave,
1120 wMsg, wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
1121 WARN("can't notify client !\n");
1122 return MMSYSERR_ERROR;
1126 FIXME("Unknown callback message %u\n", wMsg);
1127 return MMSYSERR_INVALPARAM;
1129 return MMSYSERR_NOERROR;
1132 /**************************************************************************
1133 * wodUpdatePlayedTotal [internal]
1136 static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo, snd_pcm_status_t* ps)
1138 snd_pcm_sframes_t delay = 0;
1139 snd_pcm_delay(wwo->p_handle, &delay);
1140 if (snd_pcm_state(wwo->p_handle) != SND_PCM_STATE_RUNNING)
1142 wwo->dwPlayedTotal = wwo->dwWrittenTotal - snd_pcm_frames_to_bytes(wwo->p_handle, delay);
1146 /**************************************************************************
1147 * wodPlayer_BeginWaveHdr [internal]
1149 * Makes the specified lpWaveHdr the currently playing wave header.
1150 * If the specified wave header is a begin loop and we're not already in
1151 * a loop, setup the loop.
1153 static void wodPlayer_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1155 wwo->lpPlayPtr = lpWaveHdr;
1157 if (!lpWaveHdr) return;
1159 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
1160 if (wwo->lpLoopPtr) {
1161 WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1163 TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1164 wwo->lpLoopPtr = lpWaveHdr;
1165 /* Windows does not touch WAVEHDR.dwLoops,
1166 * so we need to make an internal copy */
1167 wwo->dwLoops = lpWaveHdr->dwLoops;
1170 wwo->dwPartialOffset = 0;
1173 /**************************************************************************
1174 * wodPlayer_PlayPtrNext [internal]
1176 * Advance the play pointer to the next waveheader, looping if required.
1178 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEOUT* wwo)
1180 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1182 wwo->dwPartialOffset = 0;
1183 if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
1184 /* We're at the end of a loop, loop if required */
1185 if (--wwo->dwLoops > 0) {
1186 wwo->lpPlayPtr = wwo->lpLoopPtr;
1188 /* Handle overlapping loops correctly */
1189 if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
1190 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
1191 /* shall we consider the END flag for the closing loop or for
1192 * the opening one or for both ???
1193 * code assumes for closing loop only
1196 lpWaveHdr = lpWaveHdr->lpNext;
1198 wwo->lpLoopPtr = NULL;
1199 wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
1202 /* We're not in a loop. Advance to the next wave header */
1203 wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
1209 /**************************************************************************
1210 * wodPlayer_DSPWait [internal]
1211 * Returns the number of milliseconds to wait for the DSP buffer to play a
1214 static DWORD wodPlayer_DSPWait(const WINE_WAVEOUT *wwo)
1216 /* time for one period to be played */
1220 err = snd_pcm_hw_params_get_period_time(wwo->hw_params, &val, &dir);
1224 /**************************************************************************
1225 * wodPlayer_NotifyWait [internal]
1226 * Returns the number of milliseconds to wait before attempting to notify
1227 * completion of the specified wavehdr.
1228 * This is based on the number of bytes remaining to be written in the
1231 static DWORD wodPlayer_NotifyWait(const WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1235 if (lpWaveHdr->reserved < wwo->dwPlayedTotal) {
1238 dwMillis = (lpWaveHdr->reserved - wwo->dwPlayedTotal) * 1000 / wwo->format.Format.nAvgBytesPerSec;
1239 if (!dwMillis) dwMillis = 1;
1246 /**************************************************************************
1247 * wodPlayer_WriteMaxFrags [internal]
1248 * Writes the maximum number of frames possible to the DSP and returns
1249 * the number of frames written.
1251 static int wodPlayer_WriteMaxFrags(WINE_WAVEOUT* wwo, DWORD* frames)
1253 /* Only attempt to write to free frames */
1254 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1255 DWORD dwLength = snd_pcm_bytes_to_frames(wwo->p_handle, lpWaveHdr->dwBufferLength - wwo->dwPartialOffset);
1256 int toWrite = min(dwLength, *frames);
1259 TRACE("Writing wavehdr %p.%lu[%lu]\n", lpWaveHdr, wwo->dwPartialOffset, lpWaveHdr->dwBufferLength);
1262 written = (wwo->write)(wwo->p_handle, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
1264 /* XRUN occurred. let's try to recover */
1265 ALSA_XRUNRecovery(wwo, written);
1266 written = (wwo->write)(wwo->p_handle, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
1269 /* still in error */
1270 ERR("Error in writing wavehdr. Reason: %s\n", snd_strerror(written));
1276 wwo->dwPartialOffset += snd_pcm_frames_to_bytes(wwo->p_handle, written);
1277 if ( wwo->dwPartialOffset >= lpWaveHdr->dwBufferLength) {
1278 /* this will be used to check if the given wave header has been fully played or not... */
1279 wwo->dwPartialOffset = lpWaveHdr->dwBufferLength;
1280 /* If we wrote all current wavehdr, skip to the next one */
1281 wodPlayer_PlayPtrNext(wwo);
1284 wwo->dwWrittenTotal += snd_pcm_frames_to_bytes(wwo->p_handle, written);
1285 TRACE("dwWrittenTotal=%lu\n", wwo->dwWrittenTotal);
1291 /**************************************************************************
1292 * wodPlayer_NotifyCompletions [internal]
1294 * Notifies and remove from queue all wavehdrs which have been played to
1295 * the speaker (ie. they have cleared the ALSA buffer). If force is true,
1296 * we notify all wavehdrs and remove them all from the queue even if they
1297 * are unplayed or part of a loop.
1299 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1301 LPWAVEHDR lpWaveHdr;
1303 /* Start from lpQueuePtr and keep notifying until:
1304 * - we hit an unwritten wavehdr
1305 * - we hit the beginning of a running loop
1306 * - we hit a wavehdr which hasn't finished playing
1309 while ((lpWaveHdr = wwo->lpQueuePtr) &&
1311 (lpWaveHdr != wwo->lpPlayPtr &&
1312 lpWaveHdr != wwo->lpLoopPtr &&
1313 lpWaveHdr->reserved <= wwo->dwPlayedTotal))) {
1315 wwo->lpQueuePtr = lpWaveHdr->lpNext;
1317 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1318 lpWaveHdr->dwFlags |= WHDR_DONE;
1320 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1325 lpWaveHdr = wwo->lpQueuePtr;
1326 if (!lpWaveHdr) {TRACE("Empty queue\n"); break;}
1329 if (lpWaveHdr == wwo->lpPlayPtr) {TRACE("play %p\n", lpWaveHdr); break;}
1330 if (lpWaveHdr == wwo->lpLoopPtr) {TRACE("loop %p\n", lpWaveHdr); break;}
1331 if (lpWaveHdr->reserved > wwo->dwPlayedTotal){TRACE("still playing %p (%lu/%lu)\n", lpWaveHdr, lpWaveHdr->reserved, wwo->dwPlayedTotal);break;}
1333 wwo->lpQueuePtr = lpWaveHdr->lpNext;
1335 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1336 lpWaveHdr->dwFlags |= WHDR_DONE;
1338 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1341 return (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
1342 wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
1346 static void wait_for_poll(snd_pcm_t *handle, struct pollfd *ufds, unsigned int count)
1348 unsigned short revents;
1350 if (snd_pcm_state(handle) != SND_PCM_STATE_RUNNING)
1354 poll(ufds, count, -1);
1355 snd_pcm_poll_descriptors_revents(handle, ufds, count, &revents);
1357 if (revents & POLLERR)
1360 /*if (revents & POLLOUT)
1366 /**************************************************************************
1367 * wodPlayer_Reset [internal]
1369 * wodPlayer helper. Resets current output stream.
1371 static void wodPlayer_Reset(WINE_WAVEOUT* wwo)
1373 enum win_wm_message msg;
1378 /* flush all possible output */
1379 wait_for_poll(wwo->p_handle, wwo->ufds, wwo->count);
1381 wodUpdatePlayedTotal(wwo, NULL);
1382 /* updates current notify list */
1383 wodPlayer_NotifyCompletions(wwo, FALSE);
1385 if ( (err = snd_pcm_drop(wwo->p_handle)) < 0) {
1386 FIXME("flush: %s\n", snd_strerror(err));
1388 wwo->state = WINE_WS_STOPPED;
1391 if ( (err = snd_pcm_prepare(wwo->p_handle)) < 0 )
1392 ERR("pcm prepare failed: %s\n", snd_strerror(err));
1394 /* remove any buffer */
1395 wodPlayer_NotifyCompletions(wwo, TRUE);
1397 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1398 wwo->state = WINE_WS_STOPPED;
1399 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1400 /* Clear partial wavehdr */
1401 wwo->dwPartialOffset = 0;
1403 /* remove any existing message in the ring */
1404 EnterCriticalSection(&wwo->msgRing.msg_crst);
1405 /* return all pending headers in queue */
1406 while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, ¶m, &ev))
1408 if (msg != WINE_WM_HEADER)
1410 FIXME("shouldn't have headers left\n");
1414 ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
1415 ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
1417 wodNotifyClient(wwo, WOM_DONE, param, 0);
1419 RESET_OMR(&wwo->msgRing);
1420 LeaveCriticalSection(&wwo->msgRing.msg_crst);
1423 /**************************************************************************
1424 * wodPlayer_ProcessMessages [internal]
1426 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
1428 LPWAVEHDR lpWaveHdr;
1429 enum win_wm_message msg;
1434 while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, ¶m, &ev)) {
1435 TRACE("Received %s %lx\n", getCmdString(msg), param);
1438 case WINE_WM_PAUSING:
1439 if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_RUNNING )
1441 err = snd_pcm_pause(wwo->p_handle, 1);
1443 ERR("pcm_pause failed: %s\n", snd_strerror(err));
1445 wwo->state = WINE_WS_PAUSED;
1448 case WINE_WM_RESTARTING:
1449 if (wwo->state == WINE_WS_PAUSED)
1451 if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_PAUSED )
1453 err = snd_pcm_pause(wwo->p_handle, 0);
1455 ERR("pcm_pause failed: %s\n", snd_strerror(err));
1457 wwo->state = WINE_WS_PLAYING;
1461 case WINE_WM_HEADER:
1462 lpWaveHdr = (LPWAVEHDR)param;
1464 /* insert buffer at the end of queue */
1467 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1470 if (!wwo->lpPlayPtr)
1471 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
1472 if (wwo->state == WINE_WS_STOPPED)
1473 wwo->state = WINE_WS_PLAYING;
1475 case WINE_WM_RESETTING:
1476 wodPlayer_Reset(wwo);
1479 case WINE_WM_UPDATE:
1480 wodUpdatePlayedTotal(wwo, NULL);
1483 case WINE_WM_BREAKLOOP:
1484 if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
1485 /* ensure exit at end of current loop */
1490 case WINE_WM_CLOSING:
1491 /* sanity check: this should not happen since the device must have been reset before */
1492 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1494 wwo->state = WINE_WS_CLOSED;
1497 /* shouldn't go here */
1499 FIXME("unknown message %d\n", msg);
1505 /**************************************************************************
1506 * wodPlayer_FeedDSP [internal]
1507 * Feed as much sound data as we can into the DSP and return the number of
1508 * milliseconds before it will be necessary to feed the DSP again.
1510 static DWORD wodPlayer_FeedDSP(WINE_WAVEOUT* wwo)
1514 wodUpdatePlayedTotal(wwo, NULL);
1515 availInQ = snd_pcm_avail_update(wwo->p_handle);
1518 /* input queue empty and output buffer with less than one fragment to play */
1519 if (!wwo->lpPlayPtr && wwo->dwBufferSize < availInQ + wwo->dwFragmentSize) {
1520 TRACE("Run out of wavehdr:s...\n");
1525 /* no more room... no need to try to feed */
1527 /* Feed from partial wavehdr */
1528 if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0) {
1529 wodPlayer_WriteMaxFrags(wwo, &availInQ);
1532 /* Feed wavehdrs until we run out of wavehdrs or DSP space */
1533 if (wwo->dwPartialOffset == 0 && wwo->lpPlayPtr) {
1535 TRACE("Setting time to elapse for %p to %lu\n",
1536 wwo->lpPlayPtr, wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength);
1537 /* note the value that dwPlayedTotal will return when this wave finishes playing */
1538 wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
1539 } while (wodPlayer_WriteMaxFrags(wwo, &availInQ) && wwo->lpPlayPtr && availInQ > 0);
1543 return wodPlayer_DSPWait(wwo);
1546 /**************************************************************************
1547 * wodPlayer [internal]
1549 static DWORD CALLBACK wodPlayer(LPVOID pmt)
1551 WORD uDevID = (DWORD)pmt;
1552 WINE_WAVEOUT* wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
1553 DWORD dwNextFeedTime = INFINITE; /* Time before DSP needs feeding */
1554 DWORD dwNextNotifyTime = INFINITE; /* Time before next wave completion */
1557 wwo->state = WINE_WS_STOPPED;
1558 SetEvent(wwo->hStartUpEvent);
1561 /** Wait for the shortest time before an action is required. If there
1562 * are no pending actions, wait forever for a command.
1564 dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
1565 TRACE("waiting %lums (%lu,%lu)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
1566 WAIT_OMR(&wwo->msgRing, dwSleepTime);
1567 wodPlayer_ProcessMessages(wwo);
1568 if (wwo->state == WINE_WS_PLAYING) {
1569 dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1570 dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1571 if (dwNextFeedTime == INFINITE) {
1572 /* FeedDSP ran out of data, but before giving up, */
1573 /* check that a notification didn't give us more */
1574 wodPlayer_ProcessMessages(wwo);
1575 if (wwo->lpPlayPtr) {
1576 TRACE("recovering\n");
1577 dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1581 dwNextFeedTime = dwNextNotifyTime = INFINITE;
1586 /**************************************************************************
1587 * wodGetDevCaps [internal]
1589 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
1591 TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1593 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1595 if (wDevID >= MAX_WAVEOUTDRV) {
1596 TRACE("MAX_WAVOUTDRV reached !\n");
1597 return MMSYSERR_BADDEVICEID;
1600 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1601 return MMSYSERR_NOERROR;
1604 /**************************************************************************
1605 * wodOpen [internal]
1607 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1610 snd_pcm_hw_params_t * hw_params;
1611 snd_pcm_sw_params_t * sw_params;
1612 snd_pcm_access_t access;
1613 snd_pcm_format_t format = -1;
1615 unsigned int buffer_time = 500000;
1616 unsigned int period_time = 10000;
1617 snd_pcm_uframes_t buffer_size;
1618 snd_pcm_uframes_t period_size;
1624 snd_pcm_hw_params_alloca(&hw_params);
1625 snd_pcm_sw_params_alloca(&sw_params);
1627 TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
1628 if (lpDesc == NULL) {
1629 WARN("Invalid Parameter !\n");
1630 return MMSYSERR_INVALPARAM;
1632 if (wDevID >= MAX_WAVEOUTDRV) {
1633 TRACE("MAX_WAVOUTDRV reached !\n");
1634 return MMSYSERR_BADDEVICEID;
1637 /* only PCM format is supported so far... */
1638 if (!supportedFormat(lpDesc->lpFormat)) {
1639 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1640 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1641 lpDesc->lpFormat->nSamplesPerSec);
1642 return WAVERR_BADFORMAT;
1645 if (dwFlags & WAVE_FORMAT_QUERY) {
1646 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1647 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1648 lpDesc->lpFormat->nSamplesPerSec);
1649 return MMSYSERR_NOERROR;
1652 wwo = &WOutDev[wDevID];
1654 if ((dwFlags & WAVE_DIRECTSOUND) && !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
1655 /* not supported, ignore it */
1656 dwFlags &= ~WAVE_DIRECTSOUND;
1659 flags = SND_PCM_NONBLOCK;
1661 if ( dwFlags & WAVE_DIRECTSOUND )
1662 flags |= SND_PCM_ASYNC;
1665 if ( (err = snd_pcm_open(&pcm, wwo->device, SND_PCM_STREAM_PLAYBACK, flags)) < 0)
1667 ERR("Error open: %s\n", snd_strerror(err));
1668 return MMSYSERR_NOTENABLED;
1671 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1673 memcpy(&wwo->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
1674 copy_format(lpDesc->lpFormat, &wwo->format);
1676 if (wwo->format.Format.wBitsPerSample == 0) {
1677 WARN("Resetting zeroed wBitsPerSample\n");
1678 wwo->format.Format.wBitsPerSample = 8 *
1679 (wwo->format.Format.nAvgBytesPerSec /
1680 wwo->format.Format.nSamplesPerSec) /
1681 wwo->format.Format.nChannels;
1684 snd_pcm_hw_params_any(pcm, hw_params);
1686 #define EXIT_ON_ERROR(f,e,txt) do \
1689 if ( (err = (f) ) < 0) \
1691 ERR(txt ": %s\n", snd_strerror(err)); \
1692 snd_pcm_close(pcm); \
1697 access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
1698 if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
1699 WARN("mmap not available. switching to standard write.\n");
1700 access = SND_PCM_ACCESS_RW_INTERLEAVED;
1701 EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
1702 wwo->write = snd_pcm_writei;
1705 wwo->write = snd_pcm_mmap_writei;
1707 EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwo->format.Format.nChannels), MMSYSERR_INVALPARAM, "unable to set required channels");
1709 if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
1710 ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
1711 IsEqualGUID(&wwo->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
1712 format = (wwo->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
1713 (wwo->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
1714 (wwo->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
1715 (wwo->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
1716 } else if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
1717 IsEqualGUID(&wwo->format.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)){
1718 format = (wwo->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_FLOAT_LE : -1;
1719 } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
1720 FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
1722 return WAVERR_BADFORMAT;
1723 } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
1724 FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
1726 return WAVERR_BADFORMAT;
1727 } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
1728 FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
1730 return WAVERR_BADFORMAT;
1732 ERR("invalid format: %0x04x\n", wwo->format.Format.wFormatTag);
1734 return WAVERR_BADFORMAT;
1737 EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), MMSYSERR_INVALPARAM, "unable to set required format");
1739 rate = wwo->format.Format.nSamplesPerSec;
1741 err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
1743 ERR("Rate %ld Hz not available for playback: %s\n", wwo->format.Format.nSamplesPerSec, snd_strerror(rate));
1745 return WAVERR_BADFORMAT;
1747 if (rate != wwo->format.Format.nSamplesPerSec) {
1748 ERR("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwo->format.Format.nSamplesPerSec, rate);
1750 return WAVERR_BADFORMAT;
1753 EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
1755 EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
1757 EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
1759 err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
1760 err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
1762 snd_pcm_sw_params_current(pcm, sw_params);
1763 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");
1764 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
1765 EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
1766 EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
1767 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
1768 EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
1769 #undef EXIT_ON_ERROR
1771 snd_pcm_prepare(pcm);
1774 ALSA_TraceParameters(hw_params, sw_params, FALSE);
1776 /* now, we can save all required data for later use... */
1777 if ( wwo->hw_params )
1778 snd_pcm_hw_params_free(wwo->hw_params);
1779 snd_pcm_hw_params_malloc(&(wwo->hw_params));
1780 snd_pcm_hw_params_copy(wwo->hw_params, hw_params);
1782 wwo->dwBufferSize = buffer_size;
1783 wwo->lpQueuePtr = wwo->lpPlayPtr = wwo->lpLoopPtr = NULL;
1784 wwo->p_handle = pcm;
1785 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1786 wwo->dwPartialOffset = 0;
1788 ALSA_InitRingMessage(&wwo->msgRing);
1790 wwo->count = snd_pcm_poll_descriptors_count (wwo->p_handle);
1791 if (wwo->count <= 0) {
1792 ERR("Invalid poll descriptors count\n");
1793 return MMSYSERR_ERROR;
1796 wwo->ufds = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct pollfd) * wwo->count);
1797 if (wwo->ufds == NULL) {
1798 ERR("No enough memory\n");
1799 return MMSYSERR_NOMEM;
1801 if ((err = snd_pcm_poll_descriptors(wwo->p_handle, wwo->ufds, wwo->count)) < 0) {
1802 ERR("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
1803 return MMSYSERR_ERROR;
1806 if (!(dwFlags & WAVE_DIRECTSOUND)) {
1807 wwo->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1808 wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
1809 WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
1810 CloseHandle(wwo->hStartUpEvent);
1812 wwo->hThread = INVALID_HANDLE_VALUE;
1813 wwo->dwThreadID = 0;
1815 wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
1817 TRACE("handle=%08lx \n", (DWORD)wwo->p_handle);
1818 /* if (wwo->dwFragmentSize % wwo->format.Format.nBlockAlign)
1819 ERR("Fragment doesn't contain an integral number of data blocks\n");
1821 TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
1822 wwo->format.Format.wBitsPerSample, wwo->format.Format.nAvgBytesPerSec,
1823 wwo->format.Format.nSamplesPerSec, wwo->format.Format.nChannels,
1824 wwo->format.Format.nBlockAlign);
1826 return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
1830 /**************************************************************************
1831 * wodClose [internal]
1833 static DWORD wodClose(WORD wDevID)
1835 DWORD ret = MMSYSERR_NOERROR;
1838 TRACE("(%u);\n", wDevID);
1840 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1841 WARN("bad device ID !\n");
1842 return MMSYSERR_BADDEVICEID;
1845 wwo = &WOutDev[wDevID];
1846 if (wwo->lpQueuePtr) {
1847 WARN("buffers still playing !\n");
1848 ret = WAVERR_STILLPLAYING;
1850 if (wwo->hThread != INVALID_HANDLE_VALUE) {
1851 ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1853 ALSA_DestroyRingMessage(&wwo->msgRing);
1855 snd_pcm_hw_params_free(wwo->hw_params);
1856 wwo->hw_params = NULL;
1858 snd_pcm_close(wwo->p_handle);
1859 wwo->p_handle = NULL;
1861 ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1864 HeapFree(GetProcessHeap(), 0, wwo->ufds);
1869 /**************************************************************************
1870 * wodWrite [internal]
1873 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1875 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1877 /* first, do the sanity checks... */
1878 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1879 WARN("bad dev ID !\n");
1880 return MMSYSERR_BADDEVICEID;
1883 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1884 return WAVERR_UNPREPARED;
1886 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1887 return WAVERR_STILLPLAYING;
1889 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1890 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1891 lpWaveHdr->lpNext = 0;
1893 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1895 return MMSYSERR_NOERROR;
1898 /**************************************************************************
1899 * wodPause [internal]
1901 static DWORD wodPause(WORD wDevID)
1903 TRACE("(%u);!\n", wDevID);
1905 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1906 WARN("bad device ID !\n");
1907 return MMSYSERR_BADDEVICEID;
1910 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1912 return MMSYSERR_NOERROR;
1915 /**************************************************************************
1916 * wodRestart [internal]
1918 static DWORD wodRestart(WORD wDevID)
1920 TRACE("(%u);\n", wDevID);
1922 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1923 WARN("bad device ID !\n");
1924 return MMSYSERR_BADDEVICEID;
1927 if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1928 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1931 /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1932 /* FIXME: Myst crashes with this ... hmm -MM
1933 return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1936 return MMSYSERR_NOERROR;
1939 /**************************************************************************
1940 * wodReset [internal]
1942 static DWORD wodReset(WORD wDevID)
1944 TRACE("(%u);\n", wDevID);
1946 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1947 WARN("bad device ID !\n");
1948 return MMSYSERR_BADDEVICEID;
1951 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1953 return MMSYSERR_NOERROR;
1956 /**************************************************************************
1957 * wodGetPosition [internal]
1959 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1963 TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1965 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1966 WARN("bad device ID !\n");
1967 return MMSYSERR_BADDEVICEID;
1970 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1972 wwo = &WOutDev[wDevID];
1973 ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1975 return bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->format);
1978 /**************************************************************************
1979 * wodBreakLoop [internal]
1981 static DWORD wodBreakLoop(WORD wDevID)
1983 TRACE("(%u);\n", wDevID);
1985 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1986 WARN("bad device ID !\n");
1987 return MMSYSERR_BADDEVICEID;
1989 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
1990 return MMSYSERR_NOERROR;
1993 /**************************************************************************
1994 * wodGetVolume [internal]
1996 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
2003 TRACE("(%u, %p);\n", wDevID, lpdwVol);
2004 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
2005 WARN("bad device ID !\n");
2006 return MMSYSERR_BADDEVICEID;
2009 if (lpdwVol == NULL)
2010 return MMSYSERR_NOTENABLED;
2012 wwo = &WOutDev[wDevID];
2015 return MMSYSERR_NOTSUPPORTED;
2017 count = snd_ctl_elem_info_get_count(wwo->playback_einfo);
2018 min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
2019 max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
2021 #define VOLUME_ALSA_TO_WIN(x) (((x)-min) * 65536 /(max-min))
2026 left = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
2027 right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 1));
2030 left = right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
2033 WARN("%d channels mixer not supported\n", count);
2034 return MMSYSERR_NOERROR;
2036 #undef VOLUME_ALSA_TO_WIN
2038 TRACE("left=%d right=%d !\n", left, right);
2039 *lpdwVol = MAKELONG( left, right );
2040 return MMSYSERR_NOERROR;
2043 /**************************************************************************
2044 * wodSetVolume [internal]
2046 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
2053 TRACE("(%u, %08lX);\n", wDevID, dwParam);
2054 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
2055 WARN("bad device ID !\n");
2056 return MMSYSERR_BADDEVICEID;
2058 wwo = &WOutDev[wDevID];
2060 return MMSYSERR_NOTSUPPORTED;
2062 count=snd_ctl_elem_info_get_count(wwo->playback_einfo);
2063 min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
2064 max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
2066 left = LOWORD(dwParam);
2067 right = HIWORD(dwParam);
2069 #define VOLUME_WIN_TO_ALSA(x) ( (((x) * (max-min)) / 65536) + min )
2073 snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
2074 snd_ctl_elem_value_set_integer(wwo->playback_evalue, 1, VOLUME_WIN_TO_ALSA(right));
2077 snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
2080 WARN("%d channels mixer not supported\n", count);
2082 #undef VOLUME_WIN_TO_ALSA
2083 if ( (err = snd_ctl_elem_write(wwo->ctl, wwo->playback_evalue)) < 0)
2085 ERR("error writing snd_ctl_elem_value: %s\n", snd_strerror(err));
2087 return MMSYSERR_NOERROR;
2090 /**************************************************************************
2091 * wodGetNumDevs [internal]
2093 static DWORD wodGetNumDevs(void)
2095 return ALSA_WodNumDevs;
2098 /**************************************************************************
2099 * wodDevInterfaceSize [internal]
2101 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2103 TRACE("(%u, %p)\n", wDevID, dwParam1);
2105 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2106 NULL, 0 ) * sizeof(WCHAR);
2107 return MMSYSERR_NOERROR;
2110 /**************************************************************************
2111 * wodDevInterface [internal]
2113 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2115 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2116 NULL, 0 ) * sizeof(WCHAR))
2118 MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2119 dwParam1, dwParam2 / sizeof(WCHAR));
2120 return MMSYSERR_NOERROR;
2122 return MMSYSERR_INVALPARAM;
2125 /**************************************************************************
2126 * wodMessage (WINEALSA.@)
2128 DWORD WINAPI ALSA_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
2129 DWORD dwParam1, DWORD dwParam2)
2131 TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
2132 wDevID, wMsg, dwUser, dwParam1, dwParam2);
2139 /* FIXME: Pretend this is supported */
2141 case WODM_OPEN: return wodOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2142 case WODM_CLOSE: return wodClose (wDevID);
2143 case WODM_GETDEVCAPS: return wodGetDevCaps (wDevID, (LPWAVEOUTCAPSW)dwParam1, dwParam2);
2144 case WODM_GETNUMDEVS: return wodGetNumDevs ();
2145 case WODM_GETPITCH: return MMSYSERR_NOTSUPPORTED;
2146 case WODM_SETPITCH: return MMSYSERR_NOTSUPPORTED;
2147 case WODM_GETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
2148 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
2149 case WODM_WRITE: return wodWrite (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2150 case WODM_PAUSE: return wodPause (wDevID);
2151 case WODM_GETPOS: return wodGetPosition (wDevID, (LPMMTIME)dwParam1, dwParam2);
2152 case WODM_BREAKLOOP: return wodBreakLoop (wDevID);
2153 case WODM_PREPARE: return MMSYSERR_NOTSUPPORTED;
2154 case WODM_UNPREPARE: return MMSYSERR_NOTSUPPORTED;
2155 case WODM_GETVOLUME: return wodGetVolume (wDevID, (LPDWORD)dwParam1);
2156 case WODM_SETVOLUME: return wodSetVolume (wDevID, dwParam1);
2157 case WODM_RESTART: return wodRestart (wDevID);
2158 case WODM_RESET: return wodReset (wDevID);
2159 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2160 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2161 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
2162 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
2165 FIXME("unknown message %d!\n", wMsg);
2167 return MMSYSERR_NOTSUPPORTED;
2170 /*======================================================================*
2171 * Low level DSOUND implementation *
2172 *======================================================================*/
2174 typedef struct IDsDriverImpl IDsDriverImpl;
2175 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
2177 struct IDsDriverImpl
2179 /* IUnknown fields */
2180 IDsDriverVtbl *lpVtbl;
2182 /* IDsDriverImpl fields */
2184 IDsDriverBufferImpl*primary;
2187 struct IDsDriverBufferImpl
2189 /* IUnknown fields */
2190 IDsDriverBufferVtbl *lpVtbl;
2192 /* IDsDriverBufferImpl fields */
2195 CRITICAL_SECTION mmap_crst;
2197 DWORD mmap_buflen_bytes;
2198 snd_pcm_uframes_t mmap_buflen_frames;
2199 snd_pcm_channel_area_t * mmap_areas;
2200 snd_async_handler_t * mmap_async_handler;
2203 static void DSDB_CheckXRUN(IDsDriverBufferImpl* pdbi)
2205 WINE_WAVEOUT * wwo = &(WOutDev[pdbi->drv->wDevID]);
2206 snd_pcm_state_t state = snd_pcm_state(wwo->p_handle);
2208 if ( state == SND_PCM_STATE_XRUN )
2210 int err = snd_pcm_prepare(wwo->p_handle);
2211 TRACE("xrun occurred\n");
2213 ERR("recovery from xrun failed, prepare failed: %s\n", snd_strerror(err));
2215 else if ( state == SND_PCM_STATE_SUSPENDED )
2217 int err = snd_pcm_resume(wwo->p_handle);
2218 TRACE("recovery from suspension occurred\n");
2219 if (err < 0 && err != -EAGAIN){
2220 err = snd_pcm_prepare(wwo->p_handle);
2222 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
2227 static void DSDB_MMAPCopy(IDsDriverBufferImpl* pdbi)
2229 WINE_WAVEOUT * wwo = &(WOutDev[pdbi->drv->wDevID]);
2230 unsigned int channels;
2231 snd_pcm_format_t format;
2232 snd_pcm_uframes_t period_size;
2233 snd_pcm_sframes_t avail;
2237 if ( !pdbi->mmap_buffer || !wwo->hw_params || !wwo->p_handle)
2240 err = snd_pcm_hw_params_get_channels(wwo->hw_params, &channels);
2241 err = snd_pcm_hw_params_get_format(wwo->hw_params, &format);
2243 err = snd_pcm_hw_params_get_period_size(wwo->hw_params, &period_size, &dir);
2244 avail = snd_pcm_avail_update(wwo->p_handle);
2246 DSDB_CheckXRUN(pdbi);
2248 TRACE("avail=%d format=%s channels=%d\n", (int)avail, snd_pcm_format_name(format), channels );
2250 while (avail >= period_size)
2252 const snd_pcm_channel_area_t *areas;
2253 snd_pcm_uframes_t ofs;
2254 snd_pcm_uframes_t frames;
2257 frames = avail / period_size * period_size; /* round down to a multiple of period_size */
2259 EnterCriticalSection(&pdbi->mmap_crst);
2261 snd_pcm_mmap_begin(wwo->p_handle, &areas, &ofs, &frames);
2262 snd_pcm_areas_copy(areas, ofs, pdbi->mmap_areas, ofs, channels, frames, format);
2263 err = snd_pcm_mmap_commit(wwo->p_handle, ofs, frames);
2265 LeaveCriticalSection(&pdbi->mmap_crst);
2267 if ( err != (snd_pcm_sframes_t) frames)
2268 ERR("mmap partially failed.\n");
2270 avail = snd_pcm_avail_update(wwo->p_handle);
2274 static void DSDB_PCMCallback(snd_async_handler_t *ahandler)
2276 /* snd_pcm_t * handle = snd_async_handler_get_pcm(ahandler); */
2277 IDsDriverBufferImpl* pdbi = snd_async_handler_get_callback_private(ahandler);
2278 TRACE("callback called\n");
2279 DSDB_MMAPCopy(pdbi);
2282 static int DSDB_CreateMMAP(IDsDriverBufferImpl* pdbi)
2284 WINE_WAVEOUT * wwo = &(WOutDev[pdbi->drv->wDevID]);
2285 snd_pcm_format_t format;
2286 snd_pcm_uframes_t frames;
2287 unsigned int channels;
2288 unsigned int bits_per_sample;
2289 unsigned int bits_per_frame;
2290 snd_pcm_channel_area_t * a;
2294 err = snd_pcm_hw_params_get_format(wwo->hw_params, &format);
2295 err = snd_pcm_hw_params_get_buffer_size(wwo->hw_params, &frames);
2296 err = snd_pcm_hw_params_get_channels(wwo->hw_params, &channels);
2297 bits_per_sample = snd_pcm_format_physical_width(format);
2298 bits_per_frame = bits_per_sample * channels;
2302 ALSA_TraceParameters(wwo->hw_params, NULL, FALSE);
2304 TRACE("format=%s frames=%ld channels=%d bits_per_sample=%d bits_per_frame=%d\n",
2305 snd_pcm_format_name(format), frames, channels, bits_per_sample, bits_per_frame);
2307 pdbi->mmap_buflen_frames = frames;
2308 pdbi->mmap_buflen_bytes = snd_pcm_frames_to_bytes( wwo->p_handle, frames );
2309 pdbi->mmap_buffer = HeapAlloc(GetProcessHeap(),0,pdbi->mmap_buflen_bytes);
2310 if (!pdbi->mmap_buffer)
2311 return DSERR_OUTOFMEMORY;
2313 snd_pcm_format_set_silence(format, pdbi->mmap_buffer, frames );
2315 TRACE("created mmap buffer of %ld frames (%ld bytes) at %p\n",
2316 frames, pdbi->mmap_buflen_bytes, pdbi->mmap_buffer);
2318 pdbi->mmap_areas = HeapAlloc(GetProcessHeap(),0,channels*sizeof(snd_pcm_channel_area_t));
2319 if (!pdbi->mmap_areas)
2320 return DSERR_OUTOFMEMORY;
2322 a = pdbi->mmap_areas;
2323 for (c = 0; c < channels; c++, a++)
2325 a->addr = pdbi->mmap_buffer;
2326 a->first = bits_per_sample * c;
2327 a->step = bits_per_frame;
2328 TRACE("Area %d: addr=%p first=%d step=%d\n", c, a->addr, a->first, a->step);
2331 InitializeCriticalSection(&pdbi->mmap_crst);
2333 err = snd_async_add_pcm_handler(&pdbi->mmap_async_handler, wwo->p_handle, DSDB_PCMCallback, pdbi);
2336 ERR("add_pcm_handler failed. reason: %s\n", snd_strerror(err));
2337 return DSERR_GENERIC;
2343 static void DSDB_DestroyMMAP(IDsDriverBufferImpl* pdbi)
2345 TRACE("mmap buffer %p destroyed\n", pdbi->mmap_buffer);
2346 HeapFree(GetProcessHeap(), 0, pdbi->mmap_areas);
2347 HeapFree(GetProcessHeap(), 0, pdbi->mmap_buffer);
2348 pdbi->mmap_areas = NULL;
2349 pdbi->mmap_buffer = NULL;
2350 DeleteCriticalSection(&pdbi->mmap_crst);
2354 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
2356 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2357 FIXME("(): stub!\n");
2358 return DSERR_UNSUPPORTED;
2361 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
2363 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2364 ULONG refCount = InterlockedIncrement(&This->ref);
2366 TRACE("(%p)->(ref before=%lu)\n",This, refCount - 1);
2371 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
2373 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2374 ULONG refCount = InterlockedDecrement(&This->ref);
2376 TRACE("(%p)->(ref before=%lu)\n",This, refCount + 1);
2380 if (This == This->drv->primary)
2381 This->drv->primary = NULL;
2382 DSDB_DestroyMMAP(This);
2383 HeapFree(GetProcessHeap(), 0, This);
2387 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
2388 LPVOID*ppvAudio1,LPDWORD pdwLen1,
2389 LPVOID*ppvAudio2,LPDWORD pdwLen2,
2390 DWORD dwWritePosition,DWORD dwWriteLen,
2393 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2394 TRACE("(%p)\n",iface);
2395 return DSERR_UNSUPPORTED;
2398 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
2399 LPVOID pvAudio1,DWORD dwLen1,
2400 LPVOID pvAudio2,DWORD dwLen2)
2402 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2403 TRACE("(%p)\n",iface);
2404 return DSERR_UNSUPPORTED;
2407 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
2408 LPWAVEFORMATEX pwfx)
2410 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2411 TRACE("(%p,%p)\n",iface,pwfx);
2412 return DSERR_BUFFERLOST;
2415 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
2417 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2418 TRACE("(%p,%ld): stub\n",iface,dwFreq);
2419 return DSERR_UNSUPPORTED;
2422 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
2425 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2426 TRACE("(%p,%p)\n",iface,pVolPan);
2427 vol = pVolPan->dwTotalLeftAmpFactor | (pVolPan->dwTotalRightAmpFactor << 16);
2429 if (wodSetVolume(This->drv->wDevID, vol) != MMSYSERR_NOERROR) {
2430 WARN("wodSetVolume failed\n");
2431 return DSERR_INVALIDPARAM;
2437 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
2439 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2440 TRACE("(%p,%ld): stub\n",iface,dwNewPos);
2441 return DSERR_UNSUPPORTED;
2444 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
2445 LPDWORD lpdwPlay, LPDWORD lpdwWrite)
2447 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2448 WINE_WAVEOUT * wwo = &(WOutDev[This->drv->wDevID]);
2449 snd_pcm_uframes_t hw_ptr;
2450 snd_pcm_uframes_t period_size;
2454 if (wwo->hw_params == NULL) return DSERR_GENERIC;
2457 err = snd_pcm_hw_params_get_period_size(wwo->hw_params, &period_size, &dir);
2459 if (wwo->p_handle == NULL) return DSERR_GENERIC;
2460 /** we need to track down buffer underruns */
2461 DSDB_CheckXRUN(This);
2463 EnterCriticalSection(&This->mmap_crst);
2464 /* FIXME: snd_pcm_mmap_hw_ptr() should not be accessed by a user app. */
2465 /* It will NOT return what why want anyway. */
2466 hw_ptr = _snd_pcm_mmap_hw_ptr(wwo->p_handle);
2468 *lpdwPlay = snd_pcm_frames_to_bytes(wwo->p_handle, hw_ptr/ period_size * period_size) % This->mmap_buflen_bytes;
2470 *lpdwWrite = snd_pcm_frames_to_bytes(wwo->p_handle, (hw_ptr / period_size + 1) * period_size ) % This->mmap_buflen_bytes;
2471 LeaveCriticalSection(&This->mmap_crst);
2473 TRACE("hw_ptr=0x%08x, playpos=%ld, writepos=%ld\n", (unsigned int)hw_ptr, lpdwPlay?*lpdwPlay:-1, lpdwWrite?*lpdwWrite:-1);
2477 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
2479 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2480 WINE_WAVEOUT * wwo = &(WOutDev[This->drv->wDevID]);
2481 snd_pcm_state_t state;
2484 TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
2486 if (wwo->p_handle == NULL) return DSERR_GENERIC;
2488 state = snd_pcm_state(wwo->p_handle);
2489 if ( state == SND_PCM_STATE_SETUP )
2491 err = snd_pcm_prepare(wwo->p_handle);
2492 state = snd_pcm_state(wwo->p_handle);
2494 if ( state == SND_PCM_STATE_PREPARED )
2496 DSDB_MMAPCopy(This);
2497 err = snd_pcm_start(wwo->p_handle);
2502 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
2504 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2505 WINE_WAVEOUT * wwo = &(WOutDev[This->drv->wDevID]);
2510 TRACE("(%p)\n",iface);
2512 if (wwo->p_handle == NULL) return DSERR_GENERIC;
2514 /* ring buffer wrap up detection */
2515 IDsDriverBufferImpl_GetPosition(iface, &play, &write);
2518 TRACE("writepos wrapper up\n");
2522 if ( ( err = snd_pcm_drop(wwo->p_handle)) < 0 )
2524 ERR("error while stopping pcm: %s\n", snd_strerror(err));
2525 return DSERR_GENERIC;
2530 static IDsDriverBufferVtbl dsdbvt =
2532 IDsDriverBufferImpl_QueryInterface,
2533 IDsDriverBufferImpl_AddRef,
2534 IDsDriverBufferImpl_Release,
2535 IDsDriverBufferImpl_Lock,
2536 IDsDriverBufferImpl_Unlock,
2537 IDsDriverBufferImpl_SetFormat,
2538 IDsDriverBufferImpl_SetFrequency,
2539 IDsDriverBufferImpl_SetVolumePan,
2540 IDsDriverBufferImpl_SetPosition,
2541 IDsDriverBufferImpl_GetPosition,
2542 IDsDriverBufferImpl_Play,
2543 IDsDriverBufferImpl_Stop
2546 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
2548 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2549 FIXME("(%p): stub!\n",iface);
2550 return DSERR_UNSUPPORTED;
2553 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
2555 IDsDriverImpl *This = (IDsDriverImpl *)iface;
2556 ULONG refCount = InterlockedIncrement(&This->ref);
2558 TRACE("(%p)->(ref before=%lu)\n",This, refCount - 1);
2563 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
2565 IDsDriverImpl *This = (IDsDriverImpl *)iface;
2566 ULONG refCount = InterlockedDecrement(&This->ref);
2568 TRACE("(%p)->(ref before=%lu)\n",This, refCount + 1);
2572 HeapFree(GetProcessHeap(),0,This);
2576 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
2578 IDsDriverImpl *This = (IDsDriverImpl *)iface;
2579 TRACE("(%p,%p)\n",iface,pDesc);
2580 memcpy(pDesc, &(WOutDev[This->wDevID].ds_desc), sizeof(DSDRIVERDESC));
2581 pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
2582 DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK;
2583 pDesc->dnDevNode = WOutDev[This->wDevID].waveDesc.dnDevNode;
2585 pDesc->wReserved = 0;
2586 pDesc->ulDeviceNum = This->wDevID;
2587 pDesc->dwHeapType = DSDHEAP_NOHEAP;
2588 pDesc->pvDirectDrawHeap = NULL;
2589 pDesc->dwMemStartAddress = 0;
2590 pDesc->dwMemEndAddress = 0;
2591 pDesc->dwMemAllocExtra = 0;
2592 pDesc->pvReserved1 = NULL;
2593 pDesc->pvReserved2 = NULL;
2597 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
2599 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2600 TRACE("(%p)\n",iface);
2604 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
2606 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2607 TRACE("(%p)\n",iface);
2611 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
2613 IDsDriverImpl *This = (IDsDriverImpl *)iface;
2614 TRACE("(%p,%p)\n",iface,pCaps);
2615 memset(pCaps, 0, sizeof(*pCaps));
2617 pCaps->dwFlags = DSCAPS_PRIMARYMONO;
2618 if ( WOutDev[This->wDevID].caps.wChannels == 2 )
2619 pCaps->dwFlags |= DSCAPS_PRIMARYSTEREO;
2621 if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 ) )
2622 pCaps->dwFlags |= DSCAPS_PRIMARY8BIT;
2624 if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S16 | WAVE_FORMAT_2S16 | WAVE_FORMAT_4S16))
2625 pCaps->dwFlags |= DSCAPS_PRIMARY16BIT;
2627 pCaps->dwPrimaryBuffers = 1;
2628 TRACE("caps=0x%X\n",(unsigned int)pCaps->dwFlags);
2629 pCaps->dwMinSecondarySampleRate = DSBFREQUENCY_MIN;
2630 pCaps->dwMaxSecondarySampleRate = DSBFREQUENCY_MAX;
2632 /* the other fields only apply to secondary buffers, which we don't support
2633 * (unless we want to mess with wavetable synthesizers and MIDI) */
2637 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
2638 LPWAVEFORMATEX pwfx,
2639 DWORD dwFlags, DWORD dwCardAddress,
2640 LPDWORD pdwcbBufferSize,
2644 IDsDriverImpl *This = (IDsDriverImpl *)iface;
2645 IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
2648 TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
2649 /* we only support primary buffers */
2650 if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
2651 return DSERR_UNSUPPORTED;
2653 return DSERR_ALLOCATED;
2654 if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
2655 return DSERR_CONTROLUNAVAIL;
2657 *ippdsdb = (IDsDriverBufferImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
2658 if (*ippdsdb == NULL)
2659 return DSERR_OUTOFMEMORY;
2660 (*ippdsdb)->lpVtbl = &dsdbvt;
2661 (*ippdsdb)->ref = 1;
2662 (*ippdsdb)->drv = This;
2664 err = DSDB_CreateMMAP((*ippdsdb));
2667 HeapFree(GetProcessHeap(), 0, *ippdsdb);
2671 *ppbBuffer = (*ippdsdb)->mmap_buffer;
2672 *pdwcbBufferSize = (*ippdsdb)->mmap_buflen_bytes;
2674 This->primary = *ippdsdb;
2676 /* buffer is ready to go */
2677 TRACE("buffer created at %p\n", *ippdsdb);
2681 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
2682 PIDSDRIVERBUFFER pBuffer,
2685 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2686 TRACE("(%p,%p): stub\n",iface,pBuffer);
2687 return DSERR_INVALIDCALL;
2690 static IDsDriverVtbl dsdvt =
2692 IDsDriverImpl_QueryInterface,
2693 IDsDriverImpl_AddRef,
2694 IDsDriverImpl_Release,
2695 IDsDriverImpl_GetDriverDesc,
2697 IDsDriverImpl_Close,
2698 IDsDriverImpl_GetCaps,
2699 IDsDriverImpl_CreateSoundBuffer,
2700 IDsDriverImpl_DuplicateSoundBuffer
2703 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
2705 IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
2707 TRACE("driver created\n");
2709 /* the HAL isn't much better than the HEL if we can't do mmap() */
2710 if (!(WOutDev[wDevID].caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
2711 ERR("DirectSound flag not set\n");
2712 MESSAGE("This sound card's driver does not support direct access\n");
2713 MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
2714 return MMSYSERR_NOTSUPPORTED;
2717 *idrv = (IDsDriverImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
2719 return MMSYSERR_NOMEM;
2720 (*idrv)->lpVtbl = &dsdvt;
2723 (*idrv)->wDevID = wDevID;
2724 (*idrv)->primary = NULL;
2725 return MMSYSERR_NOERROR;
2728 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2730 memcpy(desc, &(WOutDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
2731 return MMSYSERR_NOERROR;
2734 /*======================================================================*
2735 * Low level WAVE IN implementation *
2736 *======================================================================*/
2738 /**************************************************************************
2739 * widNotifyClient [internal]
2741 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
2743 TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
2749 if (wwi->wFlags != DCB_NULL &&
2750 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags, (HDRVR)wwi->waveDesc.hWave,
2751 wMsg, wwi->waveDesc.dwInstance, dwParam1, dwParam2)) {
2752 WARN("can't notify client !\n");
2753 return MMSYSERR_ERROR;
2757 FIXME("Unknown callback message %u\n", wMsg);
2758 return MMSYSERR_INVALPARAM;
2760 return MMSYSERR_NOERROR;
2763 /**************************************************************************
2764 * widGetDevCaps [internal]
2766 static DWORD widGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
2768 TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
2770 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
2772 if (wDevID >= MAX_WAVEINDRV) {
2773 TRACE("MAX_WAVOUTDRV reached !\n");
2774 return MMSYSERR_BADDEVICEID;
2777 memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
2778 return MMSYSERR_NOERROR;
2781 /**************************************************************************
2782 * widRecorder_ReadHeaders [internal]
2784 static void widRecorder_ReadHeaders(WINE_WAVEIN * wwi)
2786 enum win_wm_message tmp_msg;
2791 while (ALSA_RetrieveRingMessage(&wwi->msgRing, &tmp_msg, &tmp_param, &tmp_ev)) {
2792 if (tmp_msg == WINE_WM_HEADER) {
2794 lpWaveHdr = (LPWAVEHDR)tmp_param;
2795 lpWaveHdr->lpNext = 0;
2797 if (wwi->lpQueuePtr == 0)
2798 wwi->lpQueuePtr = lpWaveHdr;
2800 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2804 ERR("should only have headers left\n");
2809 /**************************************************************************
2810 * widRecorder [internal]
2812 static DWORD CALLBACK widRecorder(LPVOID pmt)
2814 WORD uDevID = (DWORD)pmt;
2815 WINE_WAVEIN* wwi = (WINE_WAVEIN*)&WInDev[uDevID];
2819 LPVOID buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, wwi->dwPeriodSize);
2820 char *pOffset = buffer;
2821 enum win_wm_message msg;
2824 DWORD frames_per_period;
2826 wwi->state = WINE_WS_STOPPED;
2827 wwi->dwTotalRecorded = 0;
2828 wwi->lpQueuePtr = NULL;
2830 SetEvent(wwi->hStartUpEvent);
2832 /* make sleep time to be # of ms to output a period */
2833 dwSleepTime = (1024/*wwi-dwPeriodSize => overrun!*/ * 1000) / wwi->format.Format.nAvgBytesPerSec;
2834 frames_per_period = snd_pcm_bytes_to_frames(wwi->p_handle, wwi->dwPeriodSize);
2835 TRACE("sleeptime=%ld ms\n", dwSleepTime);
2838 /* wait for dwSleepTime or an event in thread's queue */
2839 /* FIXME: could improve wait time depending on queue state,
2840 * ie, number of queued fragments
2842 if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
2849 lpWaveHdr = wwi->lpQueuePtr;
2850 /* read all the fragments accumulated so far */
2851 frames = snd_pcm_avail_update(wwi->p_handle);
2852 bytes = snd_pcm_frames_to_bytes(wwi->p_handle, frames);
2853 TRACE("frames = %ld bytes = %ld\n", frames, bytes);
2854 periods = bytes / wwi->dwPeriodSize;
2855 while ((periods > 0) && (wwi->lpQueuePtr))
2858 bytes = wwi->dwPeriodSize;
2859 TRACE("bytes = %ld\n",bytes);
2860 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwPeriodSize)
2862 /* directly read fragment in wavehdr */
2863 read = wwi->read(wwi->p_handle, lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded, frames_per_period);
2864 bytesRead = snd_pcm_frames_to_bytes(wwi->p_handle, read);
2866 TRACE("bytesRead=%ld (direct)\n", bytesRead);
2867 if (bytesRead != (DWORD) -1)
2869 /* update number of bytes recorded in current buffer and by this device */
2870 lpWaveHdr->dwBytesRecorded += bytesRead;
2871 wwi->dwTotalRecorded += bytesRead;
2873 /* buffer is full. notify client */
2874 if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2876 /* must copy the value of next waveHdr, because we have no idea of what
2877 * will be done with the content of lpWaveHdr in callback
2879 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
2881 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2882 lpWaveHdr->dwFlags |= WHDR_DONE;
2884 wwi->lpQueuePtr = lpNext;
2885 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2889 TRACE("read(%s, %p, %ld) failed (%s)\n", wwi->device,
2890 lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2891 frames_per_period, strerror(errno));
2896 /* read the fragment in a local buffer */
2897 read = wwi->read(wwi->p_handle, buffer, frames_per_period);
2898 bytesRead = snd_pcm_frames_to_bytes(wwi->p_handle, read);
2901 TRACE("bytesRead=%ld (local)\n", bytesRead);
2903 if (bytesRead == (DWORD) -1) {
2904 TRACE("read(%s, %p, %ld) failed (%s)\n", wwi->device,
2905 buffer, frames_per_period, strerror(errno));
2909 /* copy data in client buffers */
2910 while (bytesRead != (DWORD) -1 && bytesRead > 0)
2912 DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
2914 memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2918 /* update number of bytes recorded in current buffer and by this device */
2919 lpWaveHdr->dwBytesRecorded += dwToCopy;
2920 wwi->dwTotalRecorded += dwToCopy;
2921 bytesRead -= dwToCopy;
2922 pOffset += dwToCopy;
2924 /* client buffer is full. notify client */
2925 if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2927 /* must copy the value of next waveHdr, because we have no idea of what
2928 * will be done with the content of lpWaveHdr in callback
2930 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
2931 TRACE("lpNext=%p\n", lpNext);
2933 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2934 lpWaveHdr->dwFlags |= WHDR_DONE;
2936 wwi->lpQueuePtr = lpNext;
2937 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2940 if (!lpNext && bytesRead) {
2941 /* before we give up, check for more header messages */
2942 while (ALSA_PeekRingMessage(&wwi->msgRing, &msg, ¶m, &ev))
2944 if (msg == WINE_WM_HEADER) {
2946 ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, ¶m, &ev);
2947 hdr = ((LPWAVEHDR)param);
2948 TRACE("msg = %s, hdr = %p, ev = %p\n", getCmdString(msg), hdr, ev);
2950 if (lpWaveHdr == 0) {
2951 /* new head of queue */
2952 wwi->lpQueuePtr = lpWaveHdr = hdr;
2954 /* insert buffer at the end of queue */
2956 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2963 if (lpWaveHdr == 0) {
2964 /* no more buffer to copy data to, but we did read more.
2965 * what hasn't been copied will be dropped
2967 WARN("buffer under run! %lu bytes dropped.\n", bytesRead);
2968 wwi->lpQueuePtr = NULL;
2978 WAIT_OMR(&wwi->msgRing, dwSleepTime);
2980 while (ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, ¶m, &ev))
2982 TRACE("msg=%s param=0x%lx\n", getCmdString(msg), param);
2984 case WINE_WM_PAUSING:
2985 wwi->state = WINE_WS_PAUSED;
2986 /*FIXME("Device should stop recording\n");*/
2989 case WINE_WM_STARTING:
2990 wwi->state = WINE_WS_PLAYING;
2991 snd_pcm_start(wwi->p_handle);
2994 case WINE_WM_HEADER:
2995 lpWaveHdr = (LPWAVEHDR)param;
2996 lpWaveHdr->lpNext = 0;
2998 /* insert buffer at the end of queue */
3001 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
3005 case WINE_WM_STOPPING:
3006 if (wwi->state != WINE_WS_STOPPED)
3008 snd_pcm_drain(wwi->p_handle);
3010 /* read any headers in queue */
3011 widRecorder_ReadHeaders(wwi);
3013 /* return current buffer to app */
3014 lpWaveHdr = wwi->lpQueuePtr;
3017 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
3018 TRACE("stop %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
3019 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
3020 lpWaveHdr->dwFlags |= WHDR_DONE;
3021 wwi->lpQueuePtr = lpNext;
3022 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
3025 wwi->state = WINE_WS_STOPPED;
3028 case WINE_WM_RESETTING:
3029 if (wwi->state != WINE_WS_STOPPED)
3031 snd_pcm_drain(wwi->p_handle);
3033 wwi->state = WINE_WS_STOPPED;
3034 wwi->dwTotalRecorded = 0;
3036 /* read any headers in queue */
3037 widRecorder_ReadHeaders(wwi);
3039 /* return all buffers to the app */
3040 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
3041 TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
3042 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
3043 lpWaveHdr->dwFlags |= WHDR_DONE;
3044 wwi->lpQueuePtr = lpWaveHdr->lpNext;
3045 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
3048 wwi->lpQueuePtr = NULL;
3051 case WINE_WM_CLOSING:
3053 wwi->state = WINE_WS_CLOSED;
3055 HeapFree(GetProcessHeap(), 0, buffer);
3057 /* shouldn't go here */
3058 case WINE_WM_UPDATE:
3063 FIXME("unknown message %d\n", msg);
3069 /* just for not generating compilation warnings... should never be executed */
3073 /**************************************************************************
3074 * widOpen [internal]
3076 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
3079 snd_pcm_hw_params_t * hw_params;
3080 snd_pcm_sw_params_t * sw_params;
3081 snd_pcm_access_t access;
3082 snd_pcm_format_t format;
3084 unsigned int buffer_time = 500000;
3085 unsigned int period_time = 10000;
3086 snd_pcm_uframes_t buffer_size;
3087 snd_pcm_uframes_t period_size;
3093 snd_pcm_hw_params_alloca(&hw_params);
3094 snd_pcm_sw_params_alloca(&sw_params);
3096 TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
3097 if (lpDesc == NULL) {
3098 WARN("Invalid Parameter !\n");
3099 return MMSYSERR_INVALPARAM;
3101 if (wDevID >= MAX_WAVEOUTDRV) {
3102 TRACE("MAX_WAVOUTDRV reached !\n");
3103 return MMSYSERR_BADDEVICEID;
3106 /* only PCM format is supported so far... */
3107 if (!supportedFormat(lpDesc->lpFormat)) {
3108 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
3109 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
3110 lpDesc->lpFormat->nSamplesPerSec);
3111 return WAVERR_BADFORMAT;
3114 if (dwFlags & WAVE_FORMAT_QUERY) {
3115 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
3116 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
3117 lpDesc->lpFormat->nSamplesPerSec);
3118 return MMSYSERR_NOERROR;
3121 wwi = &WInDev[wDevID];
3123 if ((dwFlags & WAVE_DIRECTSOUND) && !(wwi->dwSupport & WAVECAPS_DIRECTSOUND))
3124 /* not supported, ignore it */
3125 dwFlags &= ~WAVE_DIRECTSOUND;
3128 flags = SND_PCM_NONBLOCK;
3130 if ( dwFlags & WAVE_DIRECTSOUND )
3131 flags |= SND_PCM_ASYNC;
3134 if ( (err=snd_pcm_open(&pcm, wwi->device, SND_PCM_STREAM_CAPTURE, flags)) < 0 )
3136 ERR("Error open: %s\n", snd_strerror(err));
3137 return MMSYSERR_NOTENABLED;
3140 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
3142 memcpy(&wwi->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
3143 copy_format(lpDesc->lpFormat, &wwi->format);
3145 if (wwi->format.Format.wBitsPerSample == 0) {
3146 WARN("Resetting zeroed wBitsPerSample\n");
3147 wwi->format.Format.wBitsPerSample = 8 *
3148 (wwi->format.Format.nAvgBytesPerSec /
3149 wwi->format.Format.nSamplesPerSec) /
3150 wwi->format.Format.nChannels;
3153 snd_pcm_hw_params_any(pcm, hw_params);
3155 #define EXIT_ON_ERROR(f,e,txt) do \
3158 if ( (err = (f) ) < 0) \
3160 ERR(txt ": %s\n", snd_strerror(err)); \
3161 snd_pcm_close(pcm); \
3166 access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
3167 if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
3168 WARN("mmap not available. switching to standard write.\n");
3169 access = SND_PCM_ACCESS_RW_INTERLEAVED;
3170 EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
3171 wwi->read = snd_pcm_readi;
3174 wwi->read = snd_pcm_mmap_readi;
3176 EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwi->format.Format.nChannels), MMSYSERR_INVALPARAM, "unable to set required channels");
3178 if ((wwi->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
3179 ((wwi->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
3180 IsEqualGUID(&wwi->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
3181 format = (wwi->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
3182 (wwi->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
3183 (wwi->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
3184 (wwi->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
3185 } else if ((wwi->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
3186 IsEqualGUID(&wwi->format.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)){
3187 format = (wwi->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_FLOAT_LE : -1;
3188 } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
3189 FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
3191 return WAVERR_BADFORMAT;
3192 } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
3193 FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
3195 return WAVERR_BADFORMAT;
3196 } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
3197 FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
3199 return WAVERR_BADFORMAT;
3201 ERR("invalid format: %0x04x\n", wwi->format.Format.wFormatTag);
3203 return WAVERR_BADFORMAT;
3206 EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), MMSYSERR_INVALPARAM, "unable to set required format");
3208 rate = wwi->format.Format.nSamplesPerSec;
3210 err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
3212 ERR("Rate %ld Hz not available for playback: %s\n", wwi->format.Format.nSamplesPerSec, snd_strerror(rate));
3214 return WAVERR_BADFORMAT;
3216 if (rate != wwi->format.Format.nSamplesPerSec) {
3217 ERR("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwi->format.Format.nSamplesPerSec, rate);
3219 return WAVERR_BADFORMAT;
3223 EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
3225 EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
3227 EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
3230 err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
3231 err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
3233 snd_pcm_sw_params_current(pcm, sw_params);
3234 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");
3235 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
3236 EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
3237 EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
3238 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
3239 EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
3240 #undef EXIT_ON_ERROR
3242 snd_pcm_prepare(pcm);
3245 ALSA_TraceParameters(hw_params, sw_params, FALSE);
3247 /* now, we can save all required data for later use... */
3248 if ( wwi->hw_params )
3249 snd_pcm_hw_params_free(wwi->hw_params);
3250 snd_pcm_hw_params_malloc(&(wwi->hw_params));
3251 snd_pcm_hw_params_copy(wwi->hw_params, hw_params);
3253 wwi->dwBufferSize = buffer_size;
3254 wwi->lpQueuePtr = wwi->lpPlayPtr = wwi->lpLoopPtr = NULL;
3255 wwi->p_handle = pcm;
3257 ALSA_InitRingMessage(&wwi->msgRing);
3259 wwi->count = snd_pcm_poll_descriptors_count (wwi->p_handle);
3260 if (wwi->count <= 0) {
3261 ERR("Invalid poll descriptors count\n");
3262 return MMSYSERR_ERROR;
3265 wwi->ufds = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct pollfd) * wwi->count);
3266 if (wwi->ufds == NULL) {
3267 ERR("No enough memory\n");
3268 return MMSYSERR_NOMEM;
3270 if ((err = snd_pcm_poll_descriptors(wwi->p_handle, wwi->ufds, wwi->count)) < 0) {
3271 ERR("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
3272 return MMSYSERR_ERROR;
3275 wwi->dwPeriodSize = period_size;
3276 /*if (wwi->dwFragmentSize % wwi->format.Format.nBlockAlign)
3277 ERR("Fragment doesn't contain an integral number of data blocks\n");
3279 TRACE("dwPeriodSize=%lu\n", wwi->dwPeriodSize);
3280 TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
3281 wwi->format.Format.wBitsPerSample, wwi->format.Format.nAvgBytesPerSec,
3282 wwi->format.Format.nSamplesPerSec, wwi->format.Format.nChannels,
3283 wwi->format.Format.nBlockAlign);
3285 if (!(dwFlags & WAVE_DIRECTSOUND)) {
3286 wwi->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
3287 wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
3288 WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
3289 CloseHandle(wwi->hStartUpEvent);
3291 wwi->hThread = INVALID_HANDLE_VALUE;
3292 wwi->dwThreadID = 0;
3294 wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
3296 return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
3300 /**************************************************************************
3301 * widClose [internal]
3303 static DWORD widClose(WORD wDevID)
3305 DWORD ret = MMSYSERR_NOERROR;
3308 TRACE("(%u);\n", wDevID);
3310 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3311 WARN("bad device ID !\n");
3312 return MMSYSERR_BADDEVICEID;
3315 wwi = &WInDev[wDevID];
3316 if (wwi->lpQueuePtr) {
3317 WARN("buffers still playing !\n");
3318 ret = WAVERR_STILLPLAYING;
3320 if (wwi->hThread != INVALID_HANDLE_VALUE) {
3321 ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
3323 ALSA_DestroyRingMessage(&wwi->msgRing);
3325 snd_pcm_hw_params_free(wwi->hw_params);
3326 wwi->hw_params = NULL;
3328 snd_pcm_close(wwi->p_handle);
3329 wwi->p_handle = NULL;
3331 ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
3334 HeapFree(GetProcessHeap(), 0, wwi->ufds);
3338 /**************************************************************************
3339 * widAddBuffer [internal]
3342 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3344 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3346 /* first, do the sanity checks... */
3347 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3348 WARN("bad dev ID !\n");
3349 return MMSYSERR_BADDEVICEID;
3352 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
3353 return WAVERR_UNPREPARED;
3355 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3356 return WAVERR_STILLPLAYING;
3358 lpWaveHdr->dwFlags &= ~WHDR_DONE;
3359 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
3360 lpWaveHdr->lpNext = 0;
3362 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
3364 return MMSYSERR_NOERROR;
3367 /**************************************************************************
3368 * widStart [internal]
3371 static DWORD widStart(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3373 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3375 /* first, do the sanity checks... */
3376 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3377 WARN("bad dev ID !\n");
3378 return MMSYSERR_BADDEVICEID;
3381 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
3385 return MMSYSERR_NOERROR;
3388 /**************************************************************************
3389 * widStop [internal]
3392 static DWORD widStop(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3394 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3396 /* first, do the sanity checks... */
3397 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3398 WARN("bad dev ID !\n");
3399 return MMSYSERR_BADDEVICEID;
3402 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
3404 return MMSYSERR_NOERROR;
3407 /**************************************************************************
3408 * widReset [internal]
3410 static DWORD widReset(WORD wDevID)
3412 TRACE("(%u);\n", wDevID);
3413 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
3414 WARN("can't reset !\n");
3415 return MMSYSERR_INVALHANDLE;
3417 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
3418 return MMSYSERR_NOERROR;
3421 /**************************************************************************
3422 * widGetPosition [internal]
3424 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
3428 TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
3430 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
3431 WARN("can't get pos !\n");
3432 return MMSYSERR_INVALHANDLE;
3435 if (lpTime == NULL) {
3436 WARN("invalid parameter: lpTime = NULL\n");
3437 return MMSYSERR_INVALPARAM;
3440 wwi = &WInDev[wDevID];
3441 ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_UPDATE, 0, TRUE);
3443 return bytes_to_mmtime(lpTime, wwi->dwTotalRecorded, &wwi->format);
3446 /**************************************************************************
3447 * widGetNumDevs [internal]
3449 static DWORD widGetNumDevs(void)
3451 return ALSA_WidNumDevs;
3454 /**************************************************************************
3455 * widDevInterfaceSize [internal]
3457 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
3459 TRACE("(%u, %p)\n", wDevID, dwParam1);
3461 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3462 NULL, 0 ) * sizeof(WCHAR);
3463 return MMSYSERR_NOERROR;
3466 /**************************************************************************
3467 * widDevInterface [internal]
3469 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
3471 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3472 NULL, 0 ) * sizeof(WCHAR))
3474 MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3475 dwParam1, dwParam2 / sizeof(WCHAR));
3476 return MMSYSERR_NOERROR;
3478 return MMSYSERR_INVALPARAM;
3481 /**************************************************************************
3482 * widDsCreate [internal]
3484 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
3486 TRACE("(%d,%p)\n",wDevID,drv);
3488 /* the HAL isn't much better than the HEL if we can't do mmap() */
3489 FIXME("DirectSoundCapture not implemented\n");
3490 MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
3491 return MMSYSERR_NOTSUPPORTED;
3494 /**************************************************************************
3495 * widDsDesc [internal]
3497 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
3499 memcpy(desc, &(WInDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
3500 return MMSYSERR_NOERROR;
3503 /**************************************************************************
3504 * widMessage (WINEALSA.@)
3506 DWORD WINAPI ALSA_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
3507 DWORD dwParam1, DWORD dwParam2)
3509 TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
3510 wDevID, wMsg, dwUser, dwParam1, dwParam2);
3517 /* FIXME: Pretend this is supported */
3519 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
3520 case WIDM_CLOSE: return widClose (wDevID);
3521 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3522 case WIDM_PREPARE: return MMSYSERR_NOTSUPPORTED;
3523 case WIDM_UNPREPARE: return MMSYSERR_NOTSUPPORTED;
3524 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEOUTCAPSW)dwParam1, dwParam2);
3525 case WIDM_GETNUMDEVS: return widGetNumDevs ();
3526 case WIDM_GETPOS: return widGetPosition (wDevID, (LPMMTIME)dwParam1, dwParam2);
3527 case WIDM_RESET: return widReset (wDevID);
3528 case WIDM_START: return widStart (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3529 case WIDM_STOP: return widStop (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3530 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
3531 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
3532 case DRV_QUERYDSOUNDIFACE: return widDsCreate (wDevID, (PIDSCDRIVER*)dwParam1);
3533 case DRV_QUERYDSOUNDDESC: return widDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
3535 FIXME("unknown message %d!\n", wMsg);
3537 return MMSYSERR_NOTSUPPORTED;
3542 /**************************************************************************
3543 * widMessage (WINEALSA.@)
3545 DWORD WINAPI ALSA_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3546 DWORD dwParam1, DWORD dwParam2)
3548 FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3549 return MMSYSERR_NOTENABLED;
3552 /**************************************************************************
3553 * wodMessage (WINEALSA.@)
3555 DWORD WINAPI ALSA_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3556 DWORD dwParam1, DWORD dwParam2)
3558 FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3559 return MMSYSERR_NOTENABLED;
3562 #endif /* HAVE_ALSA */