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 /* FIXME: we shouldn't be using internal functions... */
75 snd_pcm_uframes_t _snd_pcm_mmap_hw_ptr(snd_pcm_t *pcm);
78 /* state diagram for waveOut writing:
80 * +---------+-------------+---------------+---------------------------------+
81 * | state | function | event | new state |
82 * +---------+-------------+---------------+---------------------------------+
83 * | | open() | | STOPPED |
84 * | PAUSED | write() | | PAUSED |
85 * | STOPPED | write() | <thrd create> | PLAYING |
86 * | PLAYING | write() | HEADER | PLAYING |
87 * | (other) | write() | <error> | |
88 * | (any) | pause() | PAUSING | PAUSED |
89 * | PAUSED | restart() | RESTARTING | PLAYING (if no thrd => STOPPED) |
90 * | (any) | reset() | RESETTING | STOPPED |
91 * | (any) | close() | CLOSING | CLOSED |
92 * +---------+-------------+---------------+---------------------------------+
95 /* states of the playing device */
96 #define WINE_WS_PLAYING 0
97 #define WINE_WS_PAUSED 1
98 #define WINE_WS_STOPPED 2
99 #define WINE_WS_CLOSED 3
101 /* events to be send to device */
102 enum win_wm_message {
103 WINE_WM_PAUSING = WM_USER + 1, WINE_WM_RESTARTING, WINE_WM_RESETTING, WINE_WM_HEADER,
104 WINE_WM_UPDATE, WINE_WM_BREAKLOOP, WINE_WM_CLOSING, WINE_WM_STARTING, WINE_WM_STOPPING
108 #define SIGNAL_OMR(omr) do { int x = 0; write((omr)->msg_pipe[1], &x, sizeof(x)); } while (0)
109 #define CLEAR_OMR(omr) do { int x = 0; read((omr)->msg_pipe[0], &x, sizeof(x)); } while (0)
110 #define RESET_OMR(omr) do { } while (0)
111 #define WAIT_OMR(omr, sleep) \
112 do { struct pollfd pfd; pfd.fd = (omr)->msg_pipe[0]; \
113 pfd.events = POLLIN; poll(&pfd, 1, sleep); } while (0)
115 #define SIGNAL_OMR(omr) do { SetEvent((omr)->msg_event); } while (0)
116 #define CLEAR_OMR(omr) do { } while (0)
117 #define RESET_OMR(omr) do { ResetEvent((omr)->msg_event); } while (0)
118 #define WAIT_OMR(omr, sleep) \
119 do { WaitForSingleObject((omr)->msg_event, sleep); } while (0)
123 enum win_wm_message msg; /* message identifier */
124 DWORD param; /* parameter for this message */
125 HANDLE hEvent; /* if message is synchronous, handle of event for synchro */
128 /* implement an in-process message ring for better performance
129 * (compared to passing thru the server)
130 * this ring will be used by the input (resp output) record (resp playback) routine
132 #define ALSA_RING_BUFFER_INCREMENT 64
135 int ring_buffer_size;
143 CRITICAL_SECTION msg_crst;
147 volatile int state; /* one of the WINE_WS_ manifest constants */
148 WAVEOPENDESC waveDesc;
150 WAVEFORMATPCMEX format;
152 char* pcmname; /* string name of alsa PCM device */
153 char* ctlname; /* string name of alsa control device */
154 char interface_name[MAXPNAMELEN * 2];
156 snd_pcm_t* pcm; /* handle to ALSA playback device */
158 snd_pcm_hw_params_t * hw_params;
160 DWORD dwBufferSize; /* size of whole ALSA buffer in bytes */
161 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
162 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
164 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
165 DWORD dwLoops; /* private copy of loop counter */
167 DWORD dwPlayedTotal; /* number of bytes actually played since opening */
168 DWORD dwWrittenTotal; /* number of bytes written to ALSA buffer since opening */
170 /* synchronization stuff */
171 HANDLE hStartUpEvent;
174 ALSA_MSG_RING msgRing;
176 /* DirectSound stuff */
177 DSDRIVERDESC ds_desc;
178 DSDRIVERCAPS ds_caps;
180 /* Waveout only fields */
181 WAVEOUTCAPSW outcaps;
183 snd_hctl_t * hctl; /* control handle for the playback volume */
185 snd_pcm_sframes_t (*write)(snd_pcm_t *, const void *, snd_pcm_uframes_t );
187 DWORD dwPartialOffset; /* Offset of not yet written bytes in lpPlayPtr */
189 /* Wavein only fields */
194 snd_pcm_sframes_t (*read)(snd_pcm_t *, void *, snd_pcm_uframes_t );
196 DWORD dwPeriodSize; /* size of OSS buffer period */
197 DWORD dwTotalRecorded;
202 /*----------------------------------------------------------------------------
203 ** Global array of output and input devices, initialized via ALSA_WaveInit
205 #define WAVEDEV_ALLOC_EXTENT_SIZE 10
206 static WINE_WAVEDEV *WOutDev;
207 static DWORD ALSA_WodNumMallocedDevs;
208 static DWORD ALSA_WodNumDevs;
210 static WINE_WAVEDEV *WInDev;
211 static DWORD ALSA_WidNumMallocedDevs;
212 static DWORD ALSA_WidNumDevs;
214 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
215 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
218 /*======================================================================*
219 * Utility functions *
220 *======================================================================*/
222 /* These strings used only for tracing */
223 static const char * getCmdString(enum win_wm_message msg)
225 static char unknown[32];
226 #define MSG_TO_STR(x) case x: return #x
228 MSG_TO_STR(WINE_WM_PAUSING);
229 MSG_TO_STR(WINE_WM_RESTARTING);
230 MSG_TO_STR(WINE_WM_RESETTING);
231 MSG_TO_STR(WINE_WM_HEADER);
232 MSG_TO_STR(WINE_WM_UPDATE);
233 MSG_TO_STR(WINE_WM_BREAKLOOP);
234 MSG_TO_STR(WINE_WM_CLOSING);
235 MSG_TO_STR(WINE_WM_STARTING);
236 MSG_TO_STR(WINE_WM_STOPPING);
239 sprintf(unknown, "UNKNOWN(0x%08x)", msg);
243 static const char * getMessage(UINT msg)
245 static char unknown[32];
246 #define MSG_TO_STR(x) case x: return #x
248 MSG_TO_STR(DRVM_INIT);
249 MSG_TO_STR(DRVM_EXIT);
250 MSG_TO_STR(DRVM_ENABLE);
251 MSG_TO_STR(DRVM_DISABLE);
252 MSG_TO_STR(WIDM_OPEN);
253 MSG_TO_STR(WIDM_CLOSE);
254 MSG_TO_STR(WIDM_ADDBUFFER);
255 MSG_TO_STR(WIDM_PREPARE);
256 MSG_TO_STR(WIDM_UNPREPARE);
257 MSG_TO_STR(WIDM_GETDEVCAPS);
258 MSG_TO_STR(WIDM_GETNUMDEVS);
259 MSG_TO_STR(WIDM_GETPOS);
260 MSG_TO_STR(WIDM_RESET);
261 MSG_TO_STR(WIDM_START);
262 MSG_TO_STR(WIDM_STOP);
263 MSG_TO_STR(WODM_OPEN);
264 MSG_TO_STR(WODM_CLOSE);
265 MSG_TO_STR(WODM_WRITE);
266 MSG_TO_STR(WODM_PAUSE);
267 MSG_TO_STR(WODM_GETPOS);
268 MSG_TO_STR(WODM_BREAKLOOP);
269 MSG_TO_STR(WODM_PREPARE);
270 MSG_TO_STR(WODM_UNPREPARE);
271 MSG_TO_STR(WODM_GETDEVCAPS);
272 MSG_TO_STR(WODM_GETNUMDEVS);
273 MSG_TO_STR(WODM_GETPITCH);
274 MSG_TO_STR(WODM_SETPITCH);
275 MSG_TO_STR(WODM_GETPLAYBACKRATE);
276 MSG_TO_STR(WODM_SETPLAYBACKRATE);
277 MSG_TO_STR(WODM_GETVOLUME);
278 MSG_TO_STR(WODM_SETVOLUME);
279 MSG_TO_STR(WODM_RESTART);
280 MSG_TO_STR(WODM_RESET);
281 MSG_TO_STR(DRV_QUERYDEVICEINTERFACESIZE);
282 MSG_TO_STR(DRV_QUERYDEVICEINTERFACE);
283 MSG_TO_STR(DRV_QUERYDSOUNDIFACE);
284 MSG_TO_STR(DRV_QUERYDSOUNDDESC);
287 sprintf(unknown, "UNKNOWN(0x%04x)", msg);
291 static const char * getFormat(WORD wFormatTag)
293 static char unknown[32];
294 #define FMT_TO_STR(x) case x: return #x
296 FMT_TO_STR(WAVE_FORMAT_PCM);
297 FMT_TO_STR(WAVE_FORMAT_EXTENSIBLE);
298 FMT_TO_STR(WAVE_FORMAT_MULAW);
299 FMT_TO_STR(WAVE_FORMAT_ALAW);
300 FMT_TO_STR(WAVE_FORMAT_ADPCM);
303 sprintf(unknown, "UNKNOWN(0x%04x)", wFormatTag);
307 /* Allow 1% deviation for sample rates (some ES137x cards) */
308 static BOOL NearMatch(int rate1, int rate2)
310 return (((100 * (rate1 - rate2)) / rate1) == 0);
313 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
314 WAVEFORMATPCMEX* format)
316 TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
317 lpTime->wType, format->Format.wBitsPerSample, format->Format.nSamplesPerSec,
318 format->Format.nChannels, format->Format.nAvgBytesPerSec);
319 TRACE("Position in bytes=%lu\n", position);
321 switch (lpTime->wType) {
323 lpTime->u.sample = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
324 TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
327 lpTime->u.ms = 1000.0 * position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels * format->Format.nSamplesPerSec);
328 TRACE("TIME_MS=%lu\n", lpTime->u.ms);
331 lpTime->u.smpte.fps = 30;
332 position = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
333 position += (format->Format.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
334 lpTime->u.smpte.sec = position / format->Format.nSamplesPerSec;
335 position -= lpTime->u.smpte.sec * format->Format.nSamplesPerSec;
336 lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
337 lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
338 lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
339 lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
340 lpTime->u.smpte.fps = 30;
341 lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->Format.nSamplesPerSec;
342 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
343 lpTime->u.smpte.hour, lpTime->u.smpte.min,
344 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
347 WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
348 lpTime->wType = TIME_BYTES;
351 lpTime->u.cb = position;
352 TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
355 return MMSYSERR_NOERROR;
358 static BOOL supportedFormat(LPWAVEFORMATEX wf)
362 if (wf->nSamplesPerSec<DSBFREQUENCY_MIN||wf->nSamplesPerSec>DSBFREQUENCY_MAX)
365 if (wf->wFormatTag == WAVE_FORMAT_PCM) {
366 if (wf->nChannels==1||wf->nChannels==2) {
367 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
370 } else if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
371 WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE *)wf;
373 if (wf->cbSize == 22 &&
374 (IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM) ||
375 IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))) {
376 if (wf->nChannels>=1 && wf->nChannels<=6) {
377 if (wf->wBitsPerSample==wfex->Samples.wValidBitsPerSample) {
378 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16||
379 wf->wBitsPerSample==24||wf->wBitsPerSample==32) {
383 WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
386 WARN("only KSDATAFORMAT_SUBTYPE_PCM and KSDATAFORMAT_SUBTYPE_IEEE_FLOAT "
388 } else if (wf->wFormatTag == WAVE_FORMAT_MULAW || wf->wFormatTag == WAVE_FORMAT_ALAW) {
389 if (wf->wBitsPerSample==8)
392 ERR("WAVE_FORMAT_MULAW and WAVE_FORMAT_ALAW wBitsPerSample must = 8\n");
394 } else if (wf->wFormatTag == WAVE_FORMAT_ADPCM) {
395 if (wf->wBitsPerSample==4)
398 ERR("WAVE_FORMAT_ADPCM wBitsPerSample must = 4\n");
400 WARN("only WAVE_FORMAT_PCM and WAVE_FORMAT_EXTENSIBLE supported\n");
405 static void copy_format(LPWAVEFORMATEX wf1, LPWAVEFORMATPCMEX wf2)
407 unsigned int iLength;
409 ZeroMemory(wf2, sizeof(wf2));
410 if (wf1->wFormatTag == WAVE_FORMAT_PCM)
411 iLength = sizeof(PCMWAVEFORMAT);
412 else if (wf1->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
413 iLength = sizeof(WAVEFORMATPCMEX);
415 iLength = sizeof(WAVEFORMATEX) + wf1->cbSize;
416 if (iLength > sizeof(WAVEFORMATPCMEX)) {
417 ERR("calculated %u bytes, capping to %u bytes\n", iLength, sizeof(WAVEFORMATPCMEX));
418 iLength = sizeof(WAVEFORMATPCMEX);
420 memcpy(wf2, wf1, iLength);
423 /*----------------------------------------------------------------------------
425 ** Retrieve a string from a registry key
427 static int ALSA_RegGetString(HKEY key, const char *value, char **bufp)
434 rc = RegQueryValueExA(key, value, NULL, &type, NULL, &bufsize);
435 if (rc != ERROR_SUCCESS)
441 *bufp = HeapAlloc(GetProcessHeap(), 0, bufsize);
445 rc = RegQueryValueExA(key, value, NULL, NULL, (LPBYTE)*bufp, &bufsize);
449 /*----------------------------------------------------------------------------
450 ** ALSA_RegGetBoolean
451 ** Get a string and interpret it as a boolean
453 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
454 static int ALSA_RegGetBoolean(HKEY key, const char *value, BOOL *answer)
459 rc = ALSA_RegGetString(key, value, &buf);
463 if (IS_OPTION_TRUE(*buf))
466 HeapFree(GetProcessHeap(), 0, buf);
472 /*----------------------------------------------------------------------------
473 ** ALSA_RegGetBoolean
474 ** Get a string and interpret it as a DWORD
476 static int ALSA_RegGetInt(HKEY key, const char *value, DWORD *answer)
481 rc = ALSA_RegGetString(key, value, &buf);
485 HeapFree(GetProcessHeap(), 0, buf);
491 /*======================================================================*
492 * Low level WAVE implementation *
493 *======================================================================*/
495 /*----------------------------------------------------------------------------
496 ** ALSA_TestDeviceForWine
498 ** Test to see if a given device is sufficient for Wine.
500 static int ALSA_TestDeviceForWine(int card, int device, snd_pcm_stream_t streamtype)
502 snd_pcm_t *pcm = NULL;
505 snd_pcm_hw_params_t *hwparams;
510 /* Note that the plug: device masks out a lot of info, we want to avoid that */
511 sprintf(pcmname, "hw:%d,%d", card, device);
512 retcode = snd_pcm_open(&pcm, pcmname, streamtype, SND_PCM_NONBLOCK);
515 /* Note that a busy device isn't automatically disqualified */
516 if (retcode == (-1 * EBUSY))
521 snd_pcm_hw_params_alloca(&hwparams);
523 retcode = snd_pcm_hw_params_any(pcm, hwparams);
526 reason = "Could not retrieve hw_params";
530 /* set the count of channels */
531 retcode = snd_pcm_hw_params_set_channels(pcm, hwparams, 2);
534 reason = "Could not set channels";
539 retcode = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rrate, 0);
542 reason = "Could not set rate";
548 reason = "Rate came back as 0";
552 /* write the parameters to device */
553 retcode = snd_pcm_hw_params(pcm, hwparams);
556 reason = "Could not set hwparams";
566 if (retcode != 0 && retcode != (-1 * ENOENT))
567 TRACE("Discarding card %d/device %d: %s [%d(%s)]\n", card, device, reason, retcode, snd_strerror(retcode));
573 /**************************************************************************
574 * ALSA_CheckSetVolume [internal]
576 * Helper function for Alsa volume queries. This tries to simplify
577 * the process of managing the volume. All parameters are optional
578 * (pass NULL to ignore or not use).
579 * Return values are MMSYSERR_NOERROR on success, or !0 on failure;
580 * error codes are normalized into the possible documented return
581 * values from waveOutGetVolume.
583 static int ALSA_CheckSetVolume(snd_hctl_t *hctl, int *out_left, int *out_right,
584 int *out_min, int *out_max, int *out_step,
585 int *new_left, int *new_right)
587 int rc = MMSYSERR_NOERROR;
589 snd_hctl_elem_t * elem = NULL;
590 snd_ctl_elem_info_t * eleminfop = NULL;
591 snd_ctl_elem_value_t * elemvaluep = NULL;
592 snd_ctl_elem_id_t * elemidp = NULL;
595 #define EXIT_ON_ERROR(f,txt,exitcode) do \
598 if ( (err = (f) ) < 0) \
600 ERR(txt " failed: %s\n", snd_strerror(err)); \
607 return MMSYSERR_NOTSUPPORTED;
609 /* Allocate areas to return information about the volume */
610 EXIT_ON_ERROR(snd_ctl_elem_id_malloc(&elemidp), "snd_ctl_elem_id_malloc", MMSYSERR_NOMEM);
611 EXIT_ON_ERROR(snd_ctl_elem_value_malloc (&elemvaluep), "snd_ctl_elem_value_malloc", MMSYSERR_NOMEM);
612 EXIT_ON_ERROR(snd_ctl_elem_info_malloc (&eleminfop), "snd_ctl_elem_info_malloc", MMSYSERR_NOMEM);
613 snd_ctl_elem_id_clear(elemidp);
614 snd_ctl_elem_value_clear(elemvaluep);
615 snd_ctl_elem_info_clear(eleminfop);
617 /* Setup and find an element id that exactly matches the characteristic we want
618 ** FIXME: It is probably short sighted to hard code and fixate on PCM Playback Volume */
619 snd_ctl_elem_id_set_name(elemidp, "PCM Playback Volume");
620 snd_ctl_elem_id_set_interface(elemidp, SND_CTL_ELEM_IFACE_MIXER);
621 elem = snd_hctl_find_elem(hctl, elemidp);
624 /* Read and return volume information */
625 EXIT_ON_ERROR(snd_hctl_elem_info(elem, eleminfop), "snd_hctl_elem_info", MMSYSERR_NOTSUPPORTED);
626 value_count = snd_ctl_elem_info_get_count(eleminfop);
627 if (out_min || out_max || out_step)
629 if (!snd_ctl_elem_info_is_readable(eleminfop))
631 ERR("snd_ctl_elem_info_is_readable returned false; cannot return info\n");
632 rc = MMSYSERR_NOTSUPPORTED;
637 *out_min = snd_ctl_elem_info_get_min(eleminfop);
640 *out_max = snd_ctl_elem_info_get_max(eleminfop);
643 *out_step = snd_ctl_elem_info_get_step(eleminfop);
646 if (out_left || out_right)
648 EXIT_ON_ERROR(snd_hctl_elem_read(elem, elemvaluep), "snd_hctl_elem_read", MMSYSERR_NOTSUPPORTED);
651 *out_left = snd_ctl_elem_value_get_integer(elemvaluep, 0);
655 if (value_count == 1)
656 *out_right = snd_ctl_elem_value_get_integer(elemvaluep, 0);
657 else if (value_count == 2)
658 *out_right = snd_ctl_elem_value_get_integer(elemvaluep, 1);
661 ERR("Unexpected value count %d from snd_ctl_elem_info_get_count while getting volume info\n", value_count);
669 if (new_left || new_right)
671 EXIT_ON_ERROR(snd_hctl_elem_read(elem, elemvaluep), "snd_hctl_elem_read", MMSYSERR_NOTSUPPORTED);
673 snd_ctl_elem_value_set_integer(elemvaluep, 0, *new_left);
676 if (value_count == 1)
677 snd_ctl_elem_value_set_integer(elemvaluep, 0, *new_right);
678 else if (value_count == 2)
679 snd_ctl_elem_value_set_integer(elemvaluep, 1, *new_right);
682 ERR("Unexpected value count %d from snd_ctl_elem_info_get_count while setting volume info\n", value_count);
688 EXIT_ON_ERROR(snd_hctl_elem_write(elem, elemvaluep), "snd_hctl_elem_write", MMSYSERR_NOTSUPPORTED);
693 ERR("Could not find 'PCM Playback Volume' element\n");
694 rc = MMSYSERR_NOTSUPPORTED;
703 snd_ctl_elem_value_free(elemvaluep);
705 snd_ctl_elem_info_free(eleminfop);
707 snd_ctl_elem_id_free(elemidp);
713 /**************************************************************************
714 * ALSA_XRUNRecovery [internal]
716 * used to recovery from XRUN errors (buffer underflow/overflow)
718 static int ALSA_XRUNRecovery(WINE_WAVEDEV * wwo, int err)
720 if (err == -EPIPE) { /* under-run */
721 err = snd_pcm_prepare(wwo->pcm);
723 ERR( "underrun recovery failed. prepare failed: %s\n", snd_strerror(err));
725 } else if (err == -ESTRPIPE) {
726 while ((err = snd_pcm_resume(wwo->pcm)) == -EAGAIN)
727 sleep(1); /* wait until the suspend flag is released */
729 err = snd_pcm_prepare(wwo->pcm);
731 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
738 /**************************************************************************
739 * ALSA_TraceParameters [internal]
741 * used to trace format changes, hw and sw parameters
743 static void ALSA_TraceParameters(snd_pcm_hw_params_t * hw_params, snd_pcm_sw_params_t * sw, int full)
746 snd_pcm_format_t format;
747 snd_pcm_access_t access;
748 err = snd_pcm_hw_params_get_access(hw_params, &access);
749 err = snd_pcm_hw_params_get_format(hw_params, &format);
751 #define X(x) ((x)? "true" : "false")
753 TRACE("FLAGS: sampleres=%s overrng=%s pause=%s resume=%s syncstart=%s batch=%s block=%s double=%s "
754 "halfd=%s joint=%s\n",
755 X(snd_pcm_hw_params_can_mmap_sample_resolution(hw_params)),
756 X(snd_pcm_hw_params_can_overrange(hw_params)),
757 X(snd_pcm_hw_params_can_pause(hw_params)),
758 X(snd_pcm_hw_params_can_resume(hw_params)),
759 X(snd_pcm_hw_params_can_sync_start(hw_params)),
760 X(snd_pcm_hw_params_is_batch(hw_params)),
761 X(snd_pcm_hw_params_is_block_transfer(hw_params)),
762 X(snd_pcm_hw_params_is_double(hw_params)),
763 X(snd_pcm_hw_params_is_half_duplex(hw_params)),
764 X(snd_pcm_hw_params_is_joint_duplex(hw_params)));
768 TRACE("access=%s\n", snd_pcm_access_name(access));
771 snd_pcm_access_mask_t * acmask;
772 snd_pcm_access_mask_alloca(&acmask);
773 snd_pcm_hw_params_get_access_mask(hw_params, acmask);
774 for ( access = SND_PCM_ACCESS_MMAP_INTERLEAVED; access <= SND_PCM_ACCESS_LAST; access++)
775 if (snd_pcm_access_mask_test(acmask, access))
776 TRACE("access=%s\n", snd_pcm_access_name(access));
781 TRACE("format=%s\n", snd_pcm_format_name(format));
786 snd_pcm_format_mask_t * fmask;
788 snd_pcm_format_mask_alloca(&fmask);
789 snd_pcm_hw_params_get_format_mask(hw_params, fmask);
790 for ( format = SND_PCM_FORMAT_S8; format <= SND_PCM_FORMAT_LAST ; format++)
791 if ( snd_pcm_format_mask_test(fmask, format) )
792 TRACE("format=%s\n", snd_pcm_format_name(format));
798 err = snd_pcm_hw_params_get_channels(hw_params, &val);
800 unsigned int min = 0;
801 unsigned int max = 0;
802 err = snd_pcm_hw_params_get_channels_min(hw_params, &min),
803 err = snd_pcm_hw_params_get_channels_max(hw_params, &max);
804 TRACE("channels_min=%u, channels_min_max=%u\n", min, max);
806 TRACE("channels=%d\n", val);
811 snd_pcm_uframes_t val=0;
812 err = snd_pcm_hw_params_get_buffer_size(hw_params, &val);
814 snd_pcm_uframes_t min = 0;
815 snd_pcm_uframes_t max = 0;
816 err = snd_pcm_hw_params_get_buffer_size_min(hw_params, &min),
817 err = snd_pcm_hw_params_get_buffer_size_max(hw_params, &max);
818 TRACE("buffer_size_min=%lu, buffer_size_min_max=%lu\n", min, max);
820 TRACE("buffer_size=%lu\n", val);
827 unsigned int val=0; \
828 err = snd_pcm_hw_params_get_##x(hw_params,&val, &dir); \
830 unsigned int min = 0; \
831 unsigned int max = 0; \
832 err = snd_pcm_hw_params_get_##x##_min(hw_params, &min, &dir); \
833 err = snd_pcm_hw_params_get_##x##_max(hw_params, &max, &dir); \
834 TRACE(#x "_min=%u " #x "_max=%u\n", min, max); \
836 TRACE(#x "=%d\n", val); \
845 snd_pcm_uframes_t val=0;
846 err = snd_pcm_hw_params_get_period_size(hw_params, &val, &dir);
848 snd_pcm_uframes_t min = 0;
849 snd_pcm_uframes_t max = 0;
850 err = snd_pcm_hw_params_get_period_size_min(hw_params, &min, &dir),
851 err = snd_pcm_hw_params_get_period_size_max(hw_params, &max, &dir);
852 TRACE("period_size_min=%lu, period_size_min_max=%lu\n", min, max);
854 TRACE("period_size=%lu\n", val);
866 /* return a string duplicated on the win32 process heap, free with HeapFree */
867 static char* ALSA_strdup(const char *s) {
868 char *result = HeapAlloc(GetProcessHeap(), 0, strlen(s)+1);
875 #define ALSA_RETURN_ONFAIL(mycall) \
881 ERR("%s failed: %s(%d)\n", #mycall, snd_strerror(rc), rc); \
886 /*----------------------------------------------------------------------------
889 ** Given an ALSA PCM, figure out our HW CAPS structure info.
890 ** ctl can be null, pcm is required, as is all output parms.
893 static int ALSA_ComputeCaps(snd_ctl_t *ctl, snd_pcm_t *pcm,
894 WORD *channels, DWORD *flags, DWORD *formats, DWORD *supports)
896 snd_pcm_hw_params_t *hw_params;
897 snd_pcm_format_mask_t *fmask;
898 snd_pcm_access_mask_t *acmask;
899 unsigned int ratemin = 0;
900 unsigned int ratemax = 0;
901 unsigned int chmin = 0;
902 unsigned int chmax = 0;
905 snd_pcm_hw_params_alloca(&hw_params);
906 ALSA_RETURN_ONFAIL(snd_pcm_hw_params_any(pcm, hw_params));
908 snd_pcm_format_mask_alloca(&fmask);
909 snd_pcm_hw_params_get_format_mask(hw_params, fmask);
911 snd_pcm_access_mask_alloca(&acmask);
912 ALSA_RETURN_ONFAIL(snd_pcm_hw_params_get_access_mask(hw_params, acmask));
914 ALSA_RETURN_ONFAIL(snd_pcm_hw_params_get_rate_min(hw_params, &ratemin, &dir));
915 ALSA_RETURN_ONFAIL(snd_pcm_hw_params_get_rate_max(hw_params, &ratemax, &dir));
916 ALSA_RETURN_ONFAIL(snd_pcm_hw_params_get_channels_min(hw_params, &chmin));
917 ALSA_RETURN_ONFAIL(snd_pcm_hw_params_get_channels_max(hw_params, &chmax));
920 if ( (r) >= ratemin && ( (r) <= ratemax || ratemax == -1) ) \
922 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_U8)) \
924 if (chmin <= 1 && 1 <= chmax) \
925 *formats |= WAVE_FORMAT_##v##M08; \
926 if (chmin <= 2 && 2 <= chmax) \
927 *formats |= WAVE_FORMAT_##v##S08; \
929 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_S16_LE)) \
931 if (chmin <= 1 && 1 <= chmax) \
932 *formats |= WAVE_FORMAT_##v##M16; \
933 if (chmin <= 2 && 2 <= chmax) \
934 *formats |= WAVE_FORMAT_##v##S16; \
945 FIXME("Device has a minimum of %d channels\n", chmin);
948 /* FIXME: is sample accurate always true ?
949 ** Can we do WAVECAPS_PITCH, WAVECAPS_SYNC, or WAVECAPS_PLAYBACKRATE? */
950 *supports |= WAVECAPS_SAMPLEACCURATE;
952 /* FIXME: NONITERLEAVED and COMPLEX are not supported right now */
953 if ( snd_pcm_access_mask_test( acmask, SND_PCM_ACCESS_MMAP_INTERLEAVED ) )
954 *supports |= WAVECAPS_DIRECTSOUND;
956 /* check for volume control support */
958 *supports |= WAVECAPS_VOLUME;
960 if (chmin <= 2 && 2 <= chmax)
961 *supports |= WAVECAPS_LRVOLUME;
964 if (*formats & (WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 |
965 WAVE_FORMAT_4M08 | WAVE_FORMAT_48M08 |
966 WAVE_FORMAT_96M08 | WAVE_FORMAT_1M16 |
967 WAVE_FORMAT_2M16 | WAVE_FORMAT_4M16 |
968 WAVE_FORMAT_48M16 | WAVE_FORMAT_96M16) )
969 *flags |= DSCAPS_PRIMARYMONO;
971 if (*formats & (WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 |
972 WAVE_FORMAT_4S08 | WAVE_FORMAT_48S08 |
973 WAVE_FORMAT_96S08 | WAVE_FORMAT_1S16 |
974 WAVE_FORMAT_2S16 | WAVE_FORMAT_4S16 |
975 WAVE_FORMAT_48S16 | WAVE_FORMAT_96S16) )
976 *flags |= DSCAPS_PRIMARYSTEREO;
978 if (*formats & (WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 |
979 WAVE_FORMAT_4M08 | WAVE_FORMAT_48M08 |
980 WAVE_FORMAT_96M08 | WAVE_FORMAT_1S08 |
981 WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 |
982 WAVE_FORMAT_48S08 | WAVE_FORMAT_96S08) )
983 *flags |= DSCAPS_PRIMARY8BIT;
985 if (*formats & (WAVE_FORMAT_1M16 | WAVE_FORMAT_2M16 |
986 WAVE_FORMAT_4M16 | WAVE_FORMAT_48M16 |
987 WAVE_FORMAT_96M16 | WAVE_FORMAT_1S16 |
988 WAVE_FORMAT_2S16 | WAVE_FORMAT_4S16 |
989 WAVE_FORMAT_48S16 | WAVE_FORMAT_96S16) )
990 *flags |= DSCAPS_PRIMARY16BIT;
995 /*----------------------------------------------------------------------------
996 ** ALSA_AddCommonDevice
998 ** Perform Alsa initialization common to both capture and playback
1000 ** Side Effect: ww->pcname and ww->ctlname may need to be freed.
1002 ** Note: this was originally coded by using snd_pcm_name(pcm), until
1003 ** I discovered that with at least one version of alsa lib,
1004 ** the use of a pcm named default:0 would cause snd_pcm_name() to fail.
1005 ** So passing the name in is logically extraneous. Sigh.
1007 static int ALSA_AddCommonDevice(snd_ctl_t *ctl, snd_pcm_t *pcm, const char *pcmname, WINE_WAVEDEV *ww)
1009 snd_pcm_info_t *infop;
1011 snd_pcm_info_alloca(&infop);
1012 ALSA_RETURN_ONFAIL(snd_pcm_info(pcm, infop));
1015 ww->pcmname = ALSA_strdup(pcmname);
1019 if (ctl && snd_ctl_name(ctl))
1020 ww->ctlname = ALSA_strdup(snd_ctl_name(ctl));
1022 strcpy(ww->interface_name, "winealsa: ");
1023 memcpy(ww->interface_name + strlen(ww->interface_name),
1025 min(strlen(ww->pcmname), sizeof(ww->interface_name) - strlen("winealsa: ")));
1027 strcpy(ww->ds_desc.szDrvname, "winealsa.drv");
1029 memcpy(ww->ds_desc.szDesc, snd_pcm_info_get_name(infop),
1030 min( (sizeof(ww->ds_desc.szDesc) - 1), strlen(snd_pcm_info_get_name(infop))) );
1032 ww->ds_caps.dwMinSecondarySampleRate = DSBFREQUENCY_MIN;
1033 ww->ds_caps.dwMaxSecondarySampleRate = DSBFREQUENCY_MAX;
1034 ww->ds_caps.dwPrimaryBuffers = 1;
1039 /*----------------------------------------------------------------------------
1042 static void ALSA_FreeDevice(WINE_WAVEDEV *ww)
1045 HeapFree(GetProcessHeap(), 0, ww->pcmname);
1049 HeapFree(GetProcessHeap(), 0, ww->ctlname);
1053 /*----------------------------------------------------------------------------
1054 ** ALSA_AddDeviceToArray
1056 ** Dynamically size one of the wavein or waveout arrays of devices,
1057 ** and add a fully configured device node to the array.
1060 static int ALSA_AddDeviceToArray(WINE_WAVEDEV *ww, WINE_WAVEDEV **array,
1061 DWORD *count, DWORD *alloced, int isdefault)
1065 if (*count >= *alloced)
1067 (*alloced) += WAVEDEV_ALLOC_EXTENT_SIZE;
1069 *array = HeapAlloc(GetProcessHeap(), 0, sizeof(*ww) * (*alloced));
1071 *array = HeapReAlloc(GetProcessHeap(), 0, *array, sizeof(*ww) * (*alloced));
1079 /* If this is the default, arrange for it to be the first element */
1080 if (isdefault && i > 0)
1082 (*array)[*count] = (*array)[0];
1092 /*----------------------------------------------------------------------------
1093 ** ALSA_AddPlaybackDevice
1095 ** Add a given Alsa device to Wine's internal list of Playback
1098 static int ALSA_AddPlaybackDevice(snd_ctl_t *ctl, snd_pcm_t *pcm, const char *pcmname, int isdefault)
1103 memset(&wwo, '\0', sizeof(wwo));
1105 rc = ALSA_AddCommonDevice(ctl, pcm, pcmname, &wwo);
1109 MultiByteToWideChar(CP_ACP, 0, wwo.ds_desc.szDesc, -1,
1110 wwo.outcaps.szPname, sizeof(wwo.outcaps.szPname)/sizeof(WCHAR));
1111 wwo.outcaps.szPname[sizeof(wwo.outcaps.szPname)/sizeof(WCHAR) - 1] = '\0';
1113 wwo.outcaps.wMid = MM_CREATIVE;
1114 wwo.outcaps.wPid = MM_CREATIVE_SBP16_WAVEOUT;
1115 wwo.outcaps.vDriverVersion = 0x0100;
1117 rc = ALSA_ComputeCaps(ctl, pcm, &wwo.outcaps.wChannels, &wwo.ds_caps.dwFlags,
1118 &wwo.outcaps.dwFormats, &wwo.outcaps.dwSupport);
1121 WARN("Error calculating device caps for pcm [%s]\n", wwo.pcmname);
1122 ALSA_FreeDevice(&wwo);
1126 rc = ALSA_AddDeviceToArray(&wwo, &WOutDev, &ALSA_WodNumDevs, &ALSA_WodNumMallocedDevs, isdefault);
1128 ALSA_FreeDevice(&wwo);
1132 /*----------------------------------------------------------------------------
1133 ** ALSA_AddCaptureDevice
1135 ** Add a given Alsa device to Wine's internal list of Capture
1138 static int ALSA_AddCaptureDevice(snd_ctl_t *ctl, snd_pcm_t *pcm, const char *pcmname, int isdefault)
1143 memset(&wwi, '\0', sizeof(wwi));
1145 rc = ALSA_AddCommonDevice(ctl, pcm, pcmname, &wwi);
1149 MultiByteToWideChar(CP_ACP, 0, wwi.ds_desc.szDesc, -1,
1150 wwi.incaps.szPname, sizeof(wwi.incaps.szPname) / sizeof(WCHAR));
1151 wwi.incaps.szPname[sizeof(wwi.incaps.szPname)/sizeof(WCHAR) - 1] = '\0';
1153 wwi.incaps.wMid = MM_CREATIVE;
1154 wwi.incaps.wPid = MM_CREATIVE_SBP16_WAVEOUT;
1155 wwi.incaps.vDriverVersion = 0x0100;
1157 rc = ALSA_ComputeCaps(ctl, pcm, &wwi.incaps.wChannels, &wwi.ds_caps.dwFlags,
1158 &wwi.incaps.dwFormats, &wwi.dwSupport);
1161 WARN("Error calculating device caps for pcm [%s]\n", wwi.pcmname);
1162 ALSA_FreeDevice(&wwi);
1166 rc = ALSA_AddDeviceToArray(&wwi, &WInDev, &ALSA_WidNumDevs, &ALSA_WidNumMallocedDevs, isdefault);
1168 ALSA_FreeDevice(&wwi);
1172 /*----------------------------------------------------------------------------
1173 ** ALSA_CheckEnvironment
1175 ** Given an Alsa style configuration node, scan its subitems
1176 ** for environment variable names, and use them to find an override,
1178 ** This is essentially a long and convolunted way of doing:
1179 ** getenv("ALSA_CARD")
1180 ** getenv("ALSA_CTL_CARD")
1181 ** getenv("ALSA_PCM_CARD")
1182 ** getenv("ALSA_PCM_DEVICE")
1184 ** The output value is set with the atoi() of the first environment
1185 ** variable found to be set, if any; otherwise, it is left alone
1187 static void ALSA_CheckEnvironment(snd_config_t *node, int *outvalue)
1189 snd_config_iterator_t iter;
1191 for (iter = snd_config_iterator_first(node);
1192 iter != snd_config_iterator_end(node);
1193 iter = snd_config_iterator_next(iter))
1195 snd_config_t *leaf = snd_config_iterator_entry(iter);
1196 if (snd_config_get_type(leaf) == SND_CONFIG_TYPE_STRING)
1199 if (snd_config_get_string(leaf, &value) >= 0)
1201 char *p = getenv(value);
1204 *outvalue = atoi(p);
1212 /*----------------------------------------------------------------------------
1213 ** ALSA_DefaultDevices
1215 ** Jump through Alsa style hoops to (hopefully) properly determine
1216 ** Alsa defaults for CTL Card #, as well as for PCM Card + Device #.
1217 ** We'll also find out if the user has set any of the environment
1218 ** variables that specify we're to use a specific card or device.
1221 ** directhw Whether to use a direct hardware device or not;
1222 ** essentially switches the pcm device name from
1223 ** one of 'default:X' or 'plughw:X' to "hw:X"
1224 ** defctlcard If !NULL, will hold the ctl card number given
1225 ** by the ALSA config as the default
1226 ** defpcmcard If !NULL, default pcm card #
1227 ** defpcmdev If !NULL, default pcm device #
1228 ** fixedctlcard If !NULL, and the user set the appropriate
1229 ** environment variable, we'll set to the
1230 ** card the user specified.
1231 ** fixedpcmcard If !NULL, and the user set the appropriate
1232 ** environment variable, we'll set to the
1233 ** card the user specified.
1234 ** fixedpcmdev If !NULL, and the user set the appropriate
1235 ** environment variable, we'll set to the
1236 ** device the user specified.
1238 ** Returns: 0 on success, < 0 on failiure
1240 static int ALSA_DefaultDevices(int directhw,
1242 long *defpcmcard, long *defpcmdev,
1244 int *fixedpcmcard, int *fixedpcmdev)
1246 snd_config_t *configp;
1247 char pcmsearch[256];
1249 ALSA_RETURN_ONFAIL(snd_config_update());
1252 if (snd_config_search(snd_config, "defaults.ctl.card", &configp) >= 0)
1253 snd_config_get_integer(configp, defctlcard);
1256 if (snd_config_search(snd_config, "defaults.pcm.card", &configp) >= 0)
1257 snd_config_get_integer(configp, defpcmcard);
1260 if (snd_config_search(snd_config, "defaults.pcm.device", &configp) >= 0)
1261 snd_config_get_integer(configp, defpcmdev);
1266 if (snd_config_search(snd_config, "ctl.hw.@args.CARD.default.vars", &configp) >= 0)
1267 ALSA_CheckEnvironment(configp, fixedctlcard);
1272 sprintf(pcmsearch, "pcm.%s.@args.CARD.default.vars", directhw ? "hw" : "plughw");
1273 if (snd_config_search(snd_config, pcmsearch, &configp) >= 0)
1274 ALSA_CheckEnvironment(configp, fixedpcmcard);
1279 sprintf(pcmsearch, "pcm.%s.@args.DEV.default.vars", directhw ? "hw" : "plughw");
1280 if (snd_config_search(snd_config, pcmsearch, &configp) >= 0)
1281 ALSA_CheckEnvironment(configp, fixedpcmdev);
1288 /*----------------------------------------------------------------------------
1291 ** Iterate through all discoverable ALSA cards, searching
1292 ** for usable PCM devices.
1295 ** directhw Whether to use a direct hardware device or not;
1296 ** essentially switches the pcm device name from
1297 ** one of 'default:X' or 'plughw:X' to "hw:X"
1298 ** defctlcard Alsa's notion of the default ctl card.
1299 ** defpcmcard . pcm card
1300 ** defpcmdev . pcm device
1301 ** fixedctlcard If not -1, then gives the value of ALSA_CTL_CARD
1302 ** or equivalent environment variable
1303 ** fixedpcmcard If not -1, then gives the value of ALSA_PCM_CARD
1304 ** or equivalent environment variable
1305 ** fixedpcmdev If not -1, then gives the value of ALSA_PCM_DEVICE
1306 ** or equivalent environment variable
1308 ** Returns: 0 on success, < 0 on failiure
1310 static int ALSA_ScanDevices(int directhw,
1311 long defctlcard, long defpcmcard, long defpcmdev,
1312 int fixedctlcard, int fixedpcmcard, int fixedpcmdev)
1314 int card = fixedpcmcard;
1315 int scan_devices = (fixedpcmdev == -1);
1317 /*------------------------------------------------------------------------
1318 ** Loop through all available cards
1319 **----------------------------------------------------------------------*/
1321 snd_card_next(&card);
1323 for (; card != -1; snd_card_next(&card))
1330 /*--------------------------------------------------------------------
1331 ** Try to open a ctl handle; Wine doesn't absolutely require one,
1332 ** but it does allow for volume control and for device scanning
1333 **------------------------------------------------------------------*/
1334 sprintf(ctlname, "default:%d", fixedctlcard == -1 ? card : fixedctlcard);
1335 rc = snd_ctl_open(&ctl, ctlname, SND_CTL_NONBLOCK);
1338 sprintf(ctlname, "hw:%d", fixedctlcard == -1 ? card : fixedctlcard);
1339 rc = snd_ctl_open(&ctl, ctlname, SND_CTL_NONBLOCK);
1344 WARN("Unable to open an alsa ctl for [%s] (pcm card %d): %s; not scanning devices\n",
1345 ctlname, card, snd_strerror(rc));
1346 if (fixedpcmdev == -1)
1350 /*--------------------------------------------------------------------
1351 ** Loop through all available devices on this card
1352 **------------------------------------------------------------------*/
1353 device = fixedpcmdev;
1355 snd_ctl_pcm_next_device(ctl, &device);
1357 for (; device != -1; snd_ctl_pcm_next_device(ctl, &device))
1359 char defaultpcmname[256];
1360 char plugpcmname[256];
1361 char hwpcmname[256];
1362 char *pcmname = NULL;
1365 sprintf(defaultpcmname, "default:%d", card);
1366 sprintf(plugpcmname, "plughw:%d,%d", card, device);
1367 sprintf(hwpcmname, "hw:%d,%d", card, device);
1369 /*----------------------------------------------------------------
1370 ** See if it's a valid playback device
1371 **--------------------------------------------------------------*/
1372 if (ALSA_TestDeviceForWine(card, device, SND_PCM_STREAM_PLAYBACK) == 0)
1374 /* If we can, try the default:X device name first */
1375 if (! scan_devices && ! directhw)
1377 pcmname = defaultpcmname;
1378 rc = snd_pcm_open(&pcm, pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
1385 pcmname = directhw ? hwpcmname : plugpcmname;
1386 rc = snd_pcm_open(&pcm, pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
1391 if (defctlcard == card && defpcmcard == card && defpcmdev == device)
1392 ALSA_AddPlaybackDevice(ctl, pcm, pcmname, TRUE);
1394 ALSA_AddPlaybackDevice(ctl, pcm, pcmname, FALSE);
1399 TRACE("Device [%s/%s] failed to open for playback: %s\n",
1400 directhw || scan_devices ? "(N/A)" : defaultpcmname,
1401 directhw ? hwpcmname : plugpcmname,
1406 /*----------------------------------------------------------------
1407 ** See if it's a valid capture device
1408 **--------------------------------------------------------------*/
1409 if (ALSA_TestDeviceForWine(card, device, SND_PCM_STREAM_CAPTURE) == 0)
1411 /* If we can, try the default:X device name first */
1412 if (! scan_devices && ! directhw)
1414 pcmname = defaultpcmname;
1415 rc = snd_pcm_open(&pcm, pcmname, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
1422 pcmname = directhw ? hwpcmname : plugpcmname;
1423 rc = snd_pcm_open(&pcm, pcmname, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
1428 if (defctlcard == card && defpcmcard == card && defpcmdev == device)
1429 ALSA_AddCaptureDevice(ctl, pcm, pcmname, TRUE);
1431 ALSA_AddCaptureDevice(ctl, pcm, pcmname, FALSE);
1437 TRACE("Device [%s/%s] failed to open for capture: %s\n",
1438 directhw || scan_devices ? "(N/A)" : defaultpcmname,
1439 directhw ? hwpcmname : plugpcmname,
1451 /*--------------------------------------------------------------------
1452 ** If the user has set env variables such that we're pegged to
1453 ** a specific card, then break after we've examined it
1454 **------------------------------------------------------------------*/
1455 if (fixedpcmcard != -1)
1463 /*----------------------------------------------------------------------------
1464 ** ALSA_PerformDefaultScan
1465 ** Perform the basic default scanning for devices within ALSA.
1466 ** The hope is that this routine implements a 'correct'
1467 ** scanning algorithm from the Alsalib point of view.
1469 ** Note that Wine, overall, has other mechanisms to
1470 ** override and specify exact CTL and PCM device names,
1471 ** but this routine is imagined as the default that
1472 ** 99% of users will use.
1474 ** The basic algorithm is simple:
1475 ** Use snd_card_next to iterate cards; within cards, use
1476 ** snd_ctl_pcm_next_device to iterate through devices.
1478 ** We add a little complexity by taking into consideration
1479 ** environment variables such as ALSA_CARD (et all), and by
1480 ** detecting when a given device matches the default specified
1484 ** directhw If !0, indicates we should use the hw:X
1485 ** PCM interface, rather than first try
1486 ** the 'default' device followed by the plughw
1487 ** device. (default and plughw do fancy mixing
1488 ** and audio scaling, if they are available).
1489 ** devscan If TRUE, we should scan all devices, not
1490 ** juse use device 0 on each card
1496 ** Invokes the ALSA_AddXXXDevice functions on valid
1499 static int ALSA_PerformDefaultScan(int directhw, BOOL devscan)
1501 long defctlcard = -1, defpcmcard = -1, defpcmdev = -1;
1502 int fixedctlcard = -1, fixedpcmcard = -1, fixedpcmdev = -1;
1505 /* FIXME: We should dlsym the new snd_names_list/snd_names_list_free 1.0.9 apis,
1506 ** and use them instead of this scan mechanism if they are present */
1508 rc = ALSA_DefaultDevices(directhw, &defctlcard, &defpcmcard, &defpcmdev,
1509 &fixedctlcard, &fixedpcmcard, &fixedpcmdev);
1513 if (fixedpcmdev == -1 && ! devscan)
1516 return(ALSA_ScanDevices(directhw, defctlcard, defpcmcard, defpcmdev, fixedctlcard, fixedpcmcard, fixedpcmdev));
1520 /*----------------------------------------------------------------------------
1521 ** ALSA_AddUserSpecifiedDevice
1522 ** Add a device given from the registry
1524 static int ALSA_AddUserSpecifiedDevice(const char *ctlname, const char *pcmname)
1528 snd_ctl_t *ctl = NULL;
1529 snd_pcm_t *pcm = NULL;
1533 rc = snd_ctl_open(&ctl, ctlname, SND_CTL_NONBLOCK);
1538 rc = snd_pcm_open(&pcm, pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
1541 ALSA_AddPlaybackDevice(ctl, pcm, pcmname, FALSE);
1546 rc = snd_pcm_open(&pcm, pcmname, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
1549 ALSA_AddCaptureDevice(ctl, pcm, pcmname, FALSE);
1561 /*----------------------------------------------------------------------------
1563 ** Initialize the Wine Alsa sub system.
1564 ** The main task is to probe for and store a list of all appropriate playback
1565 ** and capture devices.
1566 ** Key control points are from the registry key:
1567 ** [Software\Wine\Alsa Driver]
1568 ** AutoScanCards Whether or not to scan all known sound cards
1569 ** and add them to Wine's list (default yes)
1570 ** AutoScanDevices Whether or not to scan all known PCM devices
1571 ** on each card (default no)
1572 ** UseDirectHW Whether or not to use the hw:X device,
1573 ** instead of the fancy default:X or plughw:X device.
1574 ** The hw:X device goes straight to the hardware
1575 ** without any fancy mixing or audio scaling in between.
1576 ** DeviceCount If present, specifies the number of hard coded
1577 ** Alsa devices to add to Wine's list; default 0
1578 ** DevicePCMn Specifies the Alsa PCM devices to open for
1579 ** Device n (where n goes from 1 to DeviceCount)
1580 ** DeviceCTLn Specifies the Alsa control devices to open for
1581 ** Device n (where n goes from 1 to DeviceCount)
1583 ** Using AutoScanCards no, and then Devicexxx info
1584 ** is a way to exactly specify the devices used by Wine.
1587 LONG ALSA_WaveInit(void)
1590 BOOL AutoScanCards = TRUE;
1591 BOOL AutoScanDevices = FALSE;
1592 BOOL UseDirectHW = FALSE;
1593 DWORD DeviceCount = 0;
1597 if (!wine_dlopen("libasound.so.2", RTLD_LAZY|RTLD_GLOBAL, NULL, 0))
1599 ERR("Error: ALSA lib needs to be loaded with flags RTLD_LAZY and RTLD_GLOBAL.\n");
1603 /* @@ Wine registry key: HKCU\Software\Wine\Alsa Driver */
1604 rc = RegOpenKeyExA(HKEY_CURRENT_USER, "Software\\Wine\\Alsa Driver", 0, KEY_QUERY_VALUE, &key);
1605 if (rc == ERROR_SUCCESS)
1607 ALSA_RegGetBoolean(key, "AutoScanCards", &AutoScanCards);
1608 ALSA_RegGetBoolean(key, "AutoScanDevices", &AutoScanDevices);
1609 ALSA_RegGetBoolean(key, "UseDirectHW", &UseDirectHW);
1610 ALSA_RegGetInt(key, "DeviceCount", &DeviceCount);
1614 rc = ALSA_PerformDefaultScan(UseDirectHW, AutoScanDevices);
1616 for (i = 0; i < DeviceCount; i++)
1618 char *ctl_name = NULL;
1619 char *pcm_name = NULL;
1622 sprintf(value, "DevicePCM%d", i + 1);
1623 if (ALSA_RegGetString(key, value, &pcm_name) == ERROR_SUCCESS)
1625 sprintf(value, "DeviceCTL%d", i + 1);
1626 ALSA_RegGetString(key, value, &ctl_name);
1627 ALSA_AddUserSpecifiedDevice(ctl_name, pcm_name);
1631 HeapFree(GetProcessHeap(), 0, ctl_name);
1634 HeapFree(GetProcessHeap(), 0, pcm_name);
1643 /******************************************************************
1644 * ALSA_InitRingMessage
1646 * Initialize the ring of messages for passing between driver's caller and playback/record
1649 static int ALSA_InitRingMessage(ALSA_MSG_RING* omr)
1652 omr->msg_tosave = 0;
1653 #ifdef USE_PIPE_SYNC
1654 if (pipe(omr->msg_pipe) < 0) {
1655 omr->msg_pipe[0] = -1;
1656 omr->msg_pipe[1] = -1;
1657 ERR("could not create pipe, error=%s\n", strerror(errno));
1660 omr->msg_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1662 omr->ring_buffer_size = ALSA_RING_BUFFER_INCREMENT;
1663 omr->messages = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,omr->ring_buffer_size * sizeof(ALSA_MSG));
1665 InitializeCriticalSection(&omr->msg_crst);
1666 omr->msg_crst.DebugInfo->Spare[0] = (DWORD_PTR)"WINEALSA_msg_crst";
1670 /******************************************************************
1671 * ALSA_DestroyRingMessage
1674 static int ALSA_DestroyRingMessage(ALSA_MSG_RING* omr)
1676 #ifdef USE_PIPE_SYNC
1677 close(omr->msg_pipe[0]);
1678 close(omr->msg_pipe[1]);
1680 CloseHandle(omr->msg_event);
1682 HeapFree(GetProcessHeap(),0,omr->messages);
1683 omr->ring_buffer_size = 0;
1684 omr->msg_crst.DebugInfo->Spare[0] = 0;
1685 DeleteCriticalSection(&omr->msg_crst);
1689 /******************************************************************
1690 * ALSA_AddRingMessage
1692 * Inserts a new message into the ring (should be called from DriverProc derivated routines)
1694 static int ALSA_AddRingMessage(ALSA_MSG_RING* omr, enum win_wm_message msg, DWORD param, BOOL wait)
1696 HANDLE hEvent = INVALID_HANDLE_VALUE;
1698 EnterCriticalSection(&omr->msg_crst);
1699 if ((omr->msg_toget == ((omr->msg_tosave + 1) % omr->ring_buffer_size)))
1701 int old_ring_buffer_size = omr->ring_buffer_size;
1702 omr->ring_buffer_size += ALSA_RING_BUFFER_INCREMENT;
1703 TRACE("omr->ring_buffer_size=%d\n",omr->ring_buffer_size);
1704 omr->messages = HeapReAlloc(GetProcessHeap(),0,omr->messages, omr->ring_buffer_size * sizeof(ALSA_MSG));
1705 /* Now we need to rearrange the ring buffer so that the new
1706 buffers just allocated are in between omr->msg_tosave and
1709 if (omr->msg_tosave < omr->msg_toget)
1711 memmove(&(omr->messages[omr->msg_toget + ALSA_RING_BUFFER_INCREMENT]),
1712 &(omr->messages[omr->msg_toget]),
1713 sizeof(ALSA_MSG)*(old_ring_buffer_size - omr->msg_toget)
1715 omr->msg_toget += ALSA_RING_BUFFER_INCREMENT;
1720 hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1721 if (hEvent == INVALID_HANDLE_VALUE)
1723 ERR("can't create event !?\n");
1724 LeaveCriticalSection(&omr->msg_crst);
1727 if (omr->msg_toget != omr->msg_tosave && omr->messages[omr->msg_toget].msg != WINE_WM_HEADER)
1728 FIXME("two fast messages in the queue!!!! toget = %d(%s), tosave=%d(%s)\n",
1729 omr->msg_toget,getCmdString(omr->messages[omr->msg_toget].msg),
1730 omr->msg_tosave,getCmdString(omr->messages[omr->msg_tosave].msg));
1732 /* fast messages have to be added at the start of the queue */
1733 omr->msg_toget = (omr->msg_toget + omr->ring_buffer_size - 1) % omr->ring_buffer_size;
1735 omr->messages[omr->msg_toget].msg = msg;
1736 omr->messages[omr->msg_toget].param = param;
1737 omr->messages[omr->msg_toget].hEvent = hEvent;
1741 omr->messages[omr->msg_tosave].msg = msg;
1742 omr->messages[omr->msg_tosave].param = param;
1743 omr->messages[omr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
1744 omr->msg_tosave = (omr->msg_tosave + 1) % omr->ring_buffer_size;
1746 LeaveCriticalSection(&omr->msg_crst);
1747 /* signal a new message */
1751 /* wait for playback/record thread to have processed the message */
1752 WaitForSingleObject(hEvent, INFINITE);
1753 CloseHandle(hEvent);
1758 /******************************************************************
1759 * ALSA_RetrieveRingMessage
1761 * Get a message from the ring. Should be called by the playback/record thread.
1763 static int ALSA_RetrieveRingMessage(ALSA_MSG_RING* omr,
1764 enum win_wm_message *msg, DWORD *param, HANDLE *hEvent)
1766 EnterCriticalSection(&omr->msg_crst);
1768 if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
1770 LeaveCriticalSection(&omr->msg_crst);
1774 *msg = omr->messages[omr->msg_toget].msg;
1775 omr->messages[omr->msg_toget].msg = 0;
1776 *param = omr->messages[omr->msg_toget].param;
1777 *hEvent = omr->messages[omr->msg_toget].hEvent;
1778 omr->msg_toget = (omr->msg_toget + 1) % omr->ring_buffer_size;
1780 LeaveCriticalSection(&omr->msg_crst);
1784 /******************************************************************
1785 * ALSA_PeekRingMessage
1787 * Peek at a message from the ring but do not remove it.
1788 * Should be called by the playback/record thread.
1790 static int ALSA_PeekRingMessage(ALSA_MSG_RING* omr,
1791 enum win_wm_message *msg,
1792 DWORD *param, HANDLE *hEvent)
1794 EnterCriticalSection(&omr->msg_crst);
1796 if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
1798 LeaveCriticalSection(&omr->msg_crst);
1802 *msg = omr->messages[omr->msg_toget].msg;
1803 *param = omr->messages[omr->msg_toget].param;
1804 *hEvent = omr->messages[omr->msg_toget].hEvent;
1805 LeaveCriticalSection(&omr->msg_crst);
1809 /*======================================================================*
1810 * Low level WAVE OUT implementation *
1811 *======================================================================*/
1813 /**************************************************************************
1814 * wodNotifyClient [internal]
1816 static DWORD wodNotifyClient(WINE_WAVEDEV* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1818 TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
1824 if (wwo->wFlags != DCB_NULL &&
1825 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags, (HDRVR)wwo->waveDesc.hWave,
1826 wMsg, wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
1827 WARN("can't notify client !\n");
1828 return MMSYSERR_ERROR;
1832 FIXME("Unknown callback message %u\n", wMsg);
1833 return MMSYSERR_INVALPARAM;
1835 return MMSYSERR_NOERROR;
1838 /**************************************************************************
1839 * wodUpdatePlayedTotal [internal]
1842 static BOOL wodUpdatePlayedTotal(WINE_WAVEDEV* wwo, snd_pcm_status_t* ps)
1844 snd_pcm_sframes_t delay = 0;
1845 snd_pcm_state_t state;
1847 state = snd_pcm_state(wwo->pcm);
1848 snd_pcm_delay(wwo->pcm, &delay);
1850 /* A delay < 0 indicates an underrun; for our purposes that's 0. */
1851 if ( (state != SND_PCM_STATE_RUNNING && state != SND_PCM_STATE_PREPARED) || (delay < 0))
1853 WARN("Unexpected state (%d) or delay (%ld) while updating Total Played, resetting\n", state, delay);
1856 wwo->dwPlayedTotal = wwo->dwWrittenTotal - snd_pcm_frames_to_bytes(wwo->pcm, delay);
1860 /**************************************************************************
1861 * wodPlayer_BeginWaveHdr [internal]
1863 * Makes the specified lpWaveHdr the currently playing wave header.
1864 * If the specified wave header is a begin loop and we're not already in
1865 * a loop, setup the loop.
1867 static void wodPlayer_BeginWaveHdr(WINE_WAVEDEV* wwo, LPWAVEHDR lpWaveHdr)
1869 wwo->lpPlayPtr = lpWaveHdr;
1871 if (!lpWaveHdr) return;
1873 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
1874 if (wwo->lpLoopPtr) {
1875 WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1877 TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1878 wwo->lpLoopPtr = lpWaveHdr;
1879 /* Windows does not touch WAVEHDR.dwLoops,
1880 * so we need to make an internal copy */
1881 wwo->dwLoops = lpWaveHdr->dwLoops;
1884 wwo->dwPartialOffset = 0;
1887 /**************************************************************************
1888 * wodPlayer_PlayPtrNext [internal]
1890 * Advance the play pointer to the next waveheader, looping if required.
1892 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEDEV* wwo)
1894 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1896 wwo->dwPartialOffset = 0;
1897 if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
1898 /* We're at the end of a loop, loop if required */
1899 if (--wwo->dwLoops > 0) {
1900 wwo->lpPlayPtr = wwo->lpLoopPtr;
1902 /* Handle overlapping loops correctly */
1903 if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
1904 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
1905 /* shall we consider the END flag for the closing loop or for
1906 * the opening one or for both ???
1907 * code assumes for closing loop only
1910 lpWaveHdr = lpWaveHdr->lpNext;
1912 wwo->lpLoopPtr = NULL;
1913 wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
1916 /* We're not in a loop. Advance to the next wave header */
1917 wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
1923 /**************************************************************************
1924 * wodPlayer_DSPWait [internal]
1925 * Returns the number of milliseconds to wait for the DSP buffer to play a
1928 static DWORD wodPlayer_DSPWait(const WINE_WAVEDEV *wwo)
1930 /* time for one period to be played */
1934 err = snd_pcm_hw_params_get_period_time(wwo->hw_params, &val, &dir);
1938 /**************************************************************************
1939 * wodPlayer_NotifyWait [internal]
1940 * Returns the number of milliseconds to wait before attempting to notify
1941 * completion of the specified wavehdr.
1942 * This is based on the number of bytes remaining to be written in the
1945 static DWORD wodPlayer_NotifyWait(const WINE_WAVEDEV* wwo, LPWAVEHDR lpWaveHdr)
1949 if (lpWaveHdr->reserved < wwo->dwPlayedTotal) {
1952 dwMillis = (lpWaveHdr->reserved - wwo->dwPlayedTotal) * 1000 / wwo->format.Format.nAvgBytesPerSec;
1953 if (!dwMillis) dwMillis = 1;
1960 /**************************************************************************
1961 * wodPlayer_WriteMaxFrags [internal]
1962 * Writes the maximum number of frames possible to the DSP and returns
1963 * the number of frames written.
1965 static int wodPlayer_WriteMaxFrags(WINE_WAVEDEV* wwo, DWORD* frames)
1967 /* Only attempt to write to free frames */
1968 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1969 DWORD dwLength = snd_pcm_bytes_to_frames(wwo->pcm, lpWaveHdr->dwBufferLength - wwo->dwPartialOffset);
1970 int toWrite = min(dwLength, *frames);
1973 TRACE("Writing wavehdr %p.%lu[%lu]\n", lpWaveHdr, wwo->dwPartialOffset, lpWaveHdr->dwBufferLength);
1976 written = (wwo->write)(wwo->pcm, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
1978 /* XRUN occurred. let's try to recover */
1979 ALSA_XRUNRecovery(wwo, written);
1980 written = (wwo->write)(wwo->pcm, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
1983 /* still in error */
1984 ERR("Error in writing wavehdr. Reason: %s\n", snd_strerror(written));
1990 wwo->dwPartialOffset += snd_pcm_frames_to_bytes(wwo->pcm, written);
1991 if ( wwo->dwPartialOffset >= lpWaveHdr->dwBufferLength) {
1992 /* this will be used to check if the given wave header has been fully played or not... */
1993 wwo->dwPartialOffset = lpWaveHdr->dwBufferLength;
1994 /* If we wrote all current wavehdr, skip to the next one */
1995 wodPlayer_PlayPtrNext(wwo);
1998 wwo->dwWrittenTotal += snd_pcm_frames_to_bytes(wwo->pcm, written);
1999 TRACE("dwWrittenTotal=%lu\n", wwo->dwWrittenTotal);
2005 /**************************************************************************
2006 * wodPlayer_NotifyCompletions [internal]
2008 * Notifies and remove from queue all wavehdrs which have been played to
2009 * the speaker (ie. they have cleared the ALSA buffer). If force is true,
2010 * we notify all wavehdrs and remove them all from the queue even if they
2011 * are unplayed or part of a loop.
2013 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEDEV* wwo, BOOL force)
2015 LPWAVEHDR lpWaveHdr;
2017 /* Start from lpQueuePtr and keep notifying until:
2018 * - we hit an unwritten wavehdr
2019 * - we hit the beginning of a running loop
2020 * - we hit a wavehdr which hasn't finished playing
2023 while ((lpWaveHdr = wwo->lpQueuePtr) &&
2025 (lpWaveHdr != wwo->lpPlayPtr &&
2026 lpWaveHdr != wwo->lpLoopPtr &&
2027 lpWaveHdr->reserved <= wwo->dwPlayedTotal))) {
2029 wwo->lpQueuePtr = lpWaveHdr->lpNext;
2031 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2032 lpWaveHdr->dwFlags |= WHDR_DONE;
2034 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
2039 lpWaveHdr = wwo->lpQueuePtr;
2040 if (!lpWaveHdr) {TRACE("Empty queue\n"); break;}
2043 if (lpWaveHdr == wwo->lpPlayPtr) {TRACE("play %p\n", lpWaveHdr); break;}
2044 if (lpWaveHdr == wwo->lpLoopPtr) {TRACE("loop %p\n", lpWaveHdr); break;}
2045 if (lpWaveHdr->reserved > wwo->dwPlayedTotal){TRACE("still playing %p (%lu/%lu)\n", lpWaveHdr, lpWaveHdr->reserved, wwo->dwPlayedTotal);break;}
2047 wwo->lpQueuePtr = lpWaveHdr->lpNext;
2049 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2050 lpWaveHdr->dwFlags |= WHDR_DONE;
2052 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
2055 return (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
2056 wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
2060 /**************************************************************************
2061 * wodPlayer_Reset [internal]
2063 * wodPlayer helper. Resets current output stream.
2065 static void wodPlayer_Reset(WINE_WAVEDEV* wwo)
2067 enum win_wm_message msg;
2071 TRACE("(%p)\n", wwo);
2073 /* flush all possible output */
2074 snd_pcm_drain(wwo->pcm);
2076 wodUpdatePlayedTotal(wwo, NULL);
2077 /* updates current notify list */
2078 wodPlayer_NotifyCompletions(wwo, FALSE);
2080 if ( (err = snd_pcm_drop(wwo->pcm)) < 0) {
2081 FIXME("flush: %s\n", snd_strerror(err));
2083 wwo->state = WINE_WS_STOPPED;
2086 if ( (err = snd_pcm_prepare(wwo->pcm)) < 0 )
2087 ERR("pcm prepare failed: %s\n", snd_strerror(err));
2089 /* remove any buffer */
2090 wodPlayer_NotifyCompletions(wwo, TRUE);
2092 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
2093 wwo->state = WINE_WS_STOPPED;
2094 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
2095 /* Clear partial wavehdr */
2096 wwo->dwPartialOffset = 0;
2098 /* remove any existing message in the ring */
2099 EnterCriticalSection(&wwo->msgRing.msg_crst);
2100 /* return all pending headers in queue */
2101 while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, ¶m, &ev))
2103 if (msg != WINE_WM_HEADER)
2105 FIXME("shouldn't have headers left\n");
2109 ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
2110 ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
2112 wodNotifyClient(wwo, WOM_DONE, param, 0);
2114 RESET_OMR(&wwo->msgRing);
2115 LeaveCriticalSection(&wwo->msgRing.msg_crst);
2118 /**************************************************************************
2119 * wodPlayer_ProcessMessages [internal]
2121 static void wodPlayer_ProcessMessages(WINE_WAVEDEV* wwo)
2123 LPWAVEHDR lpWaveHdr;
2124 enum win_wm_message msg;
2129 while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, ¶m, &ev)) {
2130 TRACE("Received %s %lx\n", getCmdString(msg), param);
2133 case WINE_WM_PAUSING:
2134 if ( snd_pcm_state(wwo->pcm) == SND_PCM_STATE_RUNNING )
2136 err = snd_pcm_pause(wwo->pcm, 1);
2138 ERR("pcm_pause failed: %s\n", snd_strerror(err));
2140 wwo->state = WINE_WS_PAUSED;
2143 case WINE_WM_RESTARTING:
2144 if (wwo->state == WINE_WS_PAUSED)
2146 if ( snd_pcm_state(wwo->pcm) == SND_PCM_STATE_PAUSED )
2148 err = snd_pcm_pause(wwo->pcm, 0);
2150 ERR("pcm_pause failed: %s\n", snd_strerror(err));
2152 wwo->state = WINE_WS_PLAYING;
2156 case WINE_WM_HEADER:
2157 lpWaveHdr = (LPWAVEHDR)param;
2159 /* insert buffer at the end of queue */
2162 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2165 if (!wwo->lpPlayPtr)
2166 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
2167 if (wwo->state == WINE_WS_STOPPED)
2168 wwo->state = WINE_WS_PLAYING;
2170 case WINE_WM_RESETTING:
2171 wodPlayer_Reset(wwo);
2174 case WINE_WM_UPDATE:
2175 wodUpdatePlayedTotal(wwo, NULL);
2178 case WINE_WM_BREAKLOOP:
2179 if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
2180 /* ensure exit at end of current loop */
2185 case WINE_WM_CLOSING:
2186 /* sanity check: this should not happen since the device must have been reset before */
2187 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
2189 wwo->state = WINE_WS_CLOSED;
2192 /* shouldn't go here */
2194 FIXME("unknown message %d\n", msg);
2200 /**************************************************************************
2201 * wodPlayer_FeedDSP [internal]
2202 * Feed as much sound data as we can into the DSP and return the number of
2203 * milliseconds before it will be necessary to feed the DSP again.
2205 static DWORD wodPlayer_FeedDSP(WINE_WAVEDEV* wwo)
2209 wodUpdatePlayedTotal(wwo, NULL);
2210 availInQ = snd_pcm_avail_update(wwo->pcm);
2213 /* input queue empty and output buffer with less than one fragment to play */
2214 if (!wwo->lpPlayPtr && wwo->dwBufferSize < availInQ + wwo->dwFragmentSize) {
2215 TRACE("Run out of wavehdr:s...\n");
2219 /* no more room... no need to try to feed */
2221 /* Feed from partial wavehdr */
2222 if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0) {
2223 wodPlayer_WriteMaxFrags(wwo, &availInQ);
2226 /* Feed wavehdrs until we run out of wavehdrs or DSP space */
2227 if (wwo->dwPartialOffset == 0 && wwo->lpPlayPtr) {
2229 TRACE("Setting time to elapse for %p to %lu\n",
2230 wwo->lpPlayPtr, wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength);
2231 /* note the value that dwPlayedTotal will return when this wave finishes playing */
2232 wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
2233 } while (wodPlayer_WriteMaxFrags(wwo, &availInQ) && wwo->lpPlayPtr && availInQ > 0);
2237 return wodPlayer_DSPWait(wwo);
2240 /**************************************************************************
2241 * wodPlayer [internal]
2243 static DWORD CALLBACK wodPlayer(LPVOID pmt)
2245 WORD uDevID = (DWORD)pmt;
2246 WINE_WAVEDEV* wwo = (WINE_WAVEDEV*)&WOutDev[uDevID];
2247 DWORD dwNextFeedTime = INFINITE; /* Time before DSP needs feeding */
2248 DWORD dwNextNotifyTime = INFINITE; /* Time before next wave completion */
2251 wwo->state = WINE_WS_STOPPED;
2252 SetEvent(wwo->hStartUpEvent);
2255 /** Wait for the shortest time before an action is required. If there
2256 * are no pending actions, wait forever for a command.
2258 dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
2259 TRACE("waiting %lums (%lu,%lu)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
2260 WAIT_OMR(&wwo->msgRing, dwSleepTime);
2261 wodPlayer_ProcessMessages(wwo);
2262 if (wwo->state == WINE_WS_PLAYING) {
2263 dwNextFeedTime = wodPlayer_FeedDSP(wwo);
2264 dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
2265 if (dwNextFeedTime == INFINITE) {
2266 /* FeedDSP ran out of data, but before giving up, */
2267 /* check that a notification didn't give us more */
2268 wodPlayer_ProcessMessages(wwo);
2269 if (wwo->lpPlayPtr) {
2270 TRACE("recovering\n");
2271 dwNextFeedTime = wodPlayer_FeedDSP(wwo);
2275 dwNextFeedTime = dwNextNotifyTime = INFINITE;
2280 /**************************************************************************
2281 * wodGetDevCaps [internal]
2283 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
2285 TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
2287 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
2289 if (wDevID >= ALSA_WodNumDevs) {
2290 TRACE("Asked for device %d, but only %ld known!\n", wDevID, ALSA_WodNumDevs);
2291 return MMSYSERR_BADDEVICEID;
2294 memcpy(lpCaps, &WOutDev[wDevID].outcaps, min(dwSize, sizeof(*lpCaps)));
2295 return MMSYSERR_NOERROR;
2298 /**************************************************************************
2299 * wodOpen [internal]
2301 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
2304 snd_pcm_t * pcm = NULL;
2305 snd_hctl_t * hctl = NULL;
2306 snd_pcm_hw_params_t * hw_params = NULL;
2307 snd_pcm_sw_params_t * sw_params;
2308 snd_pcm_access_t access;
2309 snd_pcm_format_t format = -1;
2311 unsigned int buffer_time = 500000;
2312 unsigned int period_time = 10000;
2313 snd_pcm_uframes_t buffer_size;
2314 snd_pcm_uframes_t period_size;
2320 snd_pcm_sw_params_alloca(&sw_params);
2322 TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
2323 if (lpDesc == NULL) {
2324 WARN("Invalid Parameter !\n");
2325 return MMSYSERR_INVALPARAM;
2327 if (wDevID >= ALSA_WodNumDevs) {
2328 TRACE("Asked for device %d, but only %ld known!\n", wDevID, ALSA_WodNumDevs);
2329 return MMSYSERR_BADDEVICEID;
2332 /* only PCM format is supported so far... */
2333 if (!supportedFormat(lpDesc->lpFormat)) {
2334 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
2335 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
2336 lpDesc->lpFormat->nSamplesPerSec);
2337 return WAVERR_BADFORMAT;
2340 if (dwFlags & WAVE_FORMAT_QUERY) {
2341 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
2342 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
2343 lpDesc->lpFormat->nSamplesPerSec);
2344 return MMSYSERR_NOERROR;
2347 wwo = &WOutDev[wDevID];
2349 if (wwo->pcm != NULL) {
2350 WARN("%d already allocated\n", wDevID);
2351 return MMSYSERR_ALLOCATED;
2354 if ((dwFlags & WAVE_DIRECTSOUND) && !(wwo->outcaps.dwSupport & WAVECAPS_DIRECTSOUND))
2355 /* not supported, ignore it */
2356 dwFlags &= ~WAVE_DIRECTSOUND;
2358 flags = SND_PCM_NONBLOCK;
2360 /* FIXME - why is this ifdefed? */
2362 if ( dwFlags & WAVE_DIRECTSOUND )
2363 flags |= SND_PCM_ASYNC;
2366 if ( (err = snd_pcm_open(&pcm, wwo->pcmname, SND_PCM_STREAM_PLAYBACK, flags)) < 0)
2368 ERR("Error open: %s\n", snd_strerror(err));
2369 return MMSYSERR_NOTENABLED;
2374 err = snd_hctl_open(&hctl, wwo->ctlname, 0);
2377 snd_hctl_load(hctl);
2381 WARN("Could not open hctl for [%s]: %s\n", wwo->ctlname, snd_strerror(err));
2386 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
2388 memcpy(&wwo->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
2389 copy_format(lpDesc->lpFormat, &wwo->format);
2391 TRACE("Requested this format: %ldx%dx%d %s\n",
2392 wwo->format.Format.nSamplesPerSec,
2393 wwo->format.Format.wBitsPerSample,
2394 wwo->format.Format.nChannels,
2395 getFormat(wwo->format.Format.wFormatTag));
2397 if (wwo->format.Format.wBitsPerSample == 0) {
2398 WARN("Resetting zeroed wBitsPerSample\n");
2399 wwo->format.Format.wBitsPerSample = 8 *
2400 (wwo->format.Format.nAvgBytesPerSec /
2401 wwo->format.Format.nSamplesPerSec) /
2402 wwo->format.Format.nChannels;
2405 #define EXIT_ON_ERROR(f,e,txt) do \
2408 if ( (err = (f) ) < 0) \
2410 WARN(txt ": %s\n", snd_strerror(err)); \
2416 snd_pcm_hw_params_malloc(&hw_params);
2419 retcode = MMSYSERR_NOMEM;
2422 snd_pcm_hw_params_any(pcm, hw_params);
2424 access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
2425 if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
2426 WARN("mmap not available. switching to standard write.\n");
2427 access = SND_PCM_ACCESS_RW_INTERLEAVED;
2428 EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
2429 wwo->write = snd_pcm_writei;
2432 wwo->write = snd_pcm_mmap_writei;
2434 if ((err = snd_pcm_hw_params_set_channels(pcm, hw_params, wwo->format.Format.nChannels)) < 0) {
2435 WARN("unable to set required channels: %d\n", wwo->format.Format.nChannels);
2436 if (dwFlags & WAVE_DIRECTSOUND) {
2437 if (wwo->format.Format.nChannels > 2)
2438 wwo->format.Format.nChannels = 2;
2439 else if (wwo->format.Format.nChannels == 2)
2440 wwo->format.Format.nChannels = 1;
2441 else if (wwo->format.Format.nChannels == 1)
2442 wwo->format.Format.nChannels = 2;
2443 /* recalculate block align and bytes per second */
2444 wwo->format.Format.nBlockAlign = (wwo->format.Format.wBitsPerSample * wwo->format.Format.nChannels) / 8;
2445 wwo->format.Format.nAvgBytesPerSec = wwo->format.Format.nSamplesPerSec * wwo->format.Format.nBlockAlign;
2446 WARN("changed number of channels from %d to %d\n", lpDesc->lpFormat->nChannels, wwo->format.Format.nChannels);
2448 EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwo->format.Format.nChannels ), WAVERR_BADFORMAT, "unable to set required channels" );
2451 if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
2452 ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
2453 IsEqualGUID(&wwo->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
2454 format = (wwo->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
2455 (wwo->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
2456 (wwo->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
2457 (wwo->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
2458 } else if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
2459 IsEqualGUID(&wwo->format.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)){
2460 format = (wwo->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_FLOAT_LE : -1;
2461 } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
2462 FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
2463 retcode = WAVERR_BADFORMAT;
2465 } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
2466 FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
2467 retcode = WAVERR_BADFORMAT;
2469 } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
2470 FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
2471 retcode = WAVERR_BADFORMAT;
2474 ERR("invalid format: %0x04x\n", wwo->format.Format.wFormatTag);
2475 retcode = WAVERR_BADFORMAT;
2479 if ((err = snd_pcm_hw_params_set_format(pcm, hw_params, format)) < 0) {
2480 WARN("unable to set required format: %s\n", snd_pcm_format_name(format));
2481 if (dwFlags & WAVE_DIRECTSOUND) {
2482 if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
2483 ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
2484 IsEqualGUID(&wwo->format.SubFormat, & KSDATAFORMAT_SUBTYPE_PCM))) {
2485 if (wwo->format.Format.wBitsPerSample != 16) {
2486 wwo->format.Format.wBitsPerSample = 16;
2487 format = SND_PCM_FORMAT_S16_LE;
2489 wwo->format.Format.wBitsPerSample = 8;
2490 format = SND_PCM_FORMAT_U8;
2492 /* recalculate block align and bytes per second */
2493 wwo->format.Format.nBlockAlign = (wwo->format.Format.wBitsPerSample * wwo->format.Format.nChannels) / 8;
2494 wwo->format.Format.nAvgBytesPerSec = wwo->format.Format.nSamplesPerSec * wwo->format.Format.nBlockAlign;
2495 WARN("changed bits per sample from %d to %d\n", lpDesc->lpFormat->wBitsPerSample, wwo->format.Format.wBitsPerSample);
2498 EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), WAVERR_BADFORMAT, "unable to set required format" );
2501 rate = wwo->format.Format.nSamplesPerSec;
2503 err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
2505 WARN("Rate %ld Hz not available for playback: %s\n", wwo->format.Format.nSamplesPerSec, snd_strerror(rate));
2506 retcode = WAVERR_BADFORMAT;
2509 if (!NearMatch(rate, wwo->format.Format.nSamplesPerSec)) {
2510 if (dwFlags & WAVE_DIRECTSOUND) {
2511 WARN("changed sample rate from %ld Hz to %d Hz\n", wwo->format.Format.nSamplesPerSec, rate);
2512 wwo->format.Format.nSamplesPerSec = rate;
2513 /* recalculate bytes per second */
2514 wwo->format.Format.nAvgBytesPerSec = wwo->format.Format.nSamplesPerSec * wwo->format.Format.nBlockAlign;
2516 WARN("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwo->format.Format.nSamplesPerSec, rate);
2517 retcode = WAVERR_BADFORMAT;
2522 /* give the new format back to direct sound */
2523 if (dwFlags & WAVE_DIRECTSOUND) {
2524 lpDesc->lpFormat->wFormatTag = wwo->format.Format.wFormatTag;
2525 lpDesc->lpFormat->nChannels = wwo->format.Format.nChannels;
2526 lpDesc->lpFormat->nSamplesPerSec = wwo->format.Format.nSamplesPerSec;
2527 lpDesc->lpFormat->wBitsPerSample = wwo->format.Format.wBitsPerSample;
2528 lpDesc->lpFormat->nBlockAlign = wwo->format.Format.nBlockAlign;
2529 lpDesc->lpFormat->nAvgBytesPerSec = wwo->format.Format.nAvgBytesPerSec;
2532 TRACE("Got this format: %ldx%dx%d %s\n",
2533 wwo->format.Format.nSamplesPerSec,
2534 wwo->format.Format.wBitsPerSample,
2535 wwo->format.Format.nChannels,
2536 getFormat(wwo->format.Format.wFormatTag));
2539 EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
2541 EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
2543 EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
2545 err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
2546 err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
2548 snd_pcm_sw_params_current(pcm, sw_params);
2549 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");
2550 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
2551 EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
2552 EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
2553 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
2554 EXIT_ON_ERROR( snd_pcm_sw_params_set_xrun_mode(pcm, sw_params, SND_PCM_XRUN_NONE), MMSYSERR_ERROR, "unable to set xrun mode");
2555 EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
2556 #undef EXIT_ON_ERROR
2558 snd_pcm_prepare(pcm);
2561 ALSA_TraceParameters(hw_params, sw_params, FALSE);
2563 /* now, we can save all required data for later use... */
2565 wwo->dwBufferSize = snd_pcm_frames_to_bytes(pcm, buffer_size);
2566 wwo->lpQueuePtr = wwo->lpPlayPtr = wwo->lpLoopPtr = NULL;
2567 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
2568 wwo->dwPartialOffset = 0;
2570 ALSA_InitRingMessage(&wwo->msgRing);
2572 if (!(dwFlags & WAVE_DIRECTSOUND)) {
2573 wwo->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
2574 wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
2576 SetThreadPriority(wwo->hThread, THREAD_PRIORITY_TIME_CRITICAL);
2579 ERR("Thread creation for the wodPlayer failed!\n");
2580 CloseHandle(wwo->hStartUpEvent);
2581 retcode = MMSYSERR_NOMEM;
2584 WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
2585 CloseHandle(wwo->hStartUpEvent);
2587 wwo->hThread = INVALID_HANDLE_VALUE;
2588 wwo->dwThreadID = 0;
2590 wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
2592 TRACE("handle=%p\n", pcm);
2593 TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
2594 wwo->format.Format.wBitsPerSample, wwo->format.Format.nAvgBytesPerSec,
2595 wwo->format.Format.nSamplesPerSec, wwo->format.Format.nChannels,
2596 wwo->format.Format.nBlockAlign);
2600 if ( wwo->hw_params )
2601 snd_pcm_hw_params_free(wwo->hw_params);
2602 wwo->hw_params = hw_params;
2605 return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
2613 snd_hctl_free(hctl);
2614 snd_hctl_close(hctl);
2618 snd_pcm_hw_params_free(hw_params);
2620 if (wwo->msgRing.ring_buffer_size > 0)
2621 ALSA_DestroyRingMessage(&wwo->msgRing);
2627 /**************************************************************************
2628 * wodClose [internal]
2630 static DWORD wodClose(WORD wDevID)
2632 DWORD ret = MMSYSERR_NOERROR;
2635 TRACE("(%u);\n", wDevID);
2637 if (wDevID >= ALSA_WodNumDevs) {
2638 TRACE("Asked for device %d, but only %ld known!\n", wDevID, ALSA_WodNumDevs);
2639 return MMSYSERR_BADDEVICEID;
2642 if (WOutDev[wDevID].pcm == NULL) {
2643 WARN("Requested to close already closed device %d!\n", wDevID);
2644 return MMSYSERR_BADDEVICEID;
2647 wwo = &WOutDev[wDevID];
2648 if (wwo->lpQueuePtr) {
2649 WARN("buffers still playing !\n");
2650 ret = WAVERR_STILLPLAYING;
2652 if (wwo->hThread != INVALID_HANDLE_VALUE) {
2653 ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
2655 ALSA_DestroyRingMessage(&wwo->msgRing);
2658 snd_pcm_hw_params_free(wwo->hw_params);
2659 wwo->hw_params = NULL;
2662 snd_pcm_close(wwo->pcm);
2667 snd_hctl_free(wwo->hctl);
2668 snd_hctl_close(wwo->hctl);
2672 ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
2679 /**************************************************************************
2680 * wodWrite [internal]
2683 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2685 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2687 if (wDevID >= ALSA_WodNumDevs) {
2688 TRACE("Asked for device %d, but only %ld known!\n", wDevID, ALSA_WodNumDevs);
2689 return MMSYSERR_BADDEVICEID;
2692 if (WOutDev[wDevID].pcm == NULL) {
2693 WARN("Requested to write to closed device %d!\n", wDevID);
2694 return MMSYSERR_BADDEVICEID;
2697 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
2698 return WAVERR_UNPREPARED;
2700 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2701 return WAVERR_STILLPLAYING;
2703 lpWaveHdr->dwFlags &= ~WHDR_DONE;
2704 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2705 lpWaveHdr->lpNext = 0;
2707 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
2709 return MMSYSERR_NOERROR;
2712 /**************************************************************************
2713 * wodPause [internal]
2715 static DWORD wodPause(WORD wDevID)
2717 TRACE("(%u);!\n", wDevID);
2719 if (wDevID >= ALSA_WodNumDevs) {
2720 TRACE("Asked for device %d, but only %ld known!\n", wDevID, ALSA_WodNumDevs);
2721 return MMSYSERR_BADDEVICEID;
2724 if (WOutDev[wDevID].pcm == NULL) {
2725 WARN("Requested to pause closed device %d!\n", wDevID);
2726 return MMSYSERR_BADDEVICEID;
2729 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
2731 return MMSYSERR_NOERROR;
2734 /**************************************************************************
2735 * wodRestart [internal]
2737 static DWORD wodRestart(WORD wDevID)
2739 TRACE("(%u);\n", wDevID);
2741 if (wDevID >= ALSA_WodNumDevs) {
2742 TRACE("Asked for device %d, but only %ld known!\n", wDevID, ALSA_WodNumDevs);
2743 return MMSYSERR_BADDEVICEID;
2746 if (WOutDev[wDevID].pcm == NULL) {
2747 WARN("Requested to restart closed device %d!\n", wDevID);
2748 return MMSYSERR_BADDEVICEID;
2751 if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
2752 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
2755 /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
2756 /* FIXME: Myst crashes with this ... hmm -MM
2757 return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
2760 return MMSYSERR_NOERROR;
2763 /**************************************************************************
2764 * wodReset [internal]
2766 static DWORD wodReset(WORD wDevID)
2768 TRACE("(%u);\n", wDevID);
2770 if (wDevID >= ALSA_WodNumDevs) {
2771 TRACE("Asked for device %d, but only %ld known!\n", wDevID, ALSA_WodNumDevs);
2772 return MMSYSERR_BADDEVICEID;
2775 if (WOutDev[wDevID].pcm == NULL) {
2776 WARN("Requested to reset closed device %d!\n", wDevID);
2777 return MMSYSERR_BADDEVICEID;
2780 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
2782 return MMSYSERR_NOERROR;
2785 /**************************************************************************
2786 * wodGetPosition [internal]
2788 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
2792 TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
2794 if (wDevID >= ALSA_WodNumDevs) {
2795 TRACE("Asked for device %d, but only %ld known!\n", wDevID, ALSA_WodNumDevs);
2796 return MMSYSERR_BADDEVICEID;
2799 if (WOutDev[wDevID].pcm == NULL) {
2800 WARN("Requested to get position of closed device %d!\n", wDevID);
2801 return MMSYSERR_BADDEVICEID;
2804 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
2806 wwo = &WOutDev[wDevID];
2807 ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
2809 return bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->format);
2812 /**************************************************************************
2813 * wodBreakLoop [internal]
2815 static DWORD wodBreakLoop(WORD wDevID)
2817 TRACE("(%u);\n", wDevID);
2819 if (wDevID >= ALSA_WodNumDevs) {
2820 TRACE("Asked for device %d, but only %ld known!\n", wDevID, ALSA_WodNumDevs);
2821 return MMSYSERR_BADDEVICEID;
2824 if (WOutDev[wDevID].pcm == NULL) {
2825 WARN("Requested to breakloop of closed device %d!\n", wDevID);
2826 return MMSYSERR_BADDEVICEID;
2829 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
2830 return MMSYSERR_NOERROR;
2833 /**************************************************************************
2834 * wodGetVolume [internal]
2836 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
2844 TRACE("(%u, %p);\n", wDevID, lpdwVol);
2845 if (wDevID >= ALSA_WodNumDevs) {
2846 TRACE("Asked for device %d, but only %ld known!\n", wDevID, ALSA_WodNumDevs);
2847 return MMSYSERR_BADDEVICEID;
2850 if (lpdwVol == NULL)
2851 return MMSYSERR_NOTENABLED;
2853 wwo = &WOutDev[wDevID];
2855 if (lpdwVol == NULL)
2856 return MMSYSERR_NOTENABLED;
2858 rc = ALSA_CheckSetVolume(wwo->hctl, &left, &right, &min, &max, NULL, NULL, NULL);
2859 if (rc == MMSYSERR_NOERROR)
2861 #define VOLUME_ALSA_TO_WIN(x) ( ( (((x)-min) * 65535) + (max-min)/2 ) /(max-min))
2862 wleft = VOLUME_ALSA_TO_WIN(left);
2863 wright = VOLUME_ALSA_TO_WIN(right);
2864 #undef VOLUME_ALSA_TO_WIN
2865 TRACE("left=%d,right=%d,converted to windows left %d, right %d\n", left, right, wleft, wright);
2866 *lpdwVol = MAKELONG( wleft, wright );
2869 TRACE("CheckSetVolume failed; rc %ld\n", rc);
2874 /**************************************************************************
2875 * wodSetVolume [internal]
2877 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
2885 TRACE("(%u, %08lX);\n", wDevID, dwParam);
2886 if (wDevID >= ALSA_WodNumDevs) {
2887 TRACE("Asked for device %d, but only %ld known!\n", wDevID, ALSA_WodNumDevs);
2888 return MMSYSERR_BADDEVICEID;
2891 wwo = &WOutDev[wDevID];
2893 rc = ALSA_CheckSetVolume(wwo->hctl, NULL, NULL, &min, &max, NULL, NULL, NULL);
2894 if (rc == MMSYSERR_NOERROR)
2896 wleft = LOWORD(dwParam);
2897 wright = HIWORD(dwParam);
2898 #define VOLUME_WIN_TO_ALSA(x) ( ( ( ((x) * (max-min)) + 32767) / 65535) + min )
2899 left = VOLUME_WIN_TO_ALSA(wleft);
2900 right = VOLUME_WIN_TO_ALSA(wright);
2901 #undef VOLUME_WIN_TO_ALSA
2902 rc = ALSA_CheckSetVolume(wwo->hctl, NULL, NULL, NULL, NULL, NULL, &left, &right);
2903 if (rc == MMSYSERR_NOERROR)
2904 TRACE("set volume: wleft=%d, wright=%d, converted to alsa left %d, right %d\n", wleft, wright, left, right);
2906 TRACE("SetVolume failed; rc %ld\n", rc);
2912 /**************************************************************************
2913 * wodGetNumDevs [internal]
2915 static DWORD wodGetNumDevs(void)
2917 return ALSA_WodNumDevs;
2920 /**************************************************************************
2921 * wodDevInterfaceSize [internal]
2923 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2925 TRACE("(%u, %p)\n", wDevID, dwParam1);
2927 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2928 NULL, 0 ) * sizeof(WCHAR);
2929 return MMSYSERR_NOERROR;
2932 /**************************************************************************
2933 * wodDevInterface [internal]
2935 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2937 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2938 NULL, 0 ) * sizeof(WCHAR))
2940 MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2941 dwParam1, dwParam2 / sizeof(WCHAR));
2942 return MMSYSERR_NOERROR;
2944 return MMSYSERR_INVALPARAM;
2947 /**************************************************************************
2948 * wodMessage (WINEALSA.@)
2950 DWORD WINAPI ALSA_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
2951 DWORD dwParam1, DWORD dwParam2)
2953 TRACE("(%u, %s, %08lX, %08lX, %08lX);\n",
2954 wDevID, getMessage(wMsg), dwUser, dwParam1, dwParam2);
2961 /* FIXME: Pretend this is supported */
2963 case WODM_OPEN: return wodOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2964 case WODM_CLOSE: return wodClose (wDevID);
2965 case WODM_GETDEVCAPS: return wodGetDevCaps (wDevID, (LPWAVEOUTCAPSW)dwParam1, dwParam2);
2966 case WODM_GETNUMDEVS: return wodGetNumDevs ();
2967 case WODM_GETPITCH: return MMSYSERR_NOTSUPPORTED;
2968 case WODM_SETPITCH: return MMSYSERR_NOTSUPPORTED;
2969 case WODM_GETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
2970 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
2971 case WODM_WRITE: return wodWrite (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2972 case WODM_PAUSE: return wodPause (wDevID);
2973 case WODM_GETPOS: return wodGetPosition (wDevID, (LPMMTIME)dwParam1, dwParam2);
2974 case WODM_BREAKLOOP: return wodBreakLoop (wDevID);
2975 case WODM_PREPARE: return MMSYSERR_NOTSUPPORTED;
2976 case WODM_UNPREPARE: return MMSYSERR_NOTSUPPORTED;
2977 case WODM_GETVOLUME: return wodGetVolume (wDevID, (LPDWORD)dwParam1);
2978 case WODM_SETVOLUME: return wodSetVolume (wDevID, dwParam1);
2979 case WODM_RESTART: return wodRestart (wDevID);
2980 case WODM_RESET: return wodReset (wDevID);
2981 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2982 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2983 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
2984 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
2987 FIXME("unknown message %d!\n", wMsg);
2989 return MMSYSERR_NOTSUPPORTED;
2992 /*======================================================================*
2993 * Low level DSOUND implementation *
2994 *======================================================================*/
2996 typedef struct IDsDriverImpl IDsDriverImpl;
2997 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
2999 struct IDsDriverImpl
3001 /* IUnknown fields */
3002 const IDsDriverVtbl *lpVtbl;
3004 /* IDsDriverImpl fields */
3006 IDsDriverBufferImpl*primary;
3009 struct IDsDriverBufferImpl
3011 /* IUnknown fields */
3012 const IDsDriverBufferVtbl *lpVtbl;
3014 /* IDsDriverBufferImpl fields */
3017 CRITICAL_SECTION mmap_crst;
3019 DWORD mmap_buflen_bytes;
3020 snd_pcm_uframes_t mmap_buflen_frames;
3021 snd_pcm_channel_area_t * mmap_areas;
3022 snd_async_handler_t * mmap_async_handler;
3023 snd_pcm_uframes_t mmap_ppos; /* play position */
3025 /* Do we have a direct hardware buffer - SND_PCM_TYPE_HW? */
3029 static void DSDB_CheckXRUN(IDsDriverBufferImpl* pdbi)
3031 WINE_WAVEDEV * wwo = &(WOutDev[pdbi->drv->wDevID]);
3032 snd_pcm_state_t state = snd_pcm_state(wwo->pcm);
3034 if ( state == SND_PCM_STATE_XRUN )
3036 int err = snd_pcm_prepare(wwo->pcm);
3037 TRACE("xrun occurred\n");
3039 ERR("recovery from xrun failed, prepare failed: %s\n", snd_strerror(err));
3041 else if ( state == SND_PCM_STATE_SUSPENDED )
3043 int err = snd_pcm_resume(wwo->pcm);
3044 TRACE("recovery from suspension occurred\n");
3045 if (err < 0 && err != -EAGAIN){
3046 err = snd_pcm_prepare(wwo->pcm);
3048 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
3053 static void DSDB_MMAPCopy(IDsDriverBufferImpl* pdbi, int mul)
3055 WINE_WAVEDEV * wwo = &(WOutDev[pdbi->drv->wDevID]);
3056 snd_pcm_uframes_t period_size;
3057 snd_pcm_sframes_t avail;
3061 const snd_pcm_channel_area_t *areas;
3062 snd_pcm_uframes_t ofs;
3063 snd_pcm_uframes_t frames;
3064 snd_pcm_uframes_t wanted;
3066 if ( !pdbi->mmap_buffer || !wwo->hw_params || !wwo->pcm)
3069 err = snd_pcm_hw_params_get_period_size(wwo->hw_params, &period_size, &dir);
3070 avail = snd_pcm_avail_update(wwo->pcm);
3072 DSDB_CheckXRUN(pdbi);
3074 TRACE("avail=%d, mul=%d\n", (int)avail, mul);
3076 frames = pdbi->mmap_buflen_frames;
3078 EnterCriticalSection(&pdbi->mmap_crst);
3080 /* we want to commit the given number of periods, or the whole lot */
3081 wanted = mul == 0 ? frames : period_size * 2;
3083 snd_pcm_mmap_begin(wwo->pcm, &areas, &ofs, &frames);
3084 if (areas != pdbi->mmap_areas || areas->addr != pdbi->mmap_areas->addr)
3085 FIXME("Can't access sound driver's buffer directly.\n");
3087 /* mark our current play position */
3088 pdbi->mmap_ppos = ofs;
3090 if (frames > wanted)
3093 err = snd_pcm_mmap_commit(wwo->pcm, ofs, frames);
3095 /* Check to make sure we committed all we want to commit. ALSA
3096 * only gives a contiguous linear region, so we need to check this
3097 * in case we've reached the end of the buffer, in which case we
3098 * can wrap around back to the beginning. */
3099 if (frames < wanted) {
3100 frames = wanted -= frames;
3101 snd_pcm_mmap_begin(wwo->pcm, &areas, &ofs, &frames);
3102 snd_pcm_mmap_commit(wwo->pcm, ofs, frames);
3105 LeaveCriticalSection(&pdbi->mmap_crst);
3108 static void DSDB_PCMCallback(snd_async_handler_t *ahandler)
3111 /* snd_pcm_t * handle = snd_async_handler_get_pcm(ahandler); */
3112 IDsDriverBufferImpl* pdbi = snd_async_handler_get_callback_private(ahandler);
3113 TRACE("callback called\n");
3115 /* Commit another block (the entire buffer if it's a direct hw buffer) */
3116 periods = pdbi->mmap_mode == SND_PCM_TYPE_HW ? 0 : 1;
3117 DSDB_MMAPCopy(pdbi, periods);
3121 * Allocate the memory-mapped buffer for direct sound, and set up the
3124 static int DSDB_CreateMMAP(IDsDriverBufferImpl* pdbi)
3126 WINE_WAVEDEV * wwo = &(WOutDev[pdbi->drv->wDevID]);
3127 snd_pcm_format_t format;
3128 snd_pcm_uframes_t frames;
3129 snd_pcm_uframes_t ofs;
3130 snd_pcm_uframes_t avail;
3131 unsigned int channels;
3132 unsigned int bits_per_sample;
3133 unsigned int bits_per_frame;
3136 err = snd_pcm_hw_params_get_format(wwo->hw_params, &format);
3137 err = snd_pcm_hw_params_get_buffer_size(wwo->hw_params, &frames);
3138 err = snd_pcm_hw_params_get_channels(wwo->hw_params, &channels);
3139 bits_per_sample = snd_pcm_format_physical_width(format);
3140 bits_per_frame = bits_per_sample * channels;
3141 pdbi->mmap_mode = snd_pcm_type(wwo->pcm);
3143 if (pdbi->mmap_mode == SND_PCM_TYPE_HW) {
3144 TRACE("mmap'd buffer is a hardware buffer.\n");
3147 TRACE("mmap'd buffer is an ALSA emulation of hardware buffer.\n");
3151 ALSA_TraceParameters(wwo->hw_params, NULL, FALSE);
3153 TRACE("format=%s frames=%ld channels=%d bits_per_sample=%d bits_per_frame=%d\n",
3154 snd_pcm_format_name(format), frames, channels, bits_per_sample, bits_per_frame);
3156 pdbi->mmap_buflen_frames = frames;
3157 pdbi->mmap_buflen_bytes = snd_pcm_frames_to_bytes( wwo->pcm, frames );
3159 avail = snd_pcm_avail_update(wwo->pcm);
3162 ERR("No buffer is available: %s.", snd_strerror(avail));
3163 return DSERR_GENERIC;
3165 err = snd_pcm_mmap_begin(wwo->pcm, (const snd_pcm_channel_area_t **)&pdbi->mmap_areas, &ofs, &avail);
3168 ERR("Can't map sound device for direct access: %s\n", snd_strerror(err));
3169 return DSERR_GENERIC;
3171 avail = 0;/* We don't have any data to commit yet */
3172 err = snd_pcm_mmap_commit(wwo->pcm, ofs, avail);
3174 err = snd_pcm_rewind(wwo->pcm, ofs);
3175 pdbi->mmap_buffer = pdbi->mmap_areas->addr;
3177 snd_pcm_format_set_silence(format, pdbi->mmap_buffer, frames );
3179 TRACE("created mmap buffer of %ld frames (%ld bytes) at %p\n",
3180 frames, pdbi->mmap_buflen_bytes, pdbi->mmap_buffer);
3182 InitializeCriticalSection(&pdbi->mmap_crst);
3183 pdbi->mmap_crst.DebugInfo->Spare[0] = (DWORD_PTR)"WINEALSA_mmap_crst";
3185 err = snd_async_add_pcm_handler(&pdbi->mmap_async_handler, wwo->pcm, DSDB_PCMCallback, pdbi);
3188 ERR("add_pcm_handler failed. reason: %s\n", snd_strerror(err));
3189 return DSERR_GENERIC;
3195 static void DSDB_DestroyMMAP(IDsDriverBufferImpl* pdbi)
3197 TRACE("mmap buffer %p destroyed\n", pdbi->mmap_buffer);
3198 pdbi->mmap_areas = NULL;
3199 pdbi->mmap_buffer = NULL;
3200 pdbi->mmap_crst.DebugInfo->Spare[0] = 0;
3201 DeleteCriticalSection(&pdbi->mmap_crst);
3205 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
3207 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
3208 FIXME("(): stub!\n");
3209 return DSERR_UNSUPPORTED;
3212 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
3214 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
3215 ULONG refCount = InterlockedIncrement(&This->ref);
3217 TRACE("(%p)->(ref before=%lu)\n",This, refCount - 1);
3222 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
3224 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
3225 ULONG refCount = InterlockedDecrement(&This->ref);
3227 TRACE("(%p)->(ref before=%lu)\n",This, refCount + 1);
3231 if (This == This->drv->primary)
3232 This->drv->primary = NULL;
3233 DSDB_DestroyMMAP(This);
3234 HeapFree(GetProcessHeap(), 0, This);
3238 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
3239 LPVOID*ppvAudio1,LPDWORD pdwLen1,
3240 LPVOID*ppvAudio2,LPDWORD pdwLen2,
3241 DWORD dwWritePosition,DWORD dwWriteLen,
3244 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
3245 TRACE("(%p)\n",iface);
3246 return DSERR_UNSUPPORTED;
3249 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
3250 LPVOID pvAudio1,DWORD dwLen1,
3251 LPVOID pvAudio2,DWORD dwLen2)
3253 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
3254 TRACE("(%p)\n",iface);
3255 return DSERR_UNSUPPORTED;
3258 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
3259 LPWAVEFORMATEX pwfx)
3261 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
3262 TRACE("(%p,%p)\n",iface,pwfx);
3263 return DSERR_BUFFERLOST;
3266 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
3268 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
3269 TRACE("(%p,%ld): stub\n",iface,dwFreq);
3270 return DSERR_UNSUPPORTED;
3273 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
3276 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
3277 TRACE("(%p,%p)\n",iface,pVolPan);
3278 vol = pVolPan->dwTotalLeftAmpFactor | (pVolPan->dwTotalRightAmpFactor << 16);
3280 if (wodSetVolume(This->drv->wDevID, vol) != MMSYSERR_NOERROR) {
3281 WARN("wodSetVolume failed\n");
3282 return DSERR_INVALIDPARAM;
3288 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
3290 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
3291 TRACE("(%p,%ld): stub\n",iface,dwNewPos);
3292 return DSERR_UNSUPPORTED;
3295 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
3296 LPDWORD lpdwPlay, LPDWORD lpdwWrite)
3298 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
3299 WINE_WAVEDEV * wwo = &(WOutDev[This->drv->wDevID]);
3300 snd_pcm_uframes_t hw_ptr;
3301 snd_pcm_uframes_t period_size;
3302 snd_pcm_state_t state;
3306 if (wwo->hw_params == NULL) return DSERR_GENERIC;
3309 err = snd_pcm_hw_params_get_period_size(wwo->hw_params, &period_size, &dir);
3311 if (wwo->pcm == NULL) return DSERR_GENERIC;
3312 /** we need to track down buffer underruns */
3313 DSDB_CheckXRUN(This);
3315 EnterCriticalSection(&This->mmap_crst);
3316 hw_ptr = This->mmap_ppos;
3318 state = snd_pcm_state(wwo->pcm);
3319 if (state != SND_PCM_STATE_RUNNING)
3323 *lpdwPlay = snd_pcm_frames_to_bytes(wwo->pcm, hw_ptr) % This->mmap_buflen_bytes;
3325 *lpdwWrite = snd_pcm_frames_to_bytes(wwo->pcm, hw_ptr + period_size * 2) % This->mmap_buflen_bytes;
3326 LeaveCriticalSection(&This->mmap_crst);
3328 TRACE("hw_ptr=0x%08x, playpos=%ld, writepos=%ld\n", (unsigned int)hw_ptr, lpdwPlay?*lpdwPlay:-1, lpdwWrite?*lpdwWrite:-1);
3332 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
3334 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
3335 WINE_WAVEDEV * wwo = &(WOutDev[This->drv->wDevID]);
3336 snd_pcm_state_t state;
3339 TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
3341 if (wwo->pcm == NULL) return DSERR_GENERIC;
3343 state = snd_pcm_state(wwo->pcm);
3344 if ( state == SND_PCM_STATE_SETUP )
3346 err = snd_pcm_prepare(wwo->pcm);
3347 state = snd_pcm_state(wwo->pcm);
3349 if ( state == SND_PCM_STATE_PREPARED )
3351 /* If we have a direct hardware buffer, we can commit the whole lot
3352 * immediately (periods = 0), otherwise we prime the queue with only
3355 * Why 2? We want a small number so that we don't get ahead of the
3356 * DirectSound mixer. But we don't want to ever let the buffer get
3357 * completely empty - having 2 periods gives us time to commit another
3358 * period when the first expires.
3360 * The potential for buffer underrun is high, but that's the reality
3361 * of using a translated buffer (the whole point of DirectSound is
3362 * to provide direct access to the hardware).
3364 * A better implementation would use the buffer Lock() and Unlock()
3365 * methods to determine how far ahead we can commit, and to rewind if
3368 int periods = This->mmap_mode == SND_PCM_TYPE_HW ? 0 : 2;
3370 DSDB_MMAPCopy(This, periods);
3371 err = snd_pcm_start(wwo->pcm);
3376 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
3378 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
3379 WINE_WAVEDEV * wwo = &(WOutDev[This->drv->wDevID]);
3384 TRACE("(%p)\n",iface);
3386 if (wwo->pcm == NULL) return DSERR_GENERIC;
3388 /* ring buffer wrap up detection */
3389 IDsDriverBufferImpl_GetPosition(iface, &play, &write);
3392 TRACE("writepos wrapper up\n");
3396 if ( ( err = snd_pcm_drop(wwo->pcm)) < 0 )
3398 ERR("error while stopping pcm: %s\n", snd_strerror(err));
3399 return DSERR_GENERIC;
3404 static const IDsDriverBufferVtbl dsdbvt =
3406 IDsDriverBufferImpl_QueryInterface,
3407 IDsDriverBufferImpl_AddRef,
3408 IDsDriverBufferImpl_Release,
3409 IDsDriverBufferImpl_Lock,
3410 IDsDriverBufferImpl_Unlock,
3411 IDsDriverBufferImpl_SetFormat,
3412 IDsDriverBufferImpl_SetFrequency,
3413 IDsDriverBufferImpl_SetVolumePan,
3414 IDsDriverBufferImpl_SetPosition,
3415 IDsDriverBufferImpl_GetPosition,
3416 IDsDriverBufferImpl_Play,
3417 IDsDriverBufferImpl_Stop
3420 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
3422 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
3423 FIXME("(%p): stub!\n",iface);
3424 return DSERR_UNSUPPORTED;
3427 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
3429 IDsDriverImpl *This = (IDsDriverImpl *)iface;
3430 ULONG refCount = InterlockedIncrement(&This->ref);
3432 TRACE("(%p)->(ref before=%lu)\n",This, refCount - 1);
3437 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
3439 IDsDriverImpl *This = (IDsDriverImpl *)iface;
3440 ULONG refCount = InterlockedDecrement(&This->ref);
3442 TRACE("(%p)->(ref before=%lu)\n",This, refCount + 1);
3446 HeapFree(GetProcessHeap(),0,This);
3450 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
3452 IDsDriverImpl *This = (IDsDriverImpl *)iface;
3453 TRACE("(%p,%p)\n",iface,pDesc);
3454 memcpy(pDesc, &(WOutDev[This->wDevID].ds_desc), sizeof(DSDRIVERDESC));
3455 pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
3456 DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK;
3457 pDesc->dnDevNode = WOutDev[This->wDevID].waveDesc.dnDevNode;
3459 pDesc->wReserved = 0;
3460 pDesc->ulDeviceNum = This->wDevID;
3461 pDesc->dwHeapType = DSDHEAP_NOHEAP;
3462 pDesc->pvDirectDrawHeap = NULL;
3463 pDesc->dwMemStartAddress = 0;
3464 pDesc->dwMemEndAddress = 0;
3465 pDesc->dwMemAllocExtra = 0;
3466 pDesc->pvReserved1 = NULL;
3467 pDesc->pvReserved2 = NULL;
3471 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
3473 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
3474 TRACE("(%p)\n",iface);
3478 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
3480 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
3481 TRACE("(%p)\n",iface);
3485 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
3487 IDsDriverImpl *This = (IDsDriverImpl *)iface;
3488 TRACE("(%p,%p)\n",iface,pCaps);
3489 memcpy(pCaps, &(WOutDev[This->wDevID].ds_caps), sizeof(DSDRIVERCAPS));
3493 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
3494 LPWAVEFORMATEX pwfx,
3495 DWORD dwFlags, DWORD dwCardAddress,
3496 LPDWORD pdwcbBufferSize,
3500 IDsDriverImpl *This = (IDsDriverImpl *)iface;
3501 IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
3504 TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
3505 /* we only support primary buffers */
3506 if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
3507 return DSERR_UNSUPPORTED;
3509 return DSERR_ALLOCATED;
3510 if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
3511 return DSERR_CONTROLUNAVAIL;
3513 *ippdsdb = HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
3514 if (*ippdsdb == NULL)
3515 return DSERR_OUTOFMEMORY;
3516 (*ippdsdb)->lpVtbl = &dsdbvt;
3517 (*ippdsdb)->ref = 1;
3518 (*ippdsdb)->drv = This;
3520 err = DSDB_CreateMMAP((*ippdsdb));
3523 HeapFree(GetProcessHeap(), 0, *ippdsdb);
3527 *ppbBuffer = (*ippdsdb)->mmap_buffer;
3528 *pdwcbBufferSize = (*ippdsdb)->mmap_buflen_bytes;
3530 This->primary = *ippdsdb;
3532 /* buffer is ready to go */
3533 TRACE("buffer created at %p\n", *ippdsdb);
3537 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
3538 PIDSDRIVERBUFFER pBuffer,
3541 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
3542 TRACE("(%p,%p): stub\n",iface,pBuffer);
3543 return DSERR_INVALIDCALL;
3546 static const IDsDriverVtbl dsdvt =
3548 IDsDriverImpl_QueryInterface,
3549 IDsDriverImpl_AddRef,
3550 IDsDriverImpl_Release,
3551 IDsDriverImpl_GetDriverDesc,
3553 IDsDriverImpl_Close,
3554 IDsDriverImpl_GetCaps,
3555 IDsDriverImpl_CreateSoundBuffer,
3556 IDsDriverImpl_DuplicateSoundBuffer
3559 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
3561 IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
3563 TRACE("driver created\n");
3565 /* the HAL isn't much better than the HEL if we can't do mmap() */
3566 if (!(WOutDev[wDevID].outcaps.dwSupport & WAVECAPS_DIRECTSOUND)) {
3567 ERR("DirectSound flag not set\n");
3568 MESSAGE("This sound card's driver does not support direct access\n");
3569 MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
3570 return MMSYSERR_NOTSUPPORTED;
3573 *idrv = HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
3575 return MMSYSERR_NOMEM;
3576 (*idrv)->lpVtbl = &dsdvt;
3579 (*idrv)->wDevID = wDevID;
3580 (*idrv)->primary = NULL;
3581 return MMSYSERR_NOERROR;
3584 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
3586 memcpy(desc, &(WOutDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
3587 return MMSYSERR_NOERROR;
3590 /*======================================================================*
3591 * Low level WAVE IN implementation *
3592 *======================================================================*/
3594 /**************************************************************************
3595 * widNotifyClient [internal]
3597 static DWORD widNotifyClient(WINE_WAVEDEV* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
3599 TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
3605 if (wwi->wFlags != DCB_NULL &&
3606 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags, (HDRVR)wwi->waveDesc.hWave,
3607 wMsg, wwi->waveDesc.dwInstance, dwParam1, dwParam2)) {
3608 WARN("can't notify client !\n");
3609 return MMSYSERR_ERROR;
3613 FIXME("Unknown callback message %u\n", wMsg);
3614 return MMSYSERR_INVALPARAM;
3616 return MMSYSERR_NOERROR;
3619 /**************************************************************************
3620 * widGetDevCaps [internal]
3622 static DWORD widGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
3624 TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
3626 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
3628 if (wDevID >= ALSA_WidNumDevs) {
3629 TRACE("Requested device %d, but only %ld are known!\n", wDevID, ALSA_WidNumDevs);
3630 return MMSYSERR_BADDEVICEID;
3633 memcpy(lpCaps, &WInDev[wDevID].incaps, min(dwSize, sizeof(*lpCaps)));
3634 return MMSYSERR_NOERROR;
3637 /**************************************************************************
3638 * widRecorder_ReadHeaders [internal]
3640 static void widRecorder_ReadHeaders(WINE_WAVEDEV * wwi)
3642 enum win_wm_message tmp_msg;
3647 while (ALSA_RetrieveRingMessage(&wwi->msgRing, &tmp_msg, &tmp_param, &tmp_ev)) {
3648 if (tmp_msg == WINE_WM_HEADER) {
3650 lpWaveHdr = (LPWAVEHDR)tmp_param;
3651 lpWaveHdr->lpNext = 0;
3653 if (wwi->lpQueuePtr == 0)
3654 wwi->lpQueuePtr = lpWaveHdr;
3656 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
3660 ERR("should only have headers left\n");
3665 /**************************************************************************
3666 * widRecorder [internal]
3668 static DWORD CALLBACK widRecorder(LPVOID pmt)
3670 WORD uDevID = (DWORD)pmt;
3671 WINE_WAVEDEV* wwi = (WINE_WAVEDEV*)&WInDev[uDevID];
3675 LPVOID buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, wwi->dwPeriodSize);
3676 char *pOffset = buffer;
3677 enum win_wm_message msg;
3680 DWORD frames_per_period;
3682 wwi->state = WINE_WS_STOPPED;
3683 wwi->dwTotalRecorded = 0;
3684 wwi->lpQueuePtr = NULL;
3686 SetEvent(wwi->hStartUpEvent);
3688 /* make sleep time to be # of ms to output a period */
3689 dwSleepTime = (1024/*wwi-dwPeriodSize => overrun!*/ * 1000) / wwi->format.Format.nAvgBytesPerSec;
3690 frames_per_period = snd_pcm_bytes_to_frames(wwi->pcm, wwi->dwPeriodSize);
3691 TRACE("sleeptime=%ld ms\n", dwSleepTime);
3694 /* wait for dwSleepTime or an event in thread's queue */
3695 /* FIXME: could improve wait time depending on queue state,
3696 * ie, number of queued fragments
3698 if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
3705 lpWaveHdr = wwi->lpQueuePtr;
3706 /* read all the fragments accumulated so far */
3707 frames = snd_pcm_avail_update(wwi->pcm);
3708 bytes = snd_pcm_frames_to_bytes(wwi->pcm, frames);
3709 TRACE("frames = %ld bytes = %ld\n", frames, bytes);
3710 periods = bytes / wwi->dwPeriodSize;
3711 while ((periods > 0) && (wwi->lpQueuePtr))
3714 bytes = wwi->dwPeriodSize;
3715 TRACE("bytes = %ld\n",bytes);
3716 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwPeriodSize)
3718 /* directly read fragment in wavehdr */
3719 read = wwi->read(wwi->pcm, lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded, frames_per_period);
3720 bytesRead = snd_pcm_frames_to_bytes(wwi->pcm, read);
3722 TRACE("bytesRead=%ld (direct)\n", bytesRead);
3723 if (bytesRead != (DWORD) -1)
3725 /* update number of bytes recorded in current buffer and by this device */
3726 lpWaveHdr->dwBytesRecorded += bytesRead;
3727 wwi->dwTotalRecorded += bytesRead;
3729 /* buffer is full. notify client */
3730 if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
3732 /* must copy the value of next waveHdr, because we have no idea of what
3733 * will be done with the content of lpWaveHdr in callback
3735 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
3737 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
3738 lpWaveHdr->dwFlags |= WHDR_DONE;
3740 wwi->lpQueuePtr = lpNext;
3741 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
3745 TRACE("read(%s, %p, %ld) failed (%s)\n", wwi->pcmname,
3746 lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
3747 frames_per_period, strerror(errno));
3752 /* read the fragment in a local buffer */
3753 read = wwi->read(wwi->pcm, buffer, frames_per_period);
3754 bytesRead = snd_pcm_frames_to_bytes(wwi->pcm, read);
3757 TRACE("bytesRead=%ld (local)\n", bytesRead);
3759 if (bytesRead == (DWORD) -1) {
3760 TRACE("read(%s, %p, %ld) failed (%s)\n", wwi->pcmname,
3761 buffer, frames_per_period, strerror(errno));
3765 /* copy data in client buffers */
3766 while (bytesRead != (DWORD) -1 && bytesRead > 0)
3768 DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
3770 memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
3774 /* update number of bytes recorded in current buffer and by this device */
3775 lpWaveHdr->dwBytesRecorded += dwToCopy;
3776 wwi->dwTotalRecorded += dwToCopy;
3777 bytesRead -= dwToCopy;
3778 pOffset += dwToCopy;
3780 /* client buffer is full. notify client */
3781 if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
3783 /* must copy the value of next waveHdr, because we have no idea of what
3784 * will be done with the content of lpWaveHdr in callback
3786 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
3787 TRACE("lpNext=%p\n", lpNext);
3789 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
3790 lpWaveHdr->dwFlags |= WHDR_DONE;
3792 wwi->lpQueuePtr = lpNext;
3793 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
3796 if (!lpNext && bytesRead) {
3797 /* before we give up, check for more header messages */
3798 while (ALSA_PeekRingMessage(&wwi->msgRing, &msg, ¶m, &ev))
3800 if (msg == WINE_WM_HEADER) {
3802 ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, ¶m, &ev);
3803 hdr = ((LPWAVEHDR)param);
3804 TRACE("msg = %s, hdr = %p, ev = %p\n", getCmdString(msg), hdr, ev);
3806 if (lpWaveHdr == 0) {
3807 /* new head of queue */
3808 wwi->lpQueuePtr = lpWaveHdr = hdr;
3810 /* insert buffer at the end of queue */
3812 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
3819 if (lpWaveHdr == 0) {
3820 /* no more buffer to copy data to, but we did read more.
3821 * what hasn't been copied will be dropped
3823 WARN("buffer under run! %lu bytes dropped.\n", bytesRead);
3824 wwi->lpQueuePtr = NULL;
3834 WAIT_OMR(&wwi->msgRing, dwSleepTime);
3836 while (ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, ¶m, &ev))
3838 TRACE("msg=%s param=0x%lx\n", getCmdString(msg), param);
3840 case WINE_WM_PAUSING:
3841 wwi->state = WINE_WS_PAUSED;
3842 /*FIXME("Device should stop recording\n");*/
3845 case WINE_WM_STARTING:
3846 wwi->state = WINE_WS_PLAYING;
3847 snd_pcm_start(wwi->pcm);
3850 case WINE_WM_HEADER:
3851 lpWaveHdr = (LPWAVEHDR)param;
3852 lpWaveHdr->lpNext = 0;
3854 /* insert buffer at the end of queue */
3857 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
3861 case WINE_WM_STOPPING:
3862 if (wwi->state != WINE_WS_STOPPED)
3864 snd_pcm_drain(wwi->pcm);
3866 /* read any headers in queue */
3867 widRecorder_ReadHeaders(wwi);
3869 /* return current buffer to app */
3870 lpWaveHdr = wwi->lpQueuePtr;
3873 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
3874 TRACE("stop %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
3875 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
3876 lpWaveHdr->dwFlags |= WHDR_DONE;
3877 wwi->lpQueuePtr = lpNext;
3878 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
3881 wwi->state = WINE_WS_STOPPED;
3884 case WINE_WM_RESETTING:
3885 if (wwi->state != WINE_WS_STOPPED)
3887 snd_pcm_drain(wwi->pcm);
3889 wwi->state = WINE_WS_STOPPED;
3890 wwi->dwTotalRecorded = 0;
3892 /* read any headers in queue */
3893 widRecorder_ReadHeaders(wwi);
3895 /* return all buffers to the app */
3896 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
3897 TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
3898 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
3899 lpWaveHdr->dwFlags |= WHDR_DONE;
3900 wwi->lpQueuePtr = lpWaveHdr->lpNext;
3901 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
3904 wwi->lpQueuePtr = NULL;
3907 case WINE_WM_CLOSING:
3909 wwi->state = WINE_WS_CLOSED;
3911 HeapFree(GetProcessHeap(), 0, buffer);
3913 /* shouldn't go here */
3914 case WINE_WM_UPDATE:
3919 FIXME("unknown message %d\n", msg);
3925 /* just for not generating compilation warnings... should never be executed */
3929 /**************************************************************************
3930 * widOpen [internal]
3932 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
3935 snd_pcm_hw_params_t * hw_params;
3936 snd_pcm_sw_params_t * sw_params;
3937 snd_pcm_access_t access;
3938 snd_pcm_format_t format;
3940 unsigned int buffer_time = 500000;
3941 unsigned int period_time = 10000;
3942 snd_pcm_uframes_t buffer_size;
3943 snd_pcm_uframes_t period_size;
3949 snd_pcm_hw_params_alloca(&hw_params);
3950 snd_pcm_sw_params_alloca(&sw_params);
3952 /* JPW TODO - review this code */
3953 TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
3954 if (lpDesc == NULL) {
3955 WARN("Invalid Parameter !\n");
3956 return MMSYSERR_INVALPARAM;
3958 if (wDevID >= ALSA_WidNumDevs) {
3959 TRACE("Requested device %d, but only %ld are known!\n", wDevID, ALSA_WidNumDevs);
3960 return MMSYSERR_BADDEVICEID;
3963 /* only PCM format is supported so far... */
3964 if (!supportedFormat(lpDesc->lpFormat)) {
3965 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
3966 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
3967 lpDesc->lpFormat->nSamplesPerSec);
3968 return WAVERR_BADFORMAT;
3971 if (dwFlags & WAVE_FORMAT_QUERY) {
3972 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
3973 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
3974 lpDesc->lpFormat->nSamplesPerSec);
3975 return MMSYSERR_NOERROR;
3978 wwi = &WInDev[wDevID];
3980 if (wwi->pcm != NULL) {
3981 WARN("already allocated\n");
3982 return MMSYSERR_ALLOCATED;
3985 if ((dwFlags & WAVE_DIRECTSOUND) && !(wwi->dwSupport & WAVECAPS_DIRECTSOUND))
3986 /* not supported, ignore it */
3987 dwFlags &= ~WAVE_DIRECTSOUND;
3990 flags = SND_PCM_NONBLOCK;
3992 if ( dwFlags & WAVE_DIRECTSOUND )
3993 flags |= SND_PCM_ASYNC;
3996 if ( (err=snd_pcm_open(&pcm, wwi->pcmname, SND_PCM_STREAM_CAPTURE, flags)) < 0 )
3998 ERR("Error open: %s\n", snd_strerror(err));
3999 return MMSYSERR_NOTENABLED;
4002 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
4004 memcpy(&wwi->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
4005 copy_format(lpDesc->lpFormat, &wwi->format);
4007 if (wwi->format.Format.wBitsPerSample == 0) {
4008 WARN("Resetting zeroed wBitsPerSample\n");
4009 wwi->format.Format.wBitsPerSample = 8 *
4010 (wwi->format.Format.nAvgBytesPerSec /
4011 wwi->format.Format.nSamplesPerSec) /
4012 wwi->format.Format.nChannels;
4015 snd_pcm_hw_params_any(pcm, hw_params);
4017 #define EXIT_ON_ERROR(f,e,txt) do \
4020 if ( (err = (f) ) < 0) \
4022 WARN(txt ": %s\n", snd_strerror(err)); \
4023 snd_pcm_close(pcm); \
4028 access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
4029 if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
4030 WARN("mmap not available. switching to standard write.\n");
4031 access = SND_PCM_ACCESS_RW_INTERLEAVED;
4032 EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
4033 wwi->read = snd_pcm_readi;
4036 wwi->read = snd_pcm_mmap_readi;
4038 EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwi->format.Format.nChannels), WAVERR_BADFORMAT, "unable to set required channels");
4040 if ((wwi->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
4041 ((wwi->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
4042 IsEqualGUID(&wwi->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
4043 format = (wwi->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
4044 (wwi->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
4045 (wwi->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
4046 (wwi->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
4047 } else if ((wwi->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
4048 IsEqualGUID(&wwi->format.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)){
4049 format = (wwi->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_FLOAT_LE : -1;
4050 } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
4051 FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
4053 return WAVERR_BADFORMAT;
4054 } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
4055 FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
4057 return WAVERR_BADFORMAT;
4058 } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
4059 FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
4061 return WAVERR_BADFORMAT;
4063 ERR("invalid format: %0x04x\n", wwi->format.Format.wFormatTag);
4065 return WAVERR_BADFORMAT;
4068 EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), WAVERR_BADFORMAT, "unable to set required format");
4070 rate = wwi->format.Format.nSamplesPerSec;
4072 err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
4074 WARN("Rate %ld Hz not available for playback: %s\n", wwi->format.Format.nSamplesPerSec, snd_strerror(rate));
4076 return WAVERR_BADFORMAT;
4078 if (!NearMatch(rate, wwi->format.Format.nSamplesPerSec)) {
4079 WARN("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwi->format.Format.nSamplesPerSec, rate);
4081 return WAVERR_BADFORMAT;
4085 EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
4087 EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
4089 EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
4092 err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
4093 err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
4095 snd_pcm_sw_params_current(pcm, sw_params);
4096 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");
4097 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
4098 EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
4099 EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
4100 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
4101 EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
4102 #undef EXIT_ON_ERROR
4104 snd_pcm_prepare(pcm);
4107 ALSA_TraceParameters(hw_params, sw_params, FALSE);
4109 /* now, we can save all required data for later use... */
4110 if ( wwi->hw_params )
4111 snd_pcm_hw_params_free(wwi->hw_params);
4112 snd_pcm_hw_params_malloc(&(wwi->hw_params));
4113 snd_pcm_hw_params_copy(wwi->hw_params, hw_params);
4115 wwi->dwBufferSize = snd_pcm_frames_to_bytes(pcm, buffer_size);
4116 wwi->lpQueuePtr = wwi->lpPlayPtr = wwi->lpLoopPtr = NULL;
4119 ALSA_InitRingMessage(&wwi->msgRing);
4121 wwi->dwPeriodSize = period_size;
4122 /*if (wwi->dwFragmentSize % wwi->format.Format.nBlockAlign)
4123 ERR("Fragment doesn't contain an integral number of data blocks\n");
4125 TRACE("dwPeriodSize=%lu\n", wwi->dwPeriodSize);
4126 TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
4127 wwi->format.Format.wBitsPerSample, wwi->format.Format.nAvgBytesPerSec,
4128 wwi->format.Format.nSamplesPerSec, wwi->format.Format.nChannels,
4129 wwi->format.Format.nBlockAlign);
4131 if (!(dwFlags & WAVE_DIRECTSOUND)) {
4132 wwi->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
4133 wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
4135 SetThreadPriority(wwi->hThread, THREAD_PRIORITY_TIME_CRITICAL);
4136 WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
4137 CloseHandle(wwi->hStartUpEvent);
4139 wwi->hThread = INVALID_HANDLE_VALUE;
4140 wwi->dwThreadID = 0;
4142 wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
4144 return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
4148 /**************************************************************************
4149 * widClose [internal]
4151 static DWORD widClose(WORD wDevID)
4153 DWORD ret = MMSYSERR_NOERROR;
4156 TRACE("(%u);\n", wDevID);
4158 if (wDevID >= ALSA_WidNumDevs) {
4159 TRACE("Requested device %d, but only %ld are known!\n", wDevID, ALSA_WidNumDevs);
4160 return MMSYSERR_BADDEVICEID;
4163 if (WInDev[wDevID].pcm == NULL) {
4164 WARN("Requested to close already closed device %d!\n", wDevID);
4165 return MMSYSERR_BADDEVICEID;
4168 wwi = &WInDev[wDevID];
4169 if (wwi->lpQueuePtr) {
4170 WARN("buffers still playing !\n");
4171 ret = WAVERR_STILLPLAYING;
4173 if (wwi->hThread != INVALID_HANDLE_VALUE) {
4174 ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
4176 ALSA_DestroyRingMessage(&wwi->msgRing);
4178 snd_pcm_hw_params_free(wwi->hw_params);
4179 wwi->hw_params = NULL;
4181 snd_pcm_close(wwi->pcm);
4184 ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
4190 /**************************************************************************
4191 * widAddBuffer [internal]
4194 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
4196 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
4198 /* first, do the sanity checks... */
4199 if (wDevID >= ALSA_WidNumDevs) {
4200 TRACE("Requested device %d, but only %ld are known!\n", wDevID, ALSA_WidNumDevs);
4201 return MMSYSERR_BADDEVICEID;
4204 if (WInDev[wDevID].pcm == NULL) {
4205 WARN("Requested to add buffer to already closed device %d!\n", wDevID);
4206 return MMSYSERR_BADDEVICEID;
4209 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
4210 return WAVERR_UNPREPARED;
4212 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
4213 return WAVERR_STILLPLAYING;
4215 lpWaveHdr->dwFlags &= ~WHDR_DONE;
4216 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
4217 lpWaveHdr->lpNext = 0;
4219 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
4221 return MMSYSERR_NOERROR;
4224 /**************************************************************************
4225 * widStart [internal]
4228 static DWORD widStart(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
4230 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
4232 /* first, do the sanity checks... */
4233 if (wDevID >= ALSA_WidNumDevs) {
4234 TRACE("Requested device %d, but only %ld are known!\n", wDevID, ALSA_WidNumDevs);
4235 return MMSYSERR_BADDEVICEID;
4238 if (WInDev[wDevID].pcm == NULL) {
4239 WARN("Requested to start closed device %d!\n", wDevID);
4240 return MMSYSERR_BADDEVICEID;
4243 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
4245 return MMSYSERR_NOERROR;
4248 /**************************************************************************
4249 * widStop [internal]
4252 static DWORD widStop(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
4254 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
4256 /* first, do the sanity checks... */
4257 if (wDevID >= ALSA_WidNumDevs) {
4258 TRACE("Requested device %d, but only %ld are known!\n", wDevID, ALSA_WidNumDevs);
4259 return MMSYSERR_BADDEVICEID;
4262 if (WInDev[wDevID].pcm == NULL) {
4263 WARN("Requested to stop closed device %d!\n", wDevID);
4264 return MMSYSERR_BADDEVICEID;
4267 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
4269 return MMSYSERR_NOERROR;
4272 /**************************************************************************
4273 * widReset [internal]
4275 static DWORD widReset(WORD wDevID)
4277 TRACE("(%u);\n", wDevID);
4278 if (wDevID >= ALSA_WidNumDevs) {
4279 TRACE("Requested device %d, but only %ld are known!\n", wDevID, ALSA_WidNumDevs);
4280 return MMSYSERR_BADDEVICEID;
4283 if (WInDev[wDevID].pcm == NULL) {
4284 WARN("Requested to reset closed device %d!\n", wDevID);
4285 return MMSYSERR_BADDEVICEID;
4288 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
4289 return MMSYSERR_NOERROR;
4292 /**************************************************************************
4293 * widGetPosition [internal]
4295 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
4299 TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
4301 if (wDevID >= ALSA_WidNumDevs) {
4302 TRACE("Requested device %d, but only %ld are known!\n", wDevID, ALSA_WidNumDevs);
4303 return MMSYSERR_BADDEVICEID;
4306 if (WInDev[wDevID].state == WINE_WS_CLOSED) {
4307 WARN("Requested position of closed device %d!\n", wDevID);
4308 return MMSYSERR_BADDEVICEID;
4311 if (lpTime == NULL) {
4312 WARN("invalid parameter: lpTime = NULL\n");
4313 return MMSYSERR_INVALPARAM;
4316 wwi = &WInDev[wDevID];
4317 ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_UPDATE, 0, TRUE);
4319 return bytes_to_mmtime(lpTime, wwi->dwTotalRecorded, &wwi->format);
4322 /**************************************************************************
4323 * widGetNumDevs [internal]
4325 static DWORD widGetNumDevs(void)
4327 return ALSA_WidNumDevs;
4330 /**************************************************************************
4331 * widDevInterfaceSize [internal]
4333 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
4335 TRACE("(%u, %p)\n", wDevID, dwParam1);
4337 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
4338 NULL, 0 ) * sizeof(WCHAR);
4339 return MMSYSERR_NOERROR;
4342 /**************************************************************************
4343 * widDevInterface [internal]
4345 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
4347 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
4348 NULL, 0 ) * sizeof(WCHAR))
4350 MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
4351 dwParam1, dwParam2 / sizeof(WCHAR));
4352 return MMSYSERR_NOERROR;
4354 return MMSYSERR_INVALPARAM;
4357 /**************************************************************************
4358 * widDsCreate [internal]
4360 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
4362 TRACE("(%d,%p)\n",wDevID,drv);
4364 /* the HAL isn't much better than the HEL if we can't do mmap() */
4365 FIXME("DirectSoundCapture not implemented\n");
4366 MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
4367 return MMSYSERR_NOTSUPPORTED;
4370 /**************************************************************************
4371 * widDsDesc [internal]
4373 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
4375 memcpy(desc, &(WInDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
4376 return MMSYSERR_NOERROR;
4379 /**************************************************************************
4380 * widMessage (WINEALSA.@)
4382 DWORD WINAPI ALSA_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
4383 DWORD dwParam1, DWORD dwParam2)
4385 TRACE("(%u, %s, %08lX, %08lX, %08lX);\n",
4386 wDevID, getMessage(wMsg), dwUser, dwParam1, dwParam2);
4393 /* FIXME: Pretend this is supported */
4395 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
4396 case WIDM_CLOSE: return widClose (wDevID);
4397 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
4398 case WIDM_PREPARE: return MMSYSERR_NOTSUPPORTED;
4399 case WIDM_UNPREPARE: return MMSYSERR_NOTSUPPORTED;
4400 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEOUTCAPSW)dwParam1, dwParam2);
4401 case WIDM_GETNUMDEVS: return widGetNumDevs ();
4402 case WIDM_GETPOS: return widGetPosition (wDevID, (LPMMTIME)dwParam1, dwParam2);
4403 case WIDM_RESET: return widReset (wDevID);
4404 case WIDM_START: return widStart (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
4405 case WIDM_STOP: return widStop (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
4406 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
4407 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
4408 case DRV_QUERYDSOUNDIFACE: return widDsCreate (wDevID, (PIDSCDRIVER*)dwParam1);
4409 case DRV_QUERYDSOUNDDESC: return widDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
4411 FIXME("unknown message %d!\n", wMsg);
4413 return MMSYSERR_NOTSUPPORTED;
4418 /**************************************************************************
4419 * widMessage (WINEALSA.@)
4421 DWORD WINAPI ALSA_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
4422 DWORD dwParam1, DWORD dwParam2)
4424 FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
4425 return MMSYSERR_NOTENABLED;
4428 /**************************************************************************
4429 * wodMessage (WINEALSA.@)
4431 DWORD WINAPI ALSA_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
4432 DWORD dwParam1, DWORD dwParam2)
4434 FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
4435 return MMSYSERR_NOTENABLED;
4438 #endif /* HAVE_ALSA */