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>
57 #define ALSA_PCM_NEW_HW_PARAMS_API
58 #define ALSA_PCM_NEW_SW_PARAMS_API
60 #include "wine/library.h"
61 #include "wine/debug.h"
63 WINE_DEFAULT_DEBUG_CHANNEL(wave);
66 #if defined(HAVE_ALSA) && ((SND_LIB_MAJOR == 0 && SND_LIB_MINOR >= 9) || SND_LIB_MAJOR >= 1)
68 /* internal ALSALIB functions */
69 snd_pcm_uframes_t _snd_pcm_mmap_hw_ptr(snd_pcm_t *pcm);
72 #define MAX_WAVEOUTDRV (1)
73 #define MAX_WAVEINDRV (1)
75 /* state diagram for waveOut writing:
77 * +---------+-------------+---------------+---------------------------------+
78 * | state | function | event | new state |
79 * +---------+-------------+---------------+---------------------------------+
80 * | | open() | | STOPPED |
81 * | PAUSED | write() | | PAUSED |
82 * | STOPPED | write() | <thrd create> | PLAYING |
83 * | PLAYING | write() | HEADER | PLAYING |
84 * | (other) | write() | <error> | |
85 * | (any) | pause() | PAUSING | PAUSED |
86 * | PAUSED | restart() | RESTARTING | PLAYING (if no thrd => STOPPED) |
87 * | (any) | reset() | RESETTING | STOPPED |
88 * | (any) | close() | CLOSING | CLOSED |
89 * +---------+-------------+---------------+---------------------------------+
92 /* states of the playing device */
93 #define WINE_WS_PLAYING 0
94 #define WINE_WS_PAUSED 1
95 #define WINE_WS_STOPPED 2
96 #define WINE_WS_CLOSED 3
98 /* events to be send to device */
100 WINE_WM_PAUSING = WM_USER + 1, WINE_WM_RESTARTING, WINE_WM_RESETTING, WINE_WM_HEADER,
101 WINE_WM_UPDATE, WINE_WM_BREAKLOOP, WINE_WM_CLOSING, WINE_WM_STARTING, WINE_WM_STOPPING
105 #define SIGNAL_OMR(omr) do { int x = 0; write((omr)->msg_pipe[1], &x, sizeof(x)); } while (0)
106 #define CLEAR_OMR(omr) do { int x = 0; read((omr)->msg_pipe[0], &x, sizeof(x)); } while (0)
107 #define RESET_OMR(omr) do { } while (0)
108 #define WAIT_OMR(omr, sleep) \
109 do { struct pollfd pfd; pfd.fd = (omr)->msg_pipe[0]; \
110 pfd.events = POLLIN; poll(&pfd, 1, sleep); } while (0)
112 #define SIGNAL_OMR(omr) do { SetEvent((omr)->msg_event); } while (0)
113 #define CLEAR_OMR(omr) do { } while (0)
114 #define RESET_OMR(omr) do { ResetEvent((omr)->msg_event); } while (0)
115 #define WAIT_OMR(omr, sleep) \
116 do { WaitForSingleObject((omr)->msg_event, sleep); } while (0)
120 enum win_wm_message msg; /* message identifier */
121 DWORD param; /* parameter for this message */
122 HANDLE hEvent; /* if message is synchronous, handle of event for synchro */
125 /* implement an in-process message ring for better performance
126 * (compared to passing thru the server)
127 * this ring will be used by the input (resp output) record (resp playback) routine
129 #define ALSA_RING_BUFFER_INCREMENT 64
132 int ring_buffer_size;
140 CRITICAL_SECTION msg_crst;
144 /* Windows information */
145 volatile int state; /* one of the WINE_WS_ manifest constants */
146 WAVEOPENDESC waveDesc;
148 PCMWAVEFORMAT format;
151 /* ALSA information (ALSA 0.9/1.x uses two different devices for playback/capture) */
153 char interface_name[64];
154 snd_pcm_t* p_handle; /* handle to ALSA playback device */
155 snd_pcm_t* c_handle; /* handle to ALSA capture device */
156 snd_pcm_hw_params_t * hw_params; /* ALSA Hw params */
158 snd_ctl_t * ctl; /* control handle for the playback volume */
159 snd_ctl_elem_id_t * playback_eid; /* element id of the playback volume control */
160 snd_ctl_elem_value_t * playback_evalue; /* element value of the playback volume control */
161 snd_ctl_elem_info_t * playback_einfo; /* element info of the playback volume control */
163 snd_pcm_sframes_t (*write)(snd_pcm_t *, const void *, snd_pcm_uframes_t );
168 DWORD dwBufferSize; /* size of whole ALSA buffer in bytes */
169 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
170 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
171 DWORD dwPartialOffset; /* Offset of not yet written bytes in lpPlayPtr */
173 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
174 DWORD dwLoops; /* private copy of loop counter */
176 DWORD dwPlayedTotal; /* number of bytes actually played since opening */
177 DWORD dwWrittenTotal; /* number of bytes written to ALSA buffer since opening */
179 /* synchronization stuff */
180 HANDLE hStartUpEvent;
183 ALSA_MSG_RING msgRing;
185 /* DirectSound stuff */
186 DSDRIVERDESC ds_desc;
191 /* Windows information */
192 volatile int state; /* one of the WINE_WS_ manifest constants */
193 WAVEOPENDESC waveDesc;
195 PCMWAVEFORMAT format;
198 /* ALSA information (ALSA 0.9/1.x uses two different devices for playback/capture) */
200 char interface_name[64];
201 snd_pcm_t* p_handle; /* handle to ALSA playback device */
202 snd_pcm_t* c_handle; /* handle to ALSA capture device */
203 snd_pcm_hw_params_t * hw_params; /* ALSA Hw params */
205 snd_ctl_t * ctl; /* control handle for the playback volume */
206 snd_ctl_elem_id_t * playback_eid; /* element id of the playback volume control */
207 snd_ctl_elem_value_t * playback_evalue; /* element value of the playback volume control */
208 snd_ctl_elem_info_t * playback_einfo; /* element info of the playback volume control */
210 snd_pcm_sframes_t (*read)(snd_pcm_t *, void *, snd_pcm_uframes_t );
215 DWORD dwPeriodSize; /* size of OSS buffer period */
216 DWORD dwBufferSize; /* size of whole ALSA buffer in bytes */
217 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
218 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
220 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
221 DWORD dwLoops; /* private copy of loop counter */
223 /*DWORD dwPlayedTotal; */
224 DWORD dwTotalRecorded;
226 /* synchronization stuff */
227 HANDLE hStartUpEvent;
230 ALSA_MSG_RING msgRing;
232 /* DirectSound stuff */
233 DSDRIVERDESC ds_desc;
237 static WINE_WAVEOUT WOutDev [MAX_WAVEOUTDRV];
238 static DWORD ALSA_WodNumDevs;
239 static WINE_WAVEIN WInDev [MAX_WAVEINDRV];
240 static DWORD ALSA_WidNumDevs;
242 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
243 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
244 static DWORD wodDsGuid(UINT wDevID, LPGUID pGuid);
246 /* These strings used only for tracing */
248 static const char *wodPlayerCmdString[] = {
250 "WINE_WM_RESTARTING",
261 /*======================================================================*
262 * Low level WAVE implementation *
263 *======================================================================*/
265 /**************************************************************************
266 * ALSA_InitializeVolumeCtl [internal]
268 * used to initialize the PCM Volume Control
270 static int ALSA_InitializeVolumeCtl(WINE_WAVEOUT * wwo)
272 snd_ctl_t * ctl = NULL;
273 snd_ctl_card_info_t * cardinfo;
274 snd_ctl_elem_list_t * elemlist;
275 snd_ctl_elem_id_t * e_id;
276 snd_ctl_elem_info_t * einfo;
277 snd_hctl_t * hctl = NULL;
278 snd_hctl_elem_t * elem;
282 snd_ctl_card_info_alloca(&cardinfo);
283 memset(cardinfo,0,snd_ctl_card_info_sizeof());
285 snd_ctl_elem_list_alloca(&elemlist);
286 memset(elemlist,0,snd_ctl_elem_list_sizeof());
288 snd_ctl_elem_id_alloca(&e_id);
289 memset(e_id,0,snd_ctl_elem_id_sizeof());
291 snd_ctl_elem_info_alloca(&einfo);
292 memset(einfo,0,snd_ctl_elem_info_sizeof());
294 #define EXIT_ON_ERROR(f,txt) do \
297 if ( (err = (f) ) < 0) \
299 ERR(txt ": %s\n", snd_strerror(err)); \
301 snd_hctl_close(hctl); \
303 snd_ctl_close(ctl); \
308 EXIT_ON_ERROR( snd_ctl_open(&ctl,"hw",0) , "ctl open failed" );
309 EXIT_ON_ERROR( snd_ctl_card_info(ctl, cardinfo), "card info failed");
310 EXIT_ON_ERROR( snd_ctl_elem_list(ctl, elemlist), "elem list failed");
312 nCtrls = snd_ctl_elem_list_get_count(elemlist);
314 EXIT_ON_ERROR( snd_hctl_open(&hctl,"hw",0), "hctl open failed");
315 EXIT_ON_ERROR( snd_hctl_load(hctl), "hctl load failed" );
317 elem=snd_hctl_first_elem(hctl);
318 for ( i= 0; i<nCtrls; i++) {
320 memset(e_id,0,snd_ctl_elem_id_sizeof());
322 snd_hctl_elem_get_id(elem,e_id);
324 TRACE("ctl: #%d '%s'%d\n",
325 snd_ctl_elem_id_get_numid(e_id),
326 snd_ctl_elem_id_get_name(e_id),
327 snd_ctl_elem_id_get_index(e_id));
329 if ( !strcmp("PCM Playback Volume", snd_ctl_elem_id_get_name(e_id)) )
331 EXIT_ON_ERROR( snd_hctl_elem_info(elem,einfo), "hctl elem info failed" );
333 /* few sanity checks... you'll never know... */
334 if ( snd_ctl_elem_info_get_type(einfo) != SND_CTL_ELEM_TYPE_INTEGER )
335 WARN("playback volume control is not an integer\n");
336 if ( !snd_ctl_elem_info_is_readable(einfo) )
337 WARN("playback volume control is readable\n");
338 if ( !snd_ctl_elem_info_is_writable(einfo) )
339 WARN("playback volume control is readable\n");
341 TRACE(" ctrl range: min=%ld max=%ld step=%ld\n",
342 snd_ctl_elem_info_get_min(einfo),
343 snd_ctl_elem_info_get_max(einfo),
344 snd_ctl_elem_info_get_step(einfo));
346 EXIT_ON_ERROR( snd_ctl_elem_id_malloc(&wwo->playback_eid), "elem id malloc failed" );
347 EXIT_ON_ERROR( snd_ctl_elem_info_malloc(&wwo->playback_einfo), "elem info malloc failed" );
348 EXIT_ON_ERROR( snd_ctl_elem_value_malloc(&wwo->playback_evalue), "elem value malloc failed" );
350 /* ok, now we can safely save these objects for later */
351 snd_ctl_elem_id_copy(wwo->playback_eid, e_id);
352 snd_ctl_elem_info_copy(wwo->playback_einfo, einfo);
353 snd_ctl_elem_value_set_id(wwo->playback_evalue, wwo->playback_eid);
357 elem=snd_hctl_elem_next(elem);
359 snd_hctl_close(hctl);
364 /**************************************************************************
365 * ALSA_XRUNRecovery [internal]
367 * used to recovery from XRUN errors (buffer underflow/overflow)
369 static int ALSA_XRUNRecovery(WINE_WAVEOUT * wwo, int err)
371 if (err == -EPIPE) { /* under-run */
372 err = snd_pcm_prepare(wwo->p_handle);
374 ERR( "underrun recovery failed. prepare failed: %s\n", snd_strerror(err));
376 } else if (err == -ESTRPIPE) {
377 while ((err = snd_pcm_resume(wwo->p_handle)) == -EAGAIN)
378 sleep(1); /* wait until the suspend flag is released */
380 err = snd_pcm_prepare(wwo->p_handle);
382 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
389 /**************************************************************************
390 * ALSA_TraceParameters [internal]
392 * used to trace format changes, hw and sw parameters
394 static void ALSA_TraceParameters(snd_pcm_hw_params_t * hw_params, snd_pcm_sw_params_t * sw, int full)
397 snd_pcm_format_t format;
398 snd_pcm_access_t access;
400 err = snd_pcm_hw_params_get_access(hw_params, &access);
401 err = snd_pcm_hw_params_get_format(hw_params, &format);
403 #define X(x) ((x)? "true" : "false")
405 TRACE("FLAGS: sampleres=%s overrng=%s pause=%s resume=%s syncstart=%s batch=%s block=%s double=%s "
406 "halfd=%s joint=%s \n",
407 X(snd_pcm_hw_params_can_mmap_sample_resolution(hw_params)),
408 X(snd_pcm_hw_params_can_overrange(hw_params)),
409 X(snd_pcm_hw_params_can_pause(hw_params)),
410 X(snd_pcm_hw_params_can_resume(hw_params)),
411 X(snd_pcm_hw_params_can_sync_start(hw_params)),
412 X(snd_pcm_hw_params_is_batch(hw_params)),
413 X(snd_pcm_hw_params_is_block_transfer(hw_params)),
414 X(snd_pcm_hw_params_is_double(hw_params)),
415 X(snd_pcm_hw_params_is_half_duplex(hw_params)),
416 X(snd_pcm_hw_params_is_joint_duplex(hw_params)));
420 TRACE("access=%s\n", snd_pcm_access_name(access));
423 snd_pcm_access_mask_t * acmask;
424 snd_pcm_access_mask_alloca(&acmask);
425 snd_pcm_hw_params_get_access_mask(hw_params, acmask);
426 for ( access = SND_PCM_ACCESS_MMAP_INTERLEAVED; access <= SND_PCM_ACCESS_LAST; access++)
427 if (snd_pcm_access_mask_test(acmask, access))
428 TRACE("access=%s\n", snd_pcm_access_name(access));
433 TRACE("format=%s\n", snd_pcm_format_name(format));
438 snd_pcm_format_mask_t * fmask;
440 snd_pcm_format_mask_alloca(&fmask);
441 snd_pcm_hw_params_get_format_mask(hw_params, fmask);
442 for ( format = SND_PCM_FORMAT_S8; format <= SND_PCM_FORMAT_LAST ; format++)
443 if ( snd_pcm_format_mask_test(fmask, format) )
444 TRACE("format=%s\n", snd_pcm_format_name(format));
450 err = snd_pcm_hw_params_get_channels(hw_params, &val);
452 unsigned int min = 0;
453 unsigned int max = 0;
454 err = snd_pcm_hw_params_get_channels_min(hw_params, &min),
455 err = snd_pcm_hw_params_get_channels_max(hw_params, &max);
456 TRACE("channels_min=%u, channels_min_max=%u\n", min, max);
458 TRACE("channels_min=%d\n", val);
463 snd_pcm_uframes_t val=0;
464 err = snd_pcm_hw_params_get_buffer_size(hw_params, &val);
466 snd_pcm_uframes_t min = 0;
467 snd_pcm_uframes_t max = 0;
468 err = snd_pcm_hw_params_get_buffer_size_min(hw_params, &min),
469 err = snd_pcm_hw_params_get_buffer_size_max(hw_params, &max);
470 TRACE("buffer_size_min=%lu, buffer_size_min_max=%lu\n", min, max);
472 TRACE("buffer_size_min=%lu\n", val);
479 unsigned int val=0; \
480 err = snd_pcm_hw_params_get_##x(hw_params,&val, &dir); \
482 unsigned int min = 0; \
483 unsigned int max = 0; \
484 err = snd_pcm_hw_params_get_##x##_min(hw_params, &min, &dir); \
485 err = snd_pcm_hw_params_get_##x##_max(hw_params, &max, &dir); \
486 TRACE(#x "_min=%u " #x "_max=%u\n", min, max); \
488 TRACE(#x "=%d\n", val); \
497 snd_pcm_uframes_t val=0;
498 err = snd_pcm_hw_params_get_period_size(hw_params, &val, &dir);
500 snd_pcm_uframes_t min = 0;
501 snd_pcm_uframes_t max = 0;
502 err = snd_pcm_hw_params_get_period_size_min(hw_params, &min, &dir),
503 err = snd_pcm_hw_params_get_period_size_max(hw_params, &max, &dir);
504 TRACE("period_size_min=%lu, period_size_min_max=%lu\n", min, max);
506 TRACE("period_size_min=%lu\n", val);
520 /* return a string duplicated on the win32 process heap, free with HeapFree */
521 static char* ALSA_strdup(char *s) {
522 char *result = HeapAlloc(GetProcessHeap(), 0, strlen(s)+1);
527 /******************************************************************
528 * ALSA_GetDeviceFromReg
530 * Returns either "default" or reads the registry so the user can
531 * override the playback/record device used.
533 char *ALSA_GetDeviceFromReg(char *value)
537 HKEY playbackKey = 0;
541 res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\ALSA", 0, KEY_QUERY_VALUE, &playbackKey);
542 if (res != ERROR_SUCCESS) goto end;
544 res = RegQueryValueExA(playbackKey, value, NULL, &type, NULL, &resultSize);
545 if (res != ERROR_SUCCESS) goto end;
547 if (type != REG_SZ) {
548 ERR("Registry key [HKEY_LOCAL_MACHINE\\Software\\Wine\\Wine\\ALSA\\%s] must be a string\n", value);
552 result = HeapAlloc(GetProcessHeap(), 0, resultSize);
553 res = RegQueryValueExA(playbackKey, value, NULL, NULL, result, &resultSize);
556 if (!result) result = ALSA_strdup("default");
557 if (playbackKey) RegCloseKey(playbackKey);
561 /******************************************************************
564 * Initialize internal structures from ALSA information
566 LONG ALSA_WaveInit(void)
569 snd_pcm_info_t * info;
570 snd_pcm_hw_params_t * hw_params;
571 unsigned int ratemin=0;
572 unsigned int ratemax=0;
573 unsigned int chmin=0;
574 unsigned int chmax=0;
582 /* FIXME: use better values */
583 wwo->device = ALSA_GetDeviceFromReg("PlaybackDevice");
584 TRACE("using waveout device \"%s\"\n", wwo->device);
586 snprintf(wwo->interface_name, sizeof(wwo->interface_name), "winealsa: %s", wwo->device);
588 wwo->caps.wMid = 0x0002;
589 wwo->caps.wPid = 0x0104;
590 strcpy(wwo->caps.szPname, "SB16 Wave Out");
591 wwo->caps.vDriverVersion = 0x0100;
592 wwo->caps.dwFormats = 0x00000000;
593 wwo->caps.dwSupport = WAVECAPS_VOLUME;
594 strcpy(wwo->ds_desc.szDesc, "WineALSA DirectSound Driver");
595 strcpy(wwo->ds_desc.szDrvName, "winealsa.drv");
596 wwo->ds_guid = DSDEVID_DefaultPlayback;
598 if (!wine_dlopen("libasound.so.2", RTLD_LAZY|RTLD_GLOBAL, NULL, 0))
600 ERR("Error: ALSA lib needs to be loaded with flags RTLD_LAZY and RTLD_GLOBAL.\n");
604 snd_pcm_info_alloca(&info);
605 snd_pcm_hw_params_alloca(&hw_params);
607 #define EXIT_ON_ERROR(f,txt) do { int err; if ( (err = (f) ) < 0) { ERR(txt ": %s\n", snd_strerror(err)); if (h) snd_pcm_close(h); return -1; } } while(0)
611 EXIT_ON_ERROR( snd_pcm_open(&h, wwo->device, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK) , "open pcm" );
615 EXIT_ON_ERROR( snd_pcm_info(h, info) , "pcm info" );
617 TRACE("dev=%d id=%s name=%s subdev=%d subdev_name=%s subdev_avail=%d subdev_num=%d stream=%s subclass=%s \n",
618 snd_pcm_info_get_device(info),
619 snd_pcm_info_get_id(info),
620 snd_pcm_info_get_name(info),
621 snd_pcm_info_get_subdevice(info),
622 snd_pcm_info_get_subdevice_name(info),
623 snd_pcm_info_get_subdevices_avail(info),
624 snd_pcm_info_get_subdevices_count(info),
625 snd_pcm_stream_name(snd_pcm_info_get_stream(info)),
626 (snd_pcm_info_get_subclass(info) == SND_PCM_SUBCLASS_GENERIC_MIX ? "GENERIC MIX": "MULTI MIX"));
628 EXIT_ON_ERROR( snd_pcm_hw_params_any(h, hw_params) , "pcm hw params" );
631 err = snd_pcm_hw_params_get_rate_min(hw_params, &ratemin, &dir);
632 err = snd_pcm_hw_params_get_rate_max(hw_params, &ratemax, &dir);
633 err = snd_pcm_hw_params_get_channels_min(hw_params, &chmin);
634 err = snd_pcm_hw_params_get_channels_max(hw_params, &chmax);
636 ALSA_TraceParameters(hw_params, NULL, TRUE);
639 snd_pcm_format_mask_t * fmask;
641 snd_pcm_format_mask_alloca(&fmask);
642 snd_pcm_hw_params_get_format_mask(hw_params, fmask);
645 if ( (r) >= ratemin && ( (r) <= ratemax || ratemax == -1) ) \
647 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_U8)) \
649 if (chmin <= 1 && 1 <= chmax) \
650 wwo->caps.dwFormats |= WAVE_FORMAT_##v##M08; \
651 if (chmin <= 2 && 2 <= chmax) \
652 wwo->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
654 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_S16_LE)) \
656 if (chmin <= 1 && 1 <= chmax) \
657 wwo->caps.dwFormats |= WAVE_FORMAT_##v##M16; \
658 if (chmin <= 2 && 2 <= chmax) \
659 wwo->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
670 if ( chmin > 1) FIXME("-\n");
671 wwo->caps.wChannels = (chmax >= 2) ? 2 : 1;
672 if (chmin <= 2 && 2 <= chmax)
673 wwo->caps.dwSupport |= WAVECAPS_LRVOLUME;
675 /* FIXME: always true ? */
676 wwo->caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
679 snd_pcm_access_mask_t * acmask;
680 snd_pcm_access_mask_alloca(&acmask);
681 snd_pcm_hw_params_get_access_mask(hw_params, acmask);
683 /* FIXME: NONITERLEAVED and COMPLEX are not supported right now */
684 if ( snd_pcm_access_mask_test( acmask, SND_PCM_ACCESS_MMAP_INTERLEAVED ) )
685 wwo->caps.dwSupport |= WAVECAPS_DIRECTSOUND;
688 TRACE("Configured with dwFmts=%08lx dwSupport=%08lx\n",
689 wwo->caps.dwFormats, wwo->caps.dwSupport);
693 ALSA_InitializeVolumeCtl(wwo);
697 /* FIXME: use better values */
698 wwi->device = ALSA_GetDeviceFromReg("RecordDevice");
699 TRACE("using wavein device \"%s\"\n", wwi->device);
701 snprintf(wwi->interface_name, sizeof(wwi->interface_name), "winealsa: %s", wwi->device);
703 wwi->caps.wMid = 0x0002;
704 wwi->caps.wPid = 0x0104;
705 strcpy(wwi->caps.szPname, "SB16 Wave In");
706 wwi->caps.vDriverVersion = 0x0100;
707 wwi->caps.dwFormats = 0x00000000;
708 wwi->caps.dwSupport = WAVECAPS_VOLUME;
709 strcpy(wwi->ds_desc.szDesc, "WineALSA DirectSound Driver");
710 strcpy(wwi->ds_desc.szDrvName, "winealsa.drv");
711 wwi->ds_guid = DSDEVID_DefaultPlayback;
713 snd_pcm_info_alloca(&info);
714 snd_pcm_hw_params_alloca(&hw_params);
716 #define EXIT_ON_ERROR(f,txt) do { int err; if ( (err = (f) ) < 0) { ERR(txt ": %s\n", snd_strerror(err)); if (h) snd_pcm_close(h); return -1; } } while(0)
720 EXIT_ON_ERROR( snd_pcm_open(&h, wwi->device, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK) , "open pcm" );
724 EXIT_ON_ERROR( snd_pcm_info(h, info) , "pcm info" );
726 TRACE("dev=%d id=%s name=%s subdev=%d subdev_name=%s subdev_avail=%d subdev_num=%d stream=%s subclass=%s \n",
727 snd_pcm_info_get_device(info),
728 snd_pcm_info_get_id(info),
729 snd_pcm_info_get_name(info),
730 snd_pcm_info_get_subdevice(info),
731 snd_pcm_info_get_subdevice_name(info),
732 snd_pcm_info_get_subdevices_avail(info),
733 snd_pcm_info_get_subdevices_count(info),
734 snd_pcm_stream_name(snd_pcm_info_get_stream(info)),
735 (snd_pcm_info_get_subclass(info) == SND_PCM_SUBCLASS_GENERIC_MIX ? "GENERIC MIX": "MULTI MIX"));
737 EXIT_ON_ERROR( snd_pcm_hw_params_any(h, hw_params) , "pcm hw params" );
739 err = snd_pcm_hw_params_get_rate_min(hw_params, &ratemin, &dir);
740 err = snd_pcm_hw_params_get_rate_max(hw_params, &ratemax, &dir);
741 err = snd_pcm_hw_params_get_channels_min(hw_params, &chmin);
742 err = snd_pcm_hw_params_get_channels_max(hw_params, &chmax);
745 ALSA_TraceParameters(hw_params, NULL, TRUE);
748 snd_pcm_format_mask_t * fmask;
750 snd_pcm_format_mask_alloca(&fmask);
751 snd_pcm_hw_params_get_format_mask(hw_params, fmask);
754 if ( (r) >= ratemin && ( (r) <= ratemax || ratemax == -1) ) \
756 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_U8)) \
758 if (chmin <= 1 && 1 <= chmax) \
759 wwi->caps.dwFormats |= WAVE_FORMAT_##v##M08; \
760 if (chmin <= 2 && 2 <= chmax) \
761 wwi->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
763 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_S16_LE)) \
765 if (chmin <= 1 && 1 <= chmax) \
766 wwi->caps.dwFormats |= WAVE_FORMAT_##v##M16; \
767 if (chmin <= 2 && 2 <= chmax) \
768 wwi->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
779 if ( chmin > 1) FIXME("-\n");
780 wwi->caps.wChannels = (chmax >= 2) ? 2 : 1;
781 if (chmin <= 2 && 2 <= chmax)
782 wwi->caps.dwSupport |= WAVECAPS_LRVOLUME;
784 /* FIXME: always true ? */
785 wwi->caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
788 snd_pcm_access_mask_t * acmask;
789 snd_pcm_access_mask_alloca(&acmask);
790 snd_pcm_hw_params_get_access_mask(hw_params, acmask);
792 /* FIXME: NONITERLEAVED and COMPLEX are not supported right now */
793 if ( snd_pcm_access_mask_test( acmask, SND_PCM_ACCESS_MMAP_INTERLEAVED ) )
794 wwi->caps.dwSupport |= WAVECAPS_DIRECTSOUND;
797 TRACE("Configured with dwFmts=%08lx dwSupport=%08lx\n",
798 wwi->caps.dwFormats, wwi->caps.dwSupport);
805 /******************************************************************
806 * ALSA_InitRingMessage
808 * Initialize the ring of messages for passing between driver's caller and playback/record
811 static int ALSA_InitRingMessage(ALSA_MSG_RING* omr)
816 if (pipe(omr->msg_pipe) < 0) {
817 omr->msg_pipe[0] = -1;
818 omr->msg_pipe[1] = -1;
819 ERR("could not create pipe, error=%s\n", strerror(errno));
822 omr->msg_event = CreateEventA(NULL, FALSE, FALSE, NULL);
824 omr->ring_buffer_size = ALSA_RING_BUFFER_INCREMENT;
825 omr->messages = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,omr->ring_buffer_size * sizeof(ALSA_MSG));
827 InitializeCriticalSection(&omr->msg_crst);
831 /******************************************************************
832 * ALSA_DestroyRingMessage
835 static int ALSA_DestroyRingMessage(ALSA_MSG_RING* omr)
838 close(omr->msg_pipe[0]);
839 close(omr->msg_pipe[1]);
841 CloseHandle(omr->msg_event);
843 HeapFree(GetProcessHeap(),0,omr->messages);
844 DeleteCriticalSection(&omr->msg_crst);
848 /******************************************************************
849 * ALSA_AddRingMessage
851 * Inserts a new message into the ring (should be called from DriverProc derivated routines)
853 static int ALSA_AddRingMessage(ALSA_MSG_RING* omr, enum win_wm_message msg, DWORD param, BOOL wait)
855 HANDLE hEvent = INVALID_HANDLE_VALUE;
857 EnterCriticalSection(&omr->msg_crst);
858 if ((omr->msg_toget == ((omr->msg_tosave + 1) % omr->ring_buffer_size)))
860 int old_ring_buffer_size = omr->ring_buffer_size;
861 omr->ring_buffer_size += ALSA_RING_BUFFER_INCREMENT;
862 TRACE("omr->ring_buffer_size=%d\n",omr->ring_buffer_size);
863 omr->messages = HeapReAlloc(GetProcessHeap(),0,omr->messages, omr->ring_buffer_size * sizeof(ALSA_MSG));
864 /* Now we need to rearrange the ring buffer so that the new
865 buffers just allocated are in between omr->msg_tosave and
868 if (omr->msg_tosave < omr->msg_toget)
870 memmove(&(omr->messages[omr->msg_toget + ALSA_RING_BUFFER_INCREMENT]),
871 &(omr->messages[omr->msg_toget]),
872 sizeof(ALSA_MSG)*(old_ring_buffer_size - omr->msg_toget)
874 omr->msg_toget += ALSA_RING_BUFFER_INCREMENT;
879 hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
880 if (hEvent == INVALID_HANDLE_VALUE)
882 ERR("can't create event !?\n");
883 LeaveCriticalSection(&omr->msg_crst);
886 if (omr->msg_toget != omr->msg_tosave && omr->messages[omr->msg_toget].msg != WINE_WM_HEADER)
887 FIXME("two fast messages in the queue!!!!\n");
889 /* fast messages have to be added at the start of the queue */
890 omr->msg_toget = (omr->msg_toget + omr->ring_buffer_size - 1) % omr->ring_buffer_size;
892 omr->messages[omr->msg_toget].msg = msg;
893 omr->messages[omr->msg_toget].param = param;
894 omr->messages[omr->msg_toget].hEvent = hEvent;
898 omr->messages[omr->msg_tosave].msg = msg;
899 omr->messages[omr->msg_tosave].param = param;
900 omr->messages[omr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
901 omr->msg_tosave = (omr->msg_tosave + 1) % omr->ring_buffer_size;
903 LeaveCriticalSection(&omr->msg_crst);
904 /* signal a new message */
908 /* wait for playback/record thread to have processed the message */
909 WaitForSingleObject(hEvent, INFINITE);
915 /******************************************************************
916 * ALSA_RetrieveRingMessage
918 * Get a message from the ring. Should be called by the playback/record thread.
920 static int ALSA_RetrieveRingMessage(ALSA_MSG_RING* omr,
921 enum win_wm_message *msg, DWORD *param, HANDLE *hEvent)
923 EnterCriticalSection(&omr->msg_crst);
925 if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
927 LeaveCriticalSection(&omr->msg_crst);
931 *msg = omr->messages[omr->msg_toget].msg;
932 omr->messages[omr->msg_toget].msg = 0;
933 *param = omr->messages[omr->msg_toget].param;
934 *hEvent = omr->messages[omr->msg_toget].hEvent;
935 omr->msg_toget = (omr->msg_toget + 1) % omr->ring_buffer_size;
937 LeaveCriticalSection(&omr->msg_crst);
941 /******************************************************************
942 * ALSA_PeekRingMessage
944 * Peek at a message from the ring but do not remove it.
945 * Should be called by the playback/record thread.
947 static int ALSA_PeekRingMessage(ALSA_MSG_RING* omr,
948 enum win_wm_message *msg,
949 DWORD *param, HANDLE *hEvent)
951 EnterCriticalSection(&omr->msg_crst);
953 if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
955 LeaveCriticalSection(&omr->msg_crst);
959 *msg = omr->messages[omr->msg_toget].msg;
960 *param = omr->messages[omr->msg_toget].param;
961 *hEvent = omr->messages[omr->msg_toget].hEvent;
962 LeaveCriticalSection(&omr->msg_crst);
966 /*======================================================================*
967 * Low level WAVE OUT implementation *
968 *======================================================================*/
970 /**************************************************************************
971 * wodNotifyClient [internal]
973 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
975 TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
981 if (wwo->wFlags != DCB_NULL &&
982 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags, (HDRVR)wwo->waveDesc.hWave,
983 wMsg, wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
984 WARN("can't notify client !\n");
985 return MMSYSERR_ERROR;
989 FIXME("Unknown callback message %u\n", wMsg);
990 return MMSYSERR_INVALPARAM;
992 return MMSYSERR_NOERROR;
995 /**************************************************************************
996 * wodUpdatePlayedTotal [internal]
999 static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo, snd_pcm_status_t* ps)
1001 snd_pcm_sframes_t delay = 0;
1002 snd_pcm_delay(wwo->p_handle, &delay);
1003 wwo->dwPlayedTotal = wwo->dwWrittenTotal - snd_pcm_frames_to_bytes(wwo->p_handle, delay);
1007 /**************************************************************************
1008 * wodPlayer_BeginWaveHdr [internal]
1010 * Makes the specified lpWaveHdr the currently playing wave header.
1011 * If the specified wave header is a begin loop and we're not already in
1012 * a loop, setup the loop.
1014 static void wodPlayer_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1016 wwo->lpPlayPtr = lpWaveHdr;
1018 if (!lpWaveHdr) return;
1020 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
1021 if (wwo->lpLoopPtr) {
1022 WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1024 TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1025 wwo->lpLoopPtr = lpWaveHdr;
1026 /* Windows does not touch WAVEHDR.dwLoops,
1027 * so we need to make an internal copy */
1028 wwo->dwLoops = lpWaveHdr->dwLoops;
1031 wwo->dwPartialOffset = 0;
1034 /**************************************************************************
1035 * wodPlayer_PlayPtrNext [internal]
1037 * Advance the play pointer to the next waveheader, looping if required.
1039 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEOUT* wwo)
1041 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1043 wwo->dwPartialOffset = 0;
1044 if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
1045 /* We're at the end of a loop, loop if required */
1046 if (--wwo->dwLoops > 0) {
1047 wwo->lpPlayPtr = wwo->lpLoopPtr;
1049 /* Handle overlapping loops correctly */
1050 if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
1051 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
1052 /* shall we consider the END flag for the closing loop or for
1053 * the opening one or for both ???
1054 * code assumes for closing loop only
1057 lpWaveHdr = lpWaveHdr->lpNext;
1059 wwo->lpLoopPtr = NULL;
1060 wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
1063 /* We're not in a loop. Advance to the next wave header */
1064 wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
1070 /**************************************************************************
1071 * wodPlayer_DSPWait [internal]
1072 * Returns the number of milliseconds to wait for the DSP buffer to play a
1075 static DWORD wodPlayer_DSPWait(const WINE_WAVEOUT *wwo)
1077 /* time for one period to be played */
1081 err = snd_pcm_hw_params_get_period_time(wwo->hw_params, &val, &dir);
1085 /**************************************************************************
1086 * wodPlayer_NotifyWait [internal]
1087 * Returns the number of milliseconds to wait before attempting to notify
1088 * completion of the specified wavehdr.
1089 * This is based on the number of bytes remaining to be written in the
1092 static DWORD wodPlayer_NotifyWait(const WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1096 if (lpWaveHdr->reserved < wwo->dwPlayedTotal) {
1099 dwMillis = (lpWaveHdr->reserved - wwo->dwPlayedTotal) * 1000 / wwo->format.wf.nAvgBytesPerSec;
1100 if (!dwMillis) dwMillis = 1;
1107 /**************************************************************************
1108 * wodPlayer_WriteMaxFrags [internal]
1109 * Writes the maximum number of frames possible to the DSP and returns
1110 * the number of frames written.
1112 static int wodPlayer_WriteMaxFrags(WINE_WAVEOUT* wwo, DWORD* frames)
1114 /* Only attempt to write to free frames */
1115 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1116 DWORD dwLength = snd_pcm_bytes_to_frames(wwo->p_handle, lpWaveHdr->dwBufferLength - wwo->dwPartialOffset);
1117 int toWrite = min(dwLength, *frames);
1120 TRACE("Writing wavehdr %p.%lu[%lu]\n", lpWaveHdr, wwo->dwPartialOffset, lpWaveHdr->dwBufferLength);
1122 written = (wwo->write)(wwo->p_handle, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
1125 /* XRUN occurred. let's try to recover */
1126 ALSA_XRUNRecovery(wwo, written);
1127 written = (wwo->write)(wwo->p_handle, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
1131 /* still in error */
1132 ERR("Error in writing wavehdr. Reason: %s\n", snd_strerror(written));
1136 wwo->dwPartialOffset += snd_pcm_frames_to_bytes(wwo->p_handle, written);
1137 if ( wwo->dwPartialOffset >= lpWaveHdr->dwBufferLength) {
1138 /* this will be used to check if the given wave header has been fully played or not... */
1139 wwo->dwPartialOffset = lpWaveHdr->dwBufferLength;
1140 /* If we wrote all current wavehdr, skip to the next one */
1141 wodPlayer_PlayPtrNext(wwo);
1144 wwo->dwWrittenTotal += snd_pcm_frames_to_bytes(wwo->p_handle, written);
1150 /**************************************************************************
1151 * wodPlayer_NotifyCompletions [internal]
1153 * Notifies and remove from queue all wavehdrs which have been played to
1154 * the speaker (ie. they have cleared the ALSA buffer). If force is true,
1155 * we notify all wavehdrs and remove them all from the queue even if they
1156 * are unplayed or part of a loop.
1158 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1160 LPWAVEHDR lpWaveHdr;
1162 /* Start from lpQueuePtr and keep notifying until:
1163 * - we hit an unwritten wavehdr
1164 * - we hit the beginning of a running loop
1165 * - we hit a wavehdr which hasn't finished playing
1168 while ((lpWaveHdr = wwo->lpQueuePtr) &&
1170 (lpWaveHdr != wwo->lpPlayPtr &&
1171 lpWaveHdr != wwo->lpLoopPtr &&
1172 lpWaveHdr->reserved <= wwo->dwPlayedTotal))) {
1174 wwo->lpQueuePtr = lpWaveHdr->lpNext;
1176 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1177 lpWaveHdr->dwFlags |= WHDR_DONE;
1179 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1184 lpWaveHdr = wwo->lpQueuePtr;
1185 if (!lpWaveHdr) {TRACE("Empty queue\n"); break;}
1188 if (lpWaveHdr == wwo->lpPlayPtr) {TRACE("play %p\n", lpWaveHdr); break;}
1189 if (lpWaveHdr == wwo->lpLoopPtr) {TRACE("loop %p\n", lpWaveHdr); break;}
1190 if (lpWaveHdr->reserved > wwo->dwPlayedTotal){TRACE("still playing %p (%lu/%lu)\n", lpWaveHdr, lpWaveHdr->reserved, wwo->dwPlayedTotal);break;}
1192 wwo->lpQueuePtr = lpWaveHdr->lpNext;
1194 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1195 lpWaveHdr->dwFlags |= WHDR_DONE;
1197 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1200 return (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
1201 wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
1205 void wait_for_poll(snd_pcm_t *handle, struct pollfd *ufds, unsigned int count)
1207 unsigned short revents;
1209 if (snd_pcm_state(handle) != SND_PCM_STATE_RUNNING)
1213 poll(ufds, count, -1);
1214 snd_pcm_poll_descriptors_revents(handle, ufds, count, &revents);
1216 if (revents & POLLERR)
1219 /*if (revents & POLLOUT)
1225 /**************************************************************************
1226 * wodPlayer_Reset [internal]
1228 * wodPlayer helper. Resets current output stream.
1230 static void wodPlayer_Reset(WINE_WAVEOUT* wwo)
1232 enum win_wm_message msg;
1237 /* flush all possible output */
1238 wait_for_poll(wwo->p_handle, wwo->ufds, wwo->count);
1240 wodUpdatePlayedTotal(wwo, NULL);
1241 /* updates current notify list */
1242 wodPlayer_NotifyCompletions(wwo, FALSE);
1244 if ( (err = snd_pcm_drop(wwo->p_handle)) < 0) {
1245 FIXME("flush: %s\n", snd_strerror(err));
1247 wwo->state = WINE_WS_STOPPED;
1250 if ( (err = snd_pcm_prepare(wwo->p_handle)) < 0 )
1251 ERR("pcm prepare failed: %s\n", snd_strerror(err));
1253 /* remove any buffer */
1254 wodPlayer_NotifyCompletions(wwo, TRUE);
1256 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1257 wwo->state = WINE_WS_STOPPED;
1258 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1259 /* Clear partial wavehdr */
1260 wwo->dwPartialOffset = 0;
1262 /* remove any existing message in the ring */
1263 EnterCriticalSection(&wwo->msgRing.msg_crst);
1264 /* return all pending headers in queue */
1265 while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, ¶m, &ev))
1267 if (msg != WINE_WM_HEADER)
1269 FIXME("shouldn't have headers left\n");
1273 ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
1274 ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
1276 wodNotifyClient(wwo, WOM_DONE, param, 0);
1278 RESET_OMR(&wwo->msgRing);
1279 LeaveCriticalSection(&wwo->msgRing.msg_crst);
1282 /**************************************************************************
1283 * wodPlayer_ProcessMessages [internal]
1285 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
1287 LPWAVEHDR lpWaveHdr;
1288 enum win_wm_message msg;
1293 while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, ¶m, &ev)) {
1294 TRACE("Received %s %lx\n", wodPlayerCmdString[msg - WM_USER - 1], param);
1297 case WINE_WM_PAUSING:
1298 if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_RUNNING )
1300 err = snd_pcm_pause(wwo->p_handle, 1);
1302 ERR("pcm_pause failed: %s\n", snd_strerror(err));
1304 wwo->state = WINE_WS_PAUSED;
1307 case WINE_WM_RESTARTING:
1308 if (wwo->state == WINE_WS_PAUSED)
1310 if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_PAUSED )
1312 err = snd_pcm_pause(wwo->p_handle, 0);
1314 ERR("pcm_pause failed: %s\n", snd_strerror(err));
1316 wwo->state = WINE_WS_PLAYING;
1320 case WINE_WM_HEADER:
1321 lpWaveHdr = (LPWAVEHDR)param;
1323 /* insert buffer at the end of queue */
1326 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1329 if (!wwo->lpPlayPtr)
1330 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
1331 if (wwo->state == WINE_WS_STOPPED)
1332 wwo->state = WINE_WS_PLAYING;
1334 case WINE_WM_RESETTING:
1335 wodPlayer_Reset(wwo);
1338 case WINE_WM_UPDATE:
1339 wodUpdatePlayedTotal(wwo, NULL);
1342 case WINE_WM_BREAKLOOP:
1343 if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
1344 /* ensure exit at end of current loop */
1349 case WINE_WM_CLOSING:
1350 /* sanity check: this should not happen since the device must have been reset before */
1351 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1353 wwo->state = WINE_WS_CLOSED;
1356 /* shouldn't go here */
1358 FIXME("unknown message %d\n", msg);
1364 /**************************************************************************
1365 * wodPlayer_FeedDSP [internal]
1366 * Feed as much sound data as we can into the DSP and return the number of
1367 * milliseconds before it will be necessary to feed the DSP again.
1369 static DWORD wodPlayer_FeedDSP(WINE_WAVEOUT* wwo)
1373 wodUpdatePlayedTotal(wwo, NULL);
1374 availInQ = snd_pcm_avail_update(wwo->p_handle);
1377 /* input queue empty and output buffer with less than one fragment to play */
1378 if (!wwo->lpPlayPtr && wwo->dwBufferSize < availInQ + wwo->dwFragmentSize) {
1379 TRACE("Run out of wavehdr:s...\n");
1384 /* no more room... no need to try to feed */
1386 /* Feed from partial wavehdr */
1387 if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0) {
1388 wodPlayer_WriteMaxFrags(wwo, &availInQ);
1391 /* Feed wavehdrs until we run out of wavehdrs or DSP space */
1392 if (wwo->dwPartialOffset == 0 && wwo->lpPlayPtr) {
1394 TRACE("Setting time to elapse for %p to %lu\n",
1395 wwo->lpPlayPtr, wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength);
1396 /* note the value that dwPlayedTotal will return when this wave finishes playing */
1397 wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
1398 } while (wodPlayer_WriteMaxFrags(wwo, &availInQ) && wwo->lpPlayPtr && availInQ > 0);
1402 return wodPlayer_DSPWait(wwo);
1405 /**************************************************************************
1406 * wodPlayer [internal]
1408 static DWORD CALLBACK wodPlayer(LPVOID pmt)
1410 WORD uDevID = (DWORD)pmt;
1411 WINE_WAVEOUT* wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
1412 DWORD dwNextFeedTime = INFINITE; /* Time before DSP needs feeding */
1413 DWORD dwNextNotifyTime = INFINITE; /* Time before next wave completion */
1416 wwo->state = WINE_WS_STOPPED;
1417 SetEvent(wwo->hStartUpEvent);
1420 /** Wait for the shortest time before an action is required. If there
1421 * are no pending actions, wait forever for a command.
1423 dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
1424 TRACE("waiting %lums (%lu,%lu)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
1425 WAIT_OMR(&wwo->msgRing, dwSleepTime);
1426 wodPlayer_ProcessMessages(wwo);
1427 if (wwo->state == WINE_WS_PLAYING) {
1428 dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1429 dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1430 if (dwNextFeedTime == INFINITE) {
1431 /* FeedDSP ran out of data, but before giving up, */
1432 /* check that a notification didn't give us more */
1433 wodPlayer_ProcessMessages(wwo);
1434 if (wwo->lpPlayPtr) {
1435 TRACE("recovering\n");
1436 dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1440 dwNextFeedTime = dwNextNotifyTime = INFINITE;
1445 /**************************************************************************
1446 * wodGetDevCaps [internal]
1448 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSA lpCaps, DWORD dwSize)
1450 TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1452 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1454 if (wDevID >= MAX_WAVEOUTDRV) {
1455 TRACE("MAX_WAVOUTDRV reached !\n");
1456 return MMSYSERR_BADDEVICEID;
1459 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1460 return MMSYSERR_NOERROR;
1463 /**************************************************************************
1464 * wodOpen [internal]
1466 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1469 snd_pcm_hw_params_t * hw_params;
1470 snd_pcm_sw_params_t * sw_params;
1471 snd_pcm_access_t access;
1472 snd_pcm_format_t format;
1474 unsigned int buffer_time = 500000;
1475 unsigned int period_time = 10000;
1476 snd_pcm_uframes_t buffer_size;
1477 snd_pcm_uframes_t period_size;
1483 snd_pcm_hw_params_alloca(&hw_params);
1484 snd_pcm_sw_params_alloca(&sw_params);
1486 TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
1487 if (lpDesc == NULL) {
1488 WARN("Invalid Parameter !\n");
1489 return MMSYSERR_INVALPARAM;
1491 if (wDevID >= MAX_WAVEOUTDRV) {
1492 TRACE("MAX_WAVOUTDRV reached !\n");
1493 return MMSYSERR_BADDEVICEID;
1496 /* only PCM format is supported so far... */
1497 if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1498 lpDesc->lpFormat->nChannels == 0 ||
1499 lpDesc->lpFormat->nSamplesPerSec < DSBFREQUENCY_MIN ||
1500 lpDesc->lpFormat->nSamplesPerSec > DSBFREQUENCY_MAX ||
1501 (lpDesc->lpFormat->wBitsPerSample!=8 && lpDesc->lpFormat->wBitsPerSample!=16)) {
1502 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1503 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1504 lpDesc->lpFormat->nSamplesPerSec);
1505 return WAVERR_BADFORMAT;
1508 if (dwFlags & WAVE_FORMAT_QUERY) {
1509 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1510 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1511 lpDesc->lpFormat->nSamplesPerSec);
1512 return MMSYSERR_NOERROR;
1515 wwo = &WOutDev[wDevID];
1517 if ((dwFlags & WAVE_DIRECTSOUND) && !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
1518 /* not supported, ignore it */
1519 dwFlags &= ~WAVE_DIRECTSOUND;
1522 flags = SND_PCM_NONBLOCK;
1523 if ( dwFlags & WAVE_DIRECTSOUND )
1524 flags |= SND_PCM_ASYNC;
1526 if ( (err = snd_pcm_open(&pcm, wwo->device, SND_PCM_STREAM_PLAYBACK, flags)) < 0)
1528 ERR("Error open: %s\n", snd_strerror(err));
1529 return MMSYSERR_NOTENABLED;
1532 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1534 memcpy(&wwo->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
1535 memcpy(&wwo->format, lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1537 if (wwo->format.wBitsPerSample == 0) {
1538 WARN("Resetting zeroed wBitsPerSample\n");
1539 wwo->format.wBitsPerSample = 8 *
1540 (wwo->format.wf.nAvgBytesPerSec /
1541 wwo->format.wf.nSamplesPerSec) /
1542 wwo->format.wf.nChannels;
1545 snd_pcm_hw_params_any(pcm, hw_params);
1547 #define EXIT_ON_ERROR(f,e,txt) do \
1550 if ( (err = (f) ) < 0) \
1552 ERR(txt ": %s\n", snd_strerror(err)); \
1553 snd_pcm_close(pcm); \
1558 access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
1559 if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
1560 WARN("mmap not available. switching to standard write.\n");
1561 access = SND_PCM_ACCESS_RW_INTERLEAVED;
1562 EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
1563 wwo->write = snd_pcm_writei;
1566 wwo->write = snd_pcm_mmap_writei;
1568 EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwo->format.wf.nChannels), MMSYSERR_INVALPARAM, "unable to set required channels");
1570 format = (wwo->format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE : SND_PCM_FORMAT_U8;
1571 EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), MMSYSERR_INVALPARAM, "unable to set required format");
1573 rate = wwo->format.wf.nSamplesPerSec;
1575 err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
1577 ERR("Rate %ld Hz not available for playback: %s\n", wwo->format.wf.nSamplesPerSec, snd_strerror(rate));
1579 return WAVERR_BADFORMAT;
1581 if (rate != wwo->format.wf.nSamplesPerSec) {
1582 ERR("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwo->format.wf.nSamplesPerSec, rate);
1584 return WAVERR_BADFORMAT;
1587 EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
1589 EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
1591 EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
1593 err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
1594 err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
1596 snd_pcm_sw_params_current(pcm, sw_params);
1597 EXIT_ON_ERROR( snd_pcm_sw_params_set_start_threshold(pcm, sw_params, dwFlags & WAVE_DIRECTSOUND ? INT_MAX : 1 ), MMSYSERR_ERROR, "unable to set start threshold");
1598 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
1599 EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
1600 EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
1601 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
1602 EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
1603 #undef EXIT_ON_ERROR
1605 snd_pcm_prepare(pcm);
1608 ALSA_TraceParameters(hw_params, sw_params, FALSE);
1610 /* now, we can save all required data for later use... */
1611 if ( wwo->hw_params )
1612 snd_pcm_hw_params_free(wwo->hw_params);
1613 snd_pcm_hw_params_malloc(&(wwo->hw_params));
1614 snd_pcm_hw_params_copy(wwo->hw_params, hw_params);
1616 wwo->dwBufferSize = buffer_size;
1617 wwo->lpQueuePtr = wwo->lpPlayPtr = wwo->lpLoopPtr = NULL;
1618 wwo->p_handle = pcm;
1619 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1620 wwo->dwPartialOffset = 0;
1622 ALSA_InitRingMessage(&wwo->msgRing);
1624 wwo->count = snd_pcm_poll_descriptors_count (wwo->p_handle);
1625 if (wwo->count <= 0) {
1626 ERR("Invalid poll descriptors count\n");
1627 return MMSYSERR_ERROR;
1630 wwo->ufds = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct pollfd) * wwo->count);
1631 if (wwo->ufds == NULL) {
1632 ERR("No enough memory\n");
1633 return MMSYSERR_NOMEM;
1635 if ((err = snd_pcm_poll_descriptors(wwo->p_handle, wwo->ufds, wwo->count)) < 0) {
1636 ERR("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
1637 return MMSYSERR_ERROR;
1640 if (!(dwFlags & WAVE_DIRECTSOUND)) {
1641 wwo->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
1642 wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
1643 WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
1644 CloseHandle(wwo->hStartUpEvent);
1646 wwo->hThread = INVALID_HANDLE_VALUE;
1647 wwo->dwThreadID = 0;
1649 wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
1651 TRACE("handle=%08lx \n", (DWORD)wwo->p_handle);
1652 /* if (wwo->dwFragmentSize % wwo->format.wf.nBlockAlign)
1653 ERR("Fragment doesn't contain an integral number of data blocks\n");
1655 TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
1656 wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec,
1657 wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
1658 wwo->format.wf.nBlockAlign);
1660 return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
1664 /**************************************************************************
1665 * wodClose [internal]
1667 static DWORD wodClose(WORD wDevID)
1669 DWORD ret = MMSYSERR_NOERROR;
1672 TRACE("(%u);\n", wDevID);
1674 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1675 WARN("bad device ID !\n");
1676 return MMSYSERR_BADDEVICEID;
1679 wwo = &WOutDev[wDevID];
1680 if (wwo->lpQueuePtr) {
1681 WARN("buffers still playing !\n");
1682 ret = WAVERR_STILLPLAYING;
1684 if (wwo->hThread != INVALID_HANDLE_VALUE) {
1685 ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1687 ALSA_DestroyRingMessage(&wwo->msgRing);
1689 snd_pcm_hw_params_free(wwo->hw_params);
1690 wwo->hw_params = NULL;
1692 snd_pcm_close(wwo->p_handle);
1693 wwo->p_handle = NULL;
1695 ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1698 HeapFree(GetProcessHeap(), 0, wwo->ufds);
1703 /**************************************************************************
1704 * wodWrite [internal]
1707 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1709 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1711 /* first, do the sanity checks... */
1712 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1713 WARN("bad dev ID !\n");
1714 return MMSYSERR_BADDEVICEID;
1717 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1718 return WAVERR_UNPREPARED;
1720 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1721 return WAVERR_STILLPLAYING;
1723 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1724 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1725 lpWaveHdr->lpNext = 0;
1727 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1729 return MMSYSERR_NOERROR;
1732 /**************************************************************************
1733 * wodPrepare [internal]
1735 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1737 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1739 if (wDevID >= MAX_WAVEOUTDRV) {
1740 WARN("bad device ID !\n");
1741 return MMSYSERR_BADDEVICEID;
1744 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1745 return WAVERR_STILLPLAYING;
1747 lpWaveHdr->dwFlags |= WHDR_PREPARED;
1748 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1749 return MMSYSERR_NOERROR;
1752 /**************************************************************************
1753 * wodUnprepare [internal]
1755 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1757 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1759 if (wDevID >= MAX_WAVEOUTDRV) {
1760 WARN("bad device ID !\n");
1761 return MMSYSERR_BADDEVICEID;
1764 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1765 return WAVERR_STILLPLAYING;
1767 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1768 lpWaveHdr->dwFlags |= WHDR_DONE;
1770 return MMSYSERR_NOERROR;
1773 /**************************************************************************
1774 * wodPause [internal]
1776 static DWORD wodPause(WORD wDevID)
1778 TRACE("(%u);!\n", wDevID);
1780 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1781 WARN("bad device ID !\n");
1782 return MMSYSERR_BADDEVICEID;
1785 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1787 return MMSYSERR_NOERROR;
1790 /**************************************************************************
1791 * wodRestart [internal]
1793 static DWORD wodRestart(WORD wDevID)
1795 TRACE("(%u);\n", wDevID);
1797 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1798 WARN("bad device ID !\n");
1799 return MMSYSERR_BADDEVICEID;
1802 if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1803 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1806 /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1807 /* FIXME: Myst crashes with this ... hmm -MM
1808 return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1811 return MMSYSERR_NOERROR;
1814 /**************************************************************************
1815 * wodReset [internal]
1817 static DWORD wodReset(WORD wDevID)
1819 TRACE("(%u);\n", wDevID);
1821 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1822 WARN("bad device ID !\n");
1823 return MMSYSERR_BADDEVICEID;
1826 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1828 return MMSYSERR_NOERROR;
1831 /**************************************************************************
1832 * wodGetPosition [internal]
1834 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1840 TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1842 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1843 WARN("bad device ID !\n");
1844 return MMSYSERR_BADDEVICEID;
1847 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1849 wwo = &WOutDev[wDevID];
1850 ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1851 val = wwo->dwPlayedTotal;
1853 TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
1854 lpTime->wType, wwo->format.wBitsPerSample,
1855 wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
1856 wwo->format.wf.nAvgBytesPerSec);
1857 TRACE("dwPlayedTotal=%lu\n", val);
1859 switch (lpTime->wType) {
1862 TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
1865 lpTime->u.sample = val * 8 / wwo->format.wBitsPerSample /wwo->format.wf.nChannels;
1866 TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
1869 time = (double)val / (double)wwo->format.wf.nAvgBytesPerSec;
1870 lpTime->u.smpte.hour = time / (60 * 60);
1871 time -= lpTime->u.smpte.hour * (60 * 60);
1872 lpTime->u.smpte.min = time / 60;
1873 time -= lpTime->u.smpte.min * 60;
1874 lpTime->u.smpte.sec = time;
1875 time -= lpTime->u.smpte.sec;
1876 lpTime->u.smpte.frame = round(time * 30);
1877 lpTime->u.smpte.fps = 30;
1878 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
1879 lpTime->u.smpte.hour, lpTime->u.smpte.min,
1880 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
1883 FIXME("Format %d not supported ! use TIME_MS !\n", lpTime->wType);
1884 lpTime->wType = TIME_MS;
1886 lpTime->u.ms = val * 1000.0 / wwo->format.wf.nAvgBytesPerSec;
1887 TRACE("TIME_MS=%lu\n", lpTime->u.ms);
1890 return MMSYSERR_NOERROR;
1893 /**************************************************************************
1894 * wodBreakLoop [internal]
1896 static DWORD wodBreakLoop(WORD wDevID)
1898 TRACE("(%u);\n", wDevID);
1900 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1901 WARN("bad device ID !\n");
1902 return MMSYSERR_BADDEVICEID;
1904 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
1905 return MMSYSERR_NOERROR;
1908 /**************************************************************************
1909 * wodGetVolume [internal]
1911 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1918 TRACE("(%u, %p);\n", wDevID, lpdwVol);
1919 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1920 WARN("bad device ID !\n");
1921 return MMSYSERR_BADDEVICEID;
1923 wwo = &WOutDev[wDevID];
1924 count = snd_ctl_elem_info_get_count(wwo->playback_einfo);
1925 min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
1926 max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
1928 #define VOLUME_ALSA_TO_WIN(x) (((x)-min) * 65536 /(max-min))
1929 if (lpdwVol == NULL)
1930 return MMSYSERR_NOTENABLED;
1935 left = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
1936 right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 1));
1939 left = right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
1942 WARN("%d channels mixer not supported\n", count);
1943 return MMSYSERR_NOERROR;
1945 #undef VOLUME_ALSA_TO_WIN
1947 TRACE("left=%d right=%d !\n", left, right);
1948 *lpdwVol = MAKELONG( left, right );
1949 return MMSYSERR_NOERROR;
1952 /**************************************************************************
1953 * wodSetVolume [internal]
1955 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1962 TRACE("(%u, %08lX);\n", wDevID, dwParam);
1963 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1964 WARN("bad device ID !\n");
1965 return MMSYSERR_BADDEVICEID;
1967 wwo = &WOutDev[wDevID];
1968 count=snd_ctl_elem_info_get_count(wwo->playback_einfo);
1969 min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
1970 max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
1972 left = LOWORD(dwParam);
1973 right = HIWORD(dwParam);
1975 #define VOLUME_WIN_TO_ALSA(x) ( (((x) * (max-min)) / 65536) + min )
1979 snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
1980 snd_ctl_elem_value_set_integer(wwo->playback_evalue, 1, VOLUME_WIN_TO_ALSA(right));
1983 snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
1986 WARN("%d channels mixer not supported\n", count);
1988 #undef VOLUME_WIN_TO_ALSA
1989 if ( (err = snd_ctl_elem_write(wwo->ctl, wwo->playback_evalue)) < 0)
1991 ERR("error writing snd_ctl_elem_value: %s\n", snd_strerror(err));
1993 return MMSYSERR_NOERROR;
1996 /**************************************************************************
1997 * wodGetNumDevs [internal]
1999 static DWORD wodGetNumDevs(void)
2001 return ALSA_WodNumDevs;
2004 /**************************************************************************
2005 * wodDevInterfaceSize [internal]
2007 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2009 TRACE("(%u, %p)\n", wDevID, dwParam1);
2011 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2012 NULL, 0 ) * sizeof(WCHAR);
2013 return MMSYSERR_NOERROR;
2016 /**************************************************************************
2017 * wodDevInterface [internal]
2019 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2021 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2022 NULL, 0 ) * sizeof(WCHAR))
2024 MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2025 dwParam1, dwParam2 / sizeof(WCHAR));
2026 return MMSYSERR_NOERROR;
2028 return MMSYSERR_INVALPARAM;
2031 /**************************************************************************
2032 * wodMessage (WINEALSA.@)
2034 DWORD WINAPI ALSA_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
2035 DWORD dwParam1, DWORD dwParam2)
2037 TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
2038 wDevID, wMsg, dwUser, dwParam1, dwParam2);
2045 /* FIXME: Pretend this is supported */
2047 case WODM_OPEN: return wodOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2048 case WODM_CLOSE: return wodClose (wDevID);
2049 case WODM_GETDEVCAPS: return wodGetDevCaps (wDevID, (LPWAVEOUTCAPSA)dwParam1, dwParam2);
2050 case WODM_GETNUMDEVS: return wodGetNumDevs ();
2051 case WODM_GETPITCH: return MMSYSERR_NOTSUPPORTED;
2052 case WODM_SETPITCH: return MMSYSERR_NOTSUPPORTED;
2053 case WODM_GETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
2054 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
2055 case WODM_WRITE: return wodWrite (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2056 case WODM_PAUSE: return wodPause (wDevID);
2057 case WODM_GETPOS: return wodGetPosition (wDevID, (LPMMTIME)dwParam1, dwParam2);
2058 case WODM_BREAKLOOP: return wodBreakLoop (wDevID);
2059 case WODM_PREPARE: return wodPrepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2060 case WODM_UNPREPARE: return wodUnprepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2061 case WODM_GETVOLUME: return wodGetVolume (wDevID, (LPDWORD)dwParam1);
2062 case WODM_SETVOLUME: return wodSetVolume (wDevID, dwParam1);
2063 case WODM_RESTART: return wodRestart (wDevID);
2064 case WODM_RESET: return wodReset (wDevID);
2065 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2066 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2067 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
2068 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
2069 case DRV_QUERYDSOUNDGUID: return wodDsGuid (wDevID, (LPGUID)dwParam1);
2072 FIXME("unknown message %d!\n", wMsg);
2074 return MMSYSERR_NOTSUPPORTED;
2077 /*======================================================================*
2078 * Low level DSOUND implementation *
2079 *======================================================================*/
2081 typedef struct IDsDriverImpl IDsDriverImpl;
2082 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
2084 struct IDsDriverImpl
2086 /* IUnknown fields */
2087 ICOM_VFIELD(IDsDriver);
2089 /* IDsDriverImpl fields */
2091 IDsDriverBufferImpl*primary;
2094 struct IDsDriverBufferImpl
2096 /* IUnknown fields */
2097 ICOM_VFIELD(IDsDriverBuffer);
2099 /* IDsDriverBufferImpl fields */
2102 CRITICAL_SECTION mmap_crst;
2104 DWORD mmap_buflen_bytes;
2105 snd_pcm_uframes_t mmap_buflen_frames;
2106 snd_pcm_channel_area_t * mmap_areas;
2107 snd_async_handler_t * mmap_async_handler;
2110 static void DSDB_CheckXRUN(IDsDriverBufferImpl* pdbi)
2112 WINE_WAVEOUT * wwo = &(WOutDev[pdbi->drv->wDevID]);
2113 snd_pcm_state_t state = snd_pcm_state(wwo->p_handle);
2115 if ( state == SND_PCM_STATE_XRUN )
2117 int err = snd_pcm_prepare(wwo->p_handle);
2118 TRACE("xrun occurred\n");
2120 ERR("recovery from xrun failed, prepare failed: %s\n", snd_strerror(err));
2122 else if ( state == SND_PCM_STATE_SUSPENDED )
2124 int err = snd_pcm_resume(wwo->p_handle);
2125 TRACE("recovery from suspension occurred\n");
2126 if (err < 0 && err != -EAGAIN){
2127 err = snd_pcm_prepare(wwo->p_handle);
2129 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
2134 static void DSDB_MMAPCopy(IDsDriverBufferImpl* pdbi)
2136 WINE_WAVEOUT * wwo = &(WOutDev[pdbi->drv->wDevID]);
2137 unsigned int channels;
2138 snd_pcm_format_t format;
2139 snd_pcm_uframes_t period_size;
2140 snd_pcm_sframes_t avail;
2144 if ( !pdbi->mmap_buffer || !wwo->hw_params || !wwo->p_handle)
2147 err = snd_pcm_hw_params_get_channels(wwo->hw_params, &channels);
2148 err = snd_pcm_hw_params_get_format(wwo->hw_params, &format);
2150 err = snd_pcm_hw_params_get_period_size(wwo->hw_params, &period_size, &dir);
2151 avail = snd_pcm_avail_update(wwo->p_handle);
2153 DSDB_CheckXRUN(pdbi);
2155 TRACE("avail=%d format=%s channels=%d\n", (int)avail, snd_pcm_format_name(format), channels );
2157 while (avail >= period_size)
2159 const snd_pcm_channel_area_t *areas;
2160 snd_pcm_uframes_t ofs;
2161 snd_pcm_uframes_t frames;
2164 frames = avail / period_size * period_size; /* round down to a multiple of period_size */
2166 EnterCriticalSection(&pdbi->mmap_crst);
2168 snd_pcm_mmap_begin(wwo->p_handle, &areas, &ofs, &frames);
2169 snd_pcm_areas_copy(areas, ofs, pdbi->mmap_areas, ofs, channels, frames, format);
2170 err = snd_pcm_mmap_commit(wwo->p_handle, ofs, frames);
2172 LeaveCriticalSection(&pdbi->mmap_crst);
2174 if ( err != (snd_pcm_sframes_t) frames)
2175 ERR("mmap partially failed.\n");
2177 avail = snd_pcm_avail_update(wwo->p_handle);
2181 static void DSDB_PCMCallback(snd_async_handler_t *ahandler)
2183 /* snd_pcm_t * handle = snd_async_handler_get_pcm(ahandler); */
2184 IDsDriverBufferImpl* pdbi = snd_async_handler_get_callback_private(ahandler);
2185 TRACE("callback called\n");
2186 DSDB_MMAPCopy(pdbi);
2189 static int DSDB_CreateMMAP(IDsDriverBufferImpl* pdbi)
2191 WINE_WAVEOUT * wwo = &(WOutDev[pdbi->drv->wDevID]);
2192 snd_pcm_format_t format;
2193 snd_pcm_uframes_t frames;
2194 unsigned int channels;
2195 unsigned int bits_per_sample;
2196 unsigned int bits_per_frame;
2197 snd_pcm_channel_area_t * a;
2201 err = snd_pcm_hw_params_get_format(wwo->hw_params, &format);
2202 err = snd_pcm_hw_params_get_buffer_size(wwo->hw_params, &frames);
2203 err = snd_pcm_hw_params_get_channels(wwo->hw_params, &channels);
2204 bits_per_sample = snd_pcm_format_physical_width(format);
2205 bits_per_frame = bits_per_sample * channels;
2209 ALSA_TraceParameters(wwo->hw_params, NULL, FALSE);
2211 TRACE("format=%s frames=%ld channels=%d bits_per_sample=%d bits_per_frame=%d\n",
2212 snd_pcm_format_name(format), frames, channels, bits_per_sample, bits_per_frame);
2214 pdbi->mmap_buflen_frames = frames;
2215 pdbi->mmap_buflen_bytes = snd_pcm_frames_to_bytes( wwo->p_handle, frames );
2216 pdbi->mmap_buffer = HeapAlloc(GetProcessHeap(),0,pdbi->mmap_buflen_bytes);
2217 if (!pdbi->mmap_buffer)
2218 return DSERR_OUTOFMEMORY;
2220 snd_pcm_format_set_silence(format, pdbi->mmap_buffer, frames );
2222 TRACE("created mmap buffer of %ld frames (%ld bytes) at %p\n",
2223 frames, pdbi->mmap_buflen_bytes, pdbi->mmap_buffer);
2225 pdbi->mmap_areas = HeapAlloc(GetProcessHeap(),0,channels*sizeof(snd_pcm_channel_area_t));
2226 if (!pdbi->mmap_areas)
2227 return DSERR_OUTOFMEMORY;
2229 a = pdbi->mmap_areas;
2230 for (c = 0; c < channels; c++, a++)
2232 a->addr = pdbi->mmap_buffer;
2233 a->first = bits_per_sample * c;
2234 a->step = bits_per_frame;
2235 TRACE("Area %d: addr=%p first=%d step=%d\n", c, a->addr, a->first, a->step);
2238 InitializeCriticalSection(&pdbi->mmap_crst);
2240 err = snd_async_add_pcm_handler(&pdbi->mmap_async_handler, wwo->p_handle, DSDB_PCMCallback, pdbi);
2243 ERR("add_pcm_handler failed. reason: %s\n", snd_strerror(err));
2244 return DSERR_GENERIC;
2250 static void DSDB_DestroyMMAP(IDsDriverBufferImpl* pdbi)
2252 TRACE("mmap buffer %p destroyed\n", pdbi->mmap_buffer);
2253 HeapFree(GetProcessHeap(), 0, pdbi->mmap_areas);
2254 HeapFree(GetProcessHeap(), 0, pdbi->mmap_buffer);
2255 pdbi->mmap_areas = NULL;
2256 pdbi->mmap_buffer = NULL;
2257 DeleteCriticalSection(&pdbi->mmap_crst);
2261 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
2263 /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2264 FIXME("(): stub!\n");
2265 return DSERR_UNSUPPORTED;
2268 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
2270 ICOM_THIS(IDsDriverBufferImpl,iface);
2271 TRACE("(%p)\n",iface);
2275 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
2277 ICOM_THIS(IDsDriverBufferImpl,iface);
2278 TRACE("(%p)\n",iface);
2281 if (This == This->drv->primary)
2282 This->drv->primary = NULL;
2283 DSDB_DestroyMMAP(This);
2284 HeapFree(GetProcessHeap(), 0, This);
2288 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
2289 LPVOID*ppvAudio1,LPDWORD pdwLen1,
2290 LPVOID*ppvAudio2,LPDWORD pdwLen2,
2291 DWORD dwWritePosition,DWORD dwWriteLen,
2294 /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2295 TRACE("(%p)\n",iface);
2296 return DSERR_UNSUPPORTED;
2299 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
2300 LPVOID pvAudio1,DWORD dwLen1,
2301 LPVOID pvAudio2,DWORD dwLen2)
2303 /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2304 TRACE("(%p)\n",iface);
2305 return DSERR_UNSUPPORTED;
2308 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
2309 LPWAVEFORMATEX pwfx)
2311 /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2312 TRACE("(%p,%p)\n",iface,pwfx);
2313 return DSERR_BUFFERLOST;
2316 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
2318 /* ICOM_THIS(IDsDriverBufferImpl,iface); */
2319 TRACE("(%p,%ld): stub\n",iface,dwFreq);
2320 return DSERR_UNSUPPORTED;
2323 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
2326 ICOM_THIS(IDsDriverBufferImpl,iface);
2327 TRACE("(%p,%p)\n",iface,pVolPan);
2328 vol = pVolPan->dwTotalLeftAmpFactor | (pVolPan->dwTotalRightAmpFactor << 16);
2330 if (wodSetVolume(This->drv->wDevID, vol) != MMSYSERR_NOERROR) {
2331 WARN("wodSetVolume failed\n");
2332 return DSERR_INVALIDPARAM;
2338 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
2340 /* ICOM_THIS(IDsDriverImpl,iface); */
2341 TRACE("(%p,%ld): stub\n",iface,dwNewPos);
2342 return DSERR_UNSUPPORTED;
2345 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
2346 LPDWORD lpdwPlay, LPDWORD lpdwWrite)
2348 ICOM_THIS(IDsDriverBufferImpl,iface);
2349 WINE_WAVEOUT * wwo = &(WOutDev[This->drv->wDevID]);
2350 snd_pcm_uframes_t hw_ptr;
2351 snd_pcm_uframes_t period_size;
2355 if (wwo->hw_params == NULL) return DSERR_GENERIC;
2358 err = snd_pcm_hw_params_get_period_size(wwo->hw_params, &period_size, &dir);
2360 if (wwo->p_handle == NULL) return DSERR_GENERIC;
2361 /** we need to track down buffer underruns */
2362 DSDB_CheckXRUN(This);
2364 EnterCriticalSection(&This->mmap_crst);
2365 /* FIXME: snd_pcm_mmap_hw_ptr() should not be accessed by a user app. */
2366 /* It will NOT return what why want anyway. */
2367 hw_ptr = _snd_pcm_mmap_hw_ptr(wwo->p_handle);
2369 *lpdwPlay = snd_pcm_frames_to_bytes(wwo->p_handle, hw_ptr/ period_size * period_size) % This->mmap_buflen_bytes;
2371 *lpdwWrite = snd_pcm_frames_to_bytes(wwo->p_handle, (hw_ptr / period_size + 1) * period_size ) % This->mmap_buflen_bytes;
2372 LeaveCriticalSection(&This->mmap_crst);
2374 TRACE("hw_ptr=0x%08x, playpos=%ld, writepos=%ld\n", (unsigned int)hw_ptr, lpdwPlay?*lpdwPlay:-1, lpdwWrite?*lpdwWrite:-1);
2378 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
2380 ICOM_THIS(IDsDriverBufferImpl,iface);
2381 WINE_WAVEOUT * wwo = &(WOutDev[This->drv->wDevID]);
2382 snd_pcm_state_t state;
2385 TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
2387 if (wwo->p_handle == NULL) return DSERR_GENERIC;
2389 state = snd_pcm_state(wwo->p_handle);
2390 if ( state == SND_PCM_STATE_SETUP )
2392 err = snd_pcm_prepare(wwo->p_handle);
2393 state = snd_pcm_state(wwo->p_handle);
2395 if ( state == SND_PCM_STATE_PREPARED )
2397 DSDB_MMAPCopy(This);
2398 err = snd_pcm_start(wwo->p_handle);
2403 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
2405 ICOM_THIS(IDsDriverBufferImpl,iface);
2406 WINE_WAVEOUT * wwo = &(WOutDev[This->drv->wDevID]);
2411 TRACE("(%p)\n",iface);
2413 if (wwo->p_handle == NULL) return DSERR_GENERIC;
2415 /* ring buffer wrap up detection */
2416 IDsDriverBufferImpl_GetPosition(iface, &play, &write);
2419 TRACE("writepos wrapper up\n");
2423 if ( ( err = snd_pcm_drop(wwo->p_handle)) < 0 )
2425 ERR("error while stopping pcm: %s\n", snd_strerror(err));
2426 return DSERR_GENERIC;
2431 static ICOM_VTABLE(IDsDriverBuffer) dsdbvt =
2433 ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
2434 IDsDriverBufferImpl_QueryInterface,
2435 IDsDriverBufferImpl_AddRef,
2436 IDsDriverBufferImpl_Release,
2437 IDsDriverBufferImpl_Lock,
2438 IDsDriverBufferImpl_Unlock,
2439 IDsDriverBufferImpl_SetFormat,
2440 IDsDriverBufferImpl_SetFrequency,
2441 IDsDriverBufferImpl_SetVolumePan,
2442 IDsDriverBufferImpl_SetPosition,
2443 IDsDriverBufferImpl_GetPosition,
2444 IDsDriverBufferImpl_Play,
2445 IDsDriverBufferImpl_Stop
2448 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
2450 /* ICOM_THIS(IDsDriverImpl,iface); */
2451 FIXME("(%p): stub!\n",iface);
2452 return DSERR_UNSUPPORTED;
2455 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
2457 ICOM_THIS(IDsDriverImpl,iface);
2458 TRACE("(%p)\n",iface);
2463 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
2465 ICOM_THIS(IDsDriverImpl,iface);
2466 TRACE("(%p)\n",iface);
2469 HeapFree(GetProcessHeap(),0,This);
2473 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
2475 ICOM_THIS(IDsDriverImpl,iface);
2476 TRACE("(%p,%p)\n",iface,pDesc);
2477 memcpy(pDesc, &(WOutDev[This->wDevID].ds_desc), sizeof(DSDRIVERDESC));
2478 pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
2479 DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK;
2480 pDesc->dnDevNode = WOutDev[This->wDevID].waveDesc.dnDevNode;
2482 pDesc->wReserved = 0;
2483 pDesc->ulDeviceNum = This->wDevID;
2484 pDesc->dwHeapType = DSDHEAP_NOHEAP;
2485 pDesc->pvDirectDrawHeap = NULL;
2486 pDesc->dwMemStartAddress = 0;
2487 pDesc->dwMemEndAddress = 0;
2488 pDesc->dwMemAllocExtra = 0;
2489 pDesc->pvReserved1 = NULL;
2490 pDesc->pvReserved2 = NULL;
2494 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
2496 /* ICOM_THIS(IDsDriverImpl,iface); */
2497 TRACE("(%p)\n",iface);
2501 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
2503 /* ICOM_THIS(IDsDriverImpl,iface); */
2504 TRACE("(%p)\n",iface);
2508 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
2510 ICOM_THIS(IDsDriverImpl,iface);
2511 TRACE("(%p,%p)\n",iface,pCaps);
2512 memset(pCaps, 0, sizeof(*pCaps));
2514 pCaps->dwFlags = DSCAPS_PRIMARYMONO;
2515 if ( WOutDev[This->wDevID].caps.wChannels == 2 )
2516 pCaps->dwFlags |= DSCAPS_PRIMARYSTEREO;
2518 if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 ) )
2519 pCaps->dwFlags |= DSCAPS_PRIMARY8BIT;
2521 if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S16 | WAVE_FORMAT_2S16 | WAVE_FORMAT_4S16))
2522 pCaps->dwFlags |= DSCAPS_PRIMARY16BIT;
2524 pCaps->dwPrimaryBuffers = 1;
2525 TRACE("caps=0x%X\n",(unsigned int)pCaps->dwFlags);
2526 pCaps->dwMinSecondarySampleRate = DSBFREQUENCY_MIN;
2527 pCaps->dwMaxSecondarySampleRate = DSBFREQUENCY_MAX;
2529 /* the other fields only apply to secondary buffers, which we don't support
2530 * (unless we want to mess with wavetable synthesizers and MIDI) */
2534 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
2535 LPWAVEFORMATEX pwfx,
2536 DWORD dwFlags, DWORD dwCardAddress,
2537 LPDWORD pdwcbBufferSize,
2541 ICOM_THIS(IDsDriverImpl,iface);
2542 IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
2545 TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
2546 /* we only support primary buffers */
2547 if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
2548 return DSERR_UNSUPPORTED;
2550 return DSERR_ALLOCATED;
2551 if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
2552 return DSERR_CONTROLUNAVAIL;
2554 *ippdsdb = (IDsDriverBufferImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
2555 if (*ippdsdb == NULL)
2556 return DSERR_OUTOFMEMORY;
2557 (*ippdsdb)->lpVtbl = &dsdbvt;
2558 (*ippdsdb)->ref = 1;
2559 (*ippdsdb)->drv = This;
2561 err = DSDB_CreateMMAP((*ippdsdb));
2564 HeapFree(GetProcessHeap(), 0, *ippdsdb);
2568 *ppbBuffer = (*ippdsdb)->mmap_buffer;
2569 *pdwcbBufferSize = (*ippdsdb)->mmap_buflen_bytes;
2571 This->primary = *ippdsdb;
2573 /* buffer is ready to go */
2574 TRACE("buffer created at %p\n", *ippdsdb);
2578 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
2579 PIDSDRIVERBUFFER pBuffer,
2582 /* ICOM_THIS(IDsDriverImpl,iface); */
2583 TRACE("(%p,%p): stub\n",iface,pBuffer);
2584 return DSERR_INVALIDCALL;
2587 static ICOM_VTABLE(IDsDriver) dsdvt =
2589 ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
2590 IDsDriverImpl_QueryInterface,
2591 IDsDriverImpl_AddRef,
2592 IDsDriverImpl_Release,
2593 IDsDriverImpl_GetDriverDesc,
2595 IDsDriverImpl_Close,
2596 IDsDriverImpl_GetCaps,
2597 IDsDriverImpl_CreateSoundBuffer,
2598 IDsDriverImpl_DuplicateSoundBuffer
2601 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
2603 IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
2605 TRACE("driver created\n");
2607 /* the HAL isn't much better than the HEL if we can't do mmap() */
2608 if (!(WOutDev[wDevID].caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
2609 ERR("DirectSound flag not set\n");
2610 MESSAGE("This sound card's driver does not support direct access\n");
2611 MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
2612 return MMSYSERR_NOTSUPPORTED;
2615 *idrv = (IDsDriverImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
2617 return MMSYSERR_NOMEM;
2618 (*idrv)->lpVtbl = &dsdvt;
2621 (*idrv)->wDevID = wDevID;
2622 (*idrv)->primary = NULL;
2623 return MMSYSERR_NOERROR;
2626 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2628 memcpy(desc, &(WOutDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
2629 return MMSYSERR_NOERROR;
2632 static DWORD wodDsGuid(UINT wDevID, LPGUID pGuid)
2634 TRACE("(%d,%p)\n",wDevID,pGuid);
2636 memcpy(pGuid, &(WOutDev[wDevID].ds_guid), sizeof(GUID));
2638 return MMSYSERR_NOERROR;
2641 /*======================================================================*
2642 * Low level WAVE IN implementation *
2643 *======================================================================*/
2645 /**************************************************************************
2646 * widNotifyClient [internal]
2648 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
2650 TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
2656 if (wwi->wFlags != DCB_NULL &&
2657 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags, (HDRVR)wwi->waveDesc.hWave,
2658 wMsg, wwi->waveDesc.dwInstance, dwParam1, dwParam2)) {
2659 WARN("can't notify client !\n");
2660 return MMSYSERR_ERROR;
2664 FIXME("Unknown callback message %u\n", wMsg);
2665 return MMSYSERR_INVALPARAM;
2667 return MMSYSERR_NOERROR;
2670 /**************************************************************************
2671 * widGetDevCaps [internal]
2673 static DWORD widGetDevCaps(WORD wDevID, LPWAVEOUTCAPSA lpCaps, DWORD dwSize)
2675 TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
2677 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
2679 if (wDevID >= MAX_WAVEINDRV) {
2680 TRACE("MAX_WAVOUTDRV reached !\n");
2681 return MMSYSERR_BADDEVICEID;
2684 memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
2685 return MMSYSERR_NOERROR;
2688 /**************************************************************************
2689 * widRecorder_ReadHeaders [internal]
2691 static void widRecorder_ReadHeaders(WINE_WAVEIN * wwi)
2693 enum win_wm_message tmp_msg;
2698 while (ALSA_RetrieveRingMessage(&wwi->msgRing, &tmp_msg, &tmp_param, &tmp_ev)) {
2699 if (tmp_msg == WINE_WM_HEADER) {
2701 lpWaveHdr = (LPWAVEHDR)tmp_param;
2702 lpWaveHdr->lpNext = 0;
2704 if (wwi->lpQueuePtr == 0)
2705 wwi->lpQueuePtr = lpWaveHdr;
2707 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2711 ERR("should only have headers left\n");
2716 /**************************************************************************
2717 * widRecorder [internal]
2719 static DWORD CALLBACK widRecorder(LPVOID pmt)
2721 WORD uDevID = (DWORD)pmt;
2722 WINE_WAVEIN* wwi = (WINE_WAVEIN*)&WInDev[uDevID];
2726 LPVOID buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, wwi->dwPeriodSize);
2727 char *pOffset = buffer;
2728 enum win_wm_message msg;
2731 DWORD frames_per_period;
2733 wwi->state = WINE_WS_STOPPED;
2734 wwi->dwTotalRecorded = 0;
2735 wwi->lpQueuePtr = NULL;
2737 SetEvent(wwi->hStartUpEvent);
2739 /* make sleep time to be # of ms to output a period */
2740 dwSleepTime = (1024/*wwi-dwPeriodSize => overrun!*/ * 1000) / wwi->format.wf.nAvgBytesPerSec;
2741 frames_per_period = snd_pcm_bytes_to_frames(wwi->p_handle, wwi->dwPeriodSize);
2742 TRACE("sleeptime=%ld ms\n", dwSleepTime);
2745 /* wait for dwSleepTime or an event in thread's queue */
2746 /* FIXME: could improve wait time depending on queue state,
2747 * ie, number of queued fragments
2749 if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
2756 lpWaveHdr = wwi->lpQueuePtr;
2757 /* read all the fragments accumulated so far */
2758 frames = snd_pcm_avail_update(wwi->p_handle);
2759 bytes = snd_pcm_frames_to_bytes(wwi->p_handle, frames);
2760 TRACE("frames = %ld bytes = %ld\n", frames, bytes);
2761 periods = bytes / wwi->dwPeriodSize;
2762 while ((periods > 0) && (wwi->lpQueuePtr))
2765 bytes = wwi->dwPeriodSize;
2766 TRACE("bytes = %ld\n",bytes);
2767 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwPeriodSize)
2769 /* directly read fragment in wavehdr */
2770 read = wwi->read(wwi->p_handle, lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded, frames_per_period);
2771 bytesRead = snd_pcm_frames_to_bytes(wwi->p_handle, read);
2773 TRACE("bytesRead=%ld (direct)\n", bytesRead);
2774 if (bytesRead != (DWORD) -1)
2776 /* update number of bytes recorded in current buffer and by this device */
2777 lpWaveHdr->dwBytesRecorded += bytesRead;
2778 wwi->dwTotalRecorded += bytesRead;
2780 /* buffer is full. notify client */
2781 if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2783 /* must copy the value of next waveHdr, because we have no idea of what
2784 * will be done with the content of lpWaveHdr in callback
2786 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
2788 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2789 lpWaveHdr->dwFlags |= WHDR_DONE;
2791 wwi->lpQueuePtr = lpNext;
2792 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2799 /* read the fragment in a local buffer */
2800 read = wwi->read(wwi->p_handle, buffer, frames_per_period);
2801 bytesRead = snd_pcm_frames_to_bytes(wwi->p_handle, read);
2804 TRACE("bytesRead=%ld (local)\n", bytesRead);
2806 /* copy data in client buffers */
2807 while (bytesRead != (DWORD) -1 && bytesRead > 0)
2809 DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
2811 memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2815 /* update number of bytes recorded in current buffer and by this device */
2816 lpWaveHdr->dwBytesRecorded += dwToCopy;
2817 wwi->dwTotalRecorded += dwToCopy;
2818 bytesRead -= dwToCopy;
2819 pOffset += dwToCopy;
2821 /* client buffer is full. notify client */
2822 if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2824 /* must copy the value of next waveHdr, because we have no idea of what
2825 * will be done with the content of lpWaveHdr in callback
2827 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
2828 TRACE("lpNext=%p\n", lpNext);
2830 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2831 lpWaveHdr->dwFlags |= WHDR_DONE;
2833 wwi->lpQueuePtr = lpNext;
2834 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2837 if (!lpNext && bytesRead) {
2838 /* before we give up, check for more header messages */
2839 while (ALSA_PeekRingMessage(&wwi->msgRing, &msg, ¶m, &ev))
2841 if (msg == WINE_WM_HEADER) {
2843 ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, ¶m, &ev);
2844 hdr = ((LPWAVEHDR)param);
2845 TRACE("msg = %s, hdr = %p, ev = %p\n", wodPlayerCmdString[msg - WM_USER - 1], hdr, ev);
2847 if (lpWaveHdr == 0) {
2848 /* new head of queue */
2849 wwi->lpQueuePtr = lpWaveHdr = hdr;
2851 /* insert buffer at the end of queue */
2853 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2860 if (lpWaveHdr == 0) {
2861 /* no more buffer to copy data to, but we did read more.
2862 * what hasn't been copied will be dropped
2864 WARN("buffer under run! %lu bytes dropped.\n", bytesRead);
2865 wwi->lpQueuePtr = NULL;
2875 WAIT_OMR(&wwi->msgRing, dwSleepTime);
2877 while (ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, ¶m, &ev))
2879 TRACE("msg=%s param=0x%lx\n", wodPlayerCmdString[msg - WM_USER - 1], param);
2881 case WINE_WM_PAUSING:
2882 wwi->state = WINE_WS_PAUSED;
2883 /*FIXME("Device should stop recording\n");*/
2886 case WINE_WM_STARTING:
2887 wwi->state = WINE_WS_PLAYING;
2888 snd_pcm_start(wwi->p_handle);
2891 case WINE_WM_HEADER:
2892 lpWaveHdr = (LPWAVEHDR)param;
2893 lpWaveHdr->lpNext = 0;
2895 /* insert buffer at the end of queue */
2898 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2902 case WINE_WM_STOPPING:
2903 if (wwi->state != WINE_WS_STOPPED)
2905 snd_pcm_drain(wwi->p_handle);
2907 /* read any headers in queue */
2908 widRecorder_ReadHeaders(wwi);
2910 /* return current buffer to app */
2911 lpWaveHdr = wwi->lpQueuePtr;
2914 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
2915 TRACE("stop %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
2916 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2917 lpWaveHdr->dwFlags |= WHDR_DONE;
2918 wwi->lpQueuePtr = lpNext;
2919 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2922 wwi->state = WINE_WS_STOPPED;
2925 case WINE_WM_RESETTING:
2926 if (wwi->state != WINE_WS_STOPPED)
2928 snd_pcm_drain(wwi->p_handle);
2930 wwi->state = WINE_WS_STOPPED;
2931 wwi->dwTotalRecorded = 0;
2933 /* read any headers in queue */
2934 widRecorder_ReadHeaders(wwi);
2936 /* return all buffers to the app */
2937 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
2938 TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
2939 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2940 lpWaveHdr->dwFlags |= WHDR_DONE;
2941 wwi->lpQueuePtr = lpWaveHdr->lpNext;
2942 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2945 wwi->lpQueuePtr = NULL;
2948 case WINE_WM_CLOSING:
2950 wwi->state = WINE_WS_CLOSED;
2952 HeapFree(GetProcessHeap(), 0, buffer);
2954 /* shouldn't go here */
2955 case WINE_WM_UPDATE:
2960 FIXME("unknown message %d\n", msg);
2966 /* just for not generating compilation warnings... should never be executed */
2970 /**************************************************************************
2971 * widOpen [internal]
2973 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
2976 snd_pcm_hw_params_t * hw_params;
2977 snd_pcm_sw_params_t * sw_params;
2978 snd_pcm_access_t access;
2979 snd_pcm_format_t format;
2981 unsigned int buffer_time = 500000;
2982 unsigned int period_time = 10000;
2983 snd_pcm_uframes_t buffer_size;
2984 snd_pcm_uframes_t period_size;
2990 snd_pcm_hw_params_alloca(&hw_params);
2991 snd_pcm_sw_params_alloca(&sw_params);
2993 TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
2994 if (lpDesc == NULL) {
2995 WARN("Invalid Parameter !\n");
2996 return MMSYSERR_INVALPARAM;
2998 if (wDevID >= MAX_WAVEOUTDRV) {
2999 TRACE("MAX_WAVOUTDRV reached !\n");
3000 return MMSYSERR_BADDEVICEID;
3003 /* only PCM format is supported so far... */
3004 if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
3005 lpDesc->lpFormat->nChannels == 0 ||
3006 lpDesc->lpFormat->nSamplesPerSec < DSBFREQUENCY_MIN ||
3007 lpDesc->lpFormat->nSamplesPerSec > DSBFREQUENCY_MAX ||
3008 (lpDesc->lpFormat->wBitsPerSample!=8 && lpDesc->lpFormat->wBitsPerSample!=16)) {
3009 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
3010 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
3011 lpDesc->lpFormat->nSamplesPerSec);
3012 return WAVERR_BADFORMAT;
3015 if (dwFlags & WAVE_FORMAT_QUERY) {
3016 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
3017 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
3018 lpDesc->lpFormat->nSamplesPerSec);
3019 return MMSYSERR_NOERROR;
3022 wwi = &WInDev[wDevID];
3024 if ((dwFlags & WAVE_DIRECTSOUND) && !(wwi->caps.dwSupport & WAVECAPS_DIRECTSOUND))
3025 /* not supported, ignore it */
3026 dwFlags &= ~WAVE_DIRECTSOUND;
3029 flags = SND_PCM_NONBLOCK;
3030 if ( dwFlags & WAVE_DIRECTSOUND )
3031 flags |= SND_PCM_ASYNC;
3033 if ( (err=snd_pcm_open(&pcm, wwi->device, SND_PCM_STREAM_CAPTURE, dwFlags)) < 0 )
3035 ERR("Error open: %s\n", snd_strerror(err));
3036 return MMSYSERR_NOTENABLED;
3039 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
3041 memcpy(&wwi->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
3042 memcpy(&wwi->format, lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
3044 if (wwi->format.wBitsPerSample == 0) {
3045 WARN("Resetting zeroed wBitsPerSample\n");
3046 wwi->format.wBitsPerSample = 8 *
3047 (wwi->format.wf.nAvgBytesPerSec /
3048 wwi->format.wf.nSamplesPerSec) /
3049 wwi->format.wf.nChannels;
3052 snd_pcm_hw_params_any(pcm, hw_params);
3054 #define EXIT_ON_ERROR(f,e,txt) do \
3057 if ( (err = (f) ) < 0) \
3059 ERR(txt ": %s\n", snd_strerror(err)); \
3060 snd_pcm_close(pcm); \
3065 access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
3066 if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
3067 WARN("mmap not available. switching to standard write.\n");
3068 access = SND_PCM_ACCESS_RW_INTERLEAVED;
3069 EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
3070 wwi->read = snd_pcm_readi;
3073 wwi->read = snd_pcm_mmap_readi;
3075 EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwi->format.wf.nChannels), MMSYSERR_INVALPARAM, "unable to set required channels");
3077 format = (wwi->format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE : SND_PCM_FORMAT_U8;
3078 EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), MMSYSERR_INVALPARAM, "unable to set required format");
3080 rate = wwi->format.wf.nSamplesPerSec;
3082 err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
3084 ERR("Rate %ld Hz not available for playback: %s\n", wwi->format.wf.nSamplesPerSec, snd_strerror(rate));
3086 return WAVERR_BADFORMAT;
3088 if (rate != wwi->format.wf.nSamplesPerSec) {
3089 ERR("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwi->format.wf.nSamplesPerSec, rate);
3091 return WAVERR_BADFORMAT;
3095 EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
3097 EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
3099 EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
3102 err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
3103 err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
3105 snd_pcm_sw_params_current(pcm, sw_params);
3106 EXIT_ON_ERROR( snd_pcm_sw_params_set_start_threshold(pcm, sw_params, dwFlags & WAVE_DIRECTSOUND ? INT_MAX : 1 ), MMSYSERR_ERROR, "unable to set start threshold");
3107 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
3108 EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
3109 EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
3110 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
3111 EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
3112 #undef EXIT_ON_ERROR
3114 snd_pcm_prepare(pcm);
3117 ALSA_TraceParameters(hw_params, sw_params, FALSE);
3119 /* now, we can save all required data for later use... */
3120 if ( wwi->hw_params )
3121 snd_pcm_hw_params_free(wwi->hw_params);
3122 snd_pcm_hw_params_malloc(&(wwi->hw_params));
3123 snd_pcm_hw_params_copy(wwi->hw_params, hw_params);
3125 wwi->dwBufferSize = buffer_size;
3126 wwi->lpQueuePtr = wwi->lpPlayPtr = wwi->lpLoopPtr = NULL;
3127 wwi->p_handle = pcm;
3129 ALSA_InitRingMessage(&wwi->msgRing);
3131 wwi->count = snd_pcm_poll_descriptors_count (wwi->p_handle);
3132 if (wwi->count <= 0) {
3133 ERR("Invalid poll descriptors count\n");
3134 return MMSYSERR_ERROR;
3137 wwi->ufds = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct pollfd) * wwi->count);
3138 if (wwi->ufds == NULL) {
3139 ERR("No enough memory\n");
3140 return MMSYSERR_NOMEM;
3142 if ((err = snd_pcm_poll_descriptors(wwi->p_handle, wwi->ufds, wwi->count)) < 0) {
3143 ERR("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
3144 return MMSYSERR_ERROR;
3147 wwi->dwPeriodSize = period_size;
3148 /*if (wwi->dwFragmentSize % wwi->format.wf.nBlockAlign)
3149 ERR("Fragment doesn't contain an integral number of data blocks\n");
3151 TRACE("dwPeriodSize=%lu\n", wwi->dwPeriodSize);
3152 TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
3153 wwi->format.wBitsPerSample, wwi->format.wf.nAvgBytesPerSec,
3154 wwi->format.wf.nSamplesPerSec, wwi->format.wf.nChannels,
3155 wwi->format.wf.nBlockAlign);
3157 if (!(dwFlags & WAVE_DIRECTSOUND)) {
3158 wwi->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
3159 wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
3160 WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
3161 CloseHandle(wwi->hStartUpEvent);
3163 wwi->hThread = INVALID_HANDLE_VALUE;
3164 wwi->dwThreadID = 0;
3166 wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
3168 return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
3172 /**************************************************************************
3173 * widClose [internal]
3175 static DWORD widClose(WORD wDevID)
3177 DWORD ret = MMSYSERR_NOERROR;
3180 TRACE("(%u);\n", wDevID);
3182 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3183 WARN("bad device ID !\n");
3184 return MMSYSERR_BADDEVICEID;
3187 wwi = &WInDev[wDevID];
3188 if (wwi->lpQueuePtr) {
3189 WARN("buffers still playing !\n");
3190 ret = WAVERR_STILLPLAYING;
3192 if (wwi->hThread != INVALID_HANDLE_VALUE) {
3193 ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
3195 ALSA_DestroyRingMessage(&wwi->msgRing);
3197 snd_pcm_hw_params_free(wwi->hw_params);
3198 wwi->hw_params = NULL;
3200 snd_pcm_close(wwi->p_handle);
3201 wwi->p_handle = NULL;
3203 ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
3206 HeapFree(GetProcessHeap(), 0, wwi->ufds);
3210 /**************************************************************************
3211 * widAddBuffer [internal]
3214 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3216 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3218 /* first, do the sanity checks... */
3219 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3220 WARN("bad dev ID !\n");
3221 return MMSYSERR_BADDEVICEID;
3224 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
3225 return WAVERR_UNPREPARED;
3227 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3228 return WAVERR_STILLPLAYING;
3230 lpWaveHdr->dwFlags &= ~WHDR_DONE;
3231 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
3232 lpWaveHdr->lpNext = 0;
3234 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
3236 return MMSYSERR_NOERROR;
3239 /**************************************************************************
3240 * widPrepare [internal]
3242 static DWORD widPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3244 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3246 if (wDevID >= MAX_WAVEINDRV) {
3247 WARN("bad device ID !\n");
3248 return MMSYSERR_BADDEVICEID;
3251 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3252 return WAVERR_STILLPLAYING;
3254 lpWaveHdr->dwFlags |= WHDR_PREPARED;
3255 lpWaveHdr->dwFlags &= ~WHDR_DONE;
3256 return MMSYSERR_NOERROR;
3259 /**************************************************************************
3260 * widUnprepare [internal]
3262 static DWORD widUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3264 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3266 if (wDevID >= MAX_WAVEINDRV) {
3267 WARN("bad device ID !\n");
3268 return MMSYSERR_BADDEVICEID;
3271 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3272 return WAVERR_STILLPLAYING;
3274 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
3275 lpWaveHdr->dwFlags |= WHDR_DONE;
3277 return MMSYSERR_NOERROR;
3280 /**************************************************************************
3281 * widStart [internal]
3284 static DWORD widStart(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3286 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3288 /* first, do the sanity checks... */
3289 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3290 WARN("bad dev ID !\n");
3291 return MMSYSERR_BADDEVICEID;
3294 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
3298 return MMSYSERR_NOERROR;
3301 /**************************************************************************
3302 * widStop [internal]
3305 static DWORD widStop(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3307 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3309 /* first, do the sanity checks... */
3310 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3311 WARN("bad dev ID !\n");
3312 return MMSYSERR_BADDEVICEID;
3315 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
3317 return MMSYSERR_NOERROR;
3320 /**************************************************************************
3321 * widReset [internal]
3323 static DWORD widReset(WORD wDevID)
3325 TRACE("(%u);\n", wDevID);
3326 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
3327 WARN("can't reset !\n");
3328 return MMSYSERR_INVALHANDLE;
3330 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
3331 return MMSYSERR_NOERROR;
3334 /**************************************************************************
3335 * widGetPosition [internal]
3337 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
3342 FIXME("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
3344 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
3345 WARN("can't get pos !\n");
3346 return MMSYSERR_INVALHANDLE;
3348 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
3350 wwi = &WInDev[wDevID];
3351 ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_UPDATE, 0, TRUE);
3353 TRACE("wType=%04X !\n", lpTime->wType);
3354 TRACE("wBitsPerSample=%u\n", wwi->format.wBitsPerSample);
3355 TRACE("nSamplesPerSec=%lu\n", wwi->format.wf.nSamplesPerSec);
3356 TRACE("nChannels=%u\n", wwi->format.wf.nChannels);
3357 TRACE("nAvgBytesPerSec=%lu\n", wwi->format.wf.nAvgBytesPerSec);
3358 FIXME("dwTotalRecorded=%lu\n",wwi->dwTotalRecorded);
3359 switch (lpTime->wType) {
3361 lpTime->u.cb = wwi->dwTotalRecorded;
3362 TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
3365 lpTime->u.sample = wwi->dwTotalRecorded * 8 /
3366 wwi->format.wBitsPerSample / wwi->format.wf.nChannels;
3367 TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
3370 time = (double)wwi->dwTotalRecorded /
3371 (double)wwi->format.wf.nAvgBytesPerSec;
3372 lpTime->u.smpte.hour = time / (60 * 60);
3373 time -= lpTime->u.smpte.hour * (60 * 60);
3374 lpTime->u.smpte.min = time / 60;
3375 time -= lpTime->u.smpte.min * 60;
3376 lpTime->u.smpte.sec = time;
3377 time -= lpTime->u.smpte.sec;
3378 lpTime->u.smpte.frame = ceil(time * 30);
3379 lpTime->u.smpte.fps = 30;
3380 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
3381 lpTime->u.smpte.hour, lpTime->u.smpte.min,
3382 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
3385 FIXME("format not supported (%u) ! use TIME_MS !\n", lpTime->wType);
3386 lpTime->wType = TIME_MS;
3388 lpTime->u.ms = wwi->dwTotalRecorded * 1000.0 /
3389 wwi->format.wf.nAvgBytesPerSec;
3390 TRACE("TIME_MS=%lu\n", lpTime->u.ms);
3393 return MMSYSERR_NOERROR;
3396 /**************************************************************************
3397 * widGetNumDevs [internal]
3399 static DWORD widGetNumDevs(void)
3401 return ALSA_WidNumDevs;
3404 /**************************************************************************
3405 * widDevInterfaceSize [internal]
3407 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
3409 TRACE("(%u, %p)\n", wDevID, dwParam1);
3411 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3412 NULL, 0 ) * sizeof(WCHAR);
3413 return MMSYSERR_NOERROR;
3416 /**************************************************************************
3417 * widDevInterface [internal]
3419 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
3421 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3422 NULL, 0 ) * sizeof(WCHAR))
3424 MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3425 dwParam1, dwParam2 / sizeof(WCHAR));
3426 return MMSYSERR_NOERROR;
3428 return MMSYSERR_INVALPARAM;
3431 /**************************************************************************
3432 * widMessage (WINEALSA.@)
3434 DWORD WINAPI ALSA_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
3435 DWORD dwParam1, DWORD dwParam2)
3437 TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
3438 wDevID, wMsg, dwUser, dwParam1, dwParam2);
3445 /* FIXME: Pretend this is supported */
3447 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
3448 case WIDM_CLOSE: return widClose (wDevID);
3449 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3450 case WIDM_PREPARE: return widPrepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3451 case WIDM_UNPREPARE: return widUnprepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3452 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEOUTCAPSA)dwParam1, dwParam2);
3453 case WIDM_GETNUMDEVS: return widGetNumDevs ();
3454 case WIDM_GETPOS: return widGetPosition (wDevID, (LPMMTIME)dwParam1, dwParam2);
3455 case WIDM_RESET: return widReset (wDevID);
3456 case WIDM_START: return widStart (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3457 case WIDM_STOP: return widStop (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3458 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
3459 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
3460 /*case DRV_QUERYDSOUNDIFACE: return widDsCreate (wDevID, (PIDSCDRIVER*)dwParam1);
3461 case DRV_QUERYDSOUNDDESC: return widDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
3462 case DRV_QUERYDSOUNDGUID: return widDsGuid (wDevID, (LPGUID)dwParam1);*/
3464 FIXME("unknown message %d!\n", wMsg);
3466 return MMSYSERR_NOTSUPPORTED;
3471 #if !(defined(HAVE_ALSA) && ((SND_LIB_MAJOR == 0 && SND_LIB_MINOR >= 9) || SND_LIB_MAJOR >= 1))
3473 /**************************************************************************
3474 * widMessage (WINEALSA.@)
3476 DWORD WINAPI ALSA_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3477 DWORD dwParam1, DWORD dwParam2)
3479 FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3480 return MMSYSERR_NOTENABLED;
3487 /**************************************************************************
3488 * wodMessage (WINEALSA.@)
3490 DWORD WINAPI ALSA_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3491 DWORD dwParam1, DWORD dwParam2)
3493 FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3494 return MMSYSERR_NOTENABLED;
3497 #endif /* HAVE_ALSA */