Removed some more uses of the non-standard ICOM_THIS macro.
[wine/multimedia.git] / dlls / winmm / winealsa / audio.c
blobecbd5741c30cc34ddb0672f8c01a7d8670ebdeca
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
2 /*
3 * Sample Wine Driver for Advanced Linux Sound System (ALSA)
4 * Based on version <final> of the ALSA API
6 * Copyright 2002 Eric Pouech
7 * 2002 Marco Pietrobono
8 * 2003 Christian Costa : WaveIn support
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 /* unless someone makes a wineserver kernel module, Unix pipes are faster than win32 events */
26 #define USE_PIPE_SYNC
28 #include "config.h"
29 #include "wine/port.h"
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <string.h>
35 #ifdef HAVE_UNISTD_H
36 # include <unistd.h>
37 #endif
38 #include <errno.h>
39 #include <limits.h>
40 #include <fcntl.h>
41 #ifdef HAVE_SYS_IOCTL_H
42 # include <sys/ioctl.h>
43 #endif
44 #ifdef HAVE_SYS_MMAN_H
45 # include <sys/mman.h>
46 #endif
47 #include "windef.h"
48 #include "winbase.h"
49 #include "wingdi.h"
50 #include "winerror.h"
51 #include "winuser.h"
52 #include "winnls.h"
53 #include "winreg.h"
54 #include "mmddk.h"
55 #include "mmreg.h"
56 #include "dsound.h"
57 #include "dsdriver.h"
58 #include "ks.h"
59 #include "ksguid.h"
60 #include "ksmedia.h"
61 #define ALSA_PCM_NEW_HW_PARAMS_API
62 #define ALSA_PCM_NEW_SW_PARAMS_API
63 #include "alsa.h"
64 #include "wine/library.h"
65 #include "wine/debug.h"
67 WINE_DEFAULT_DEBUG_CHANNEL(wave);
70 #if defined(HAVE_ALSA) && ((SND_LIB_MAJOR == 0 && SND_LIB_MINOR >= 9) || SND_LIB_MAJOR >= 1)
72 /* internal ALSALIB functions */
73 snd_pcm_uframes_t _snd_pcm_mmap_hw_ptr(snd_pcm_t *pcm);
76 #define MAX_WAVEOUTDRV (1)
77 #define MAX_WAVEINDRV (1)
79 /* state diagram for waveOut writing:
81 * +---------+-------------+---------------+---------------------------------+
82 * | state | function | event | new state |
83 * +---------+-------------+---------------+---------------------------------+
84 * | | open() | | STOPPED |
85 * | PAUSED | write() | | PAUSED |
86 * | STOPPED | write() | <thrd create> | PLAYING |
87 * | PLAYING | write() | HEADER | PLAYING |
88 * | (other) | write() | <error> | |
89 * | (any) | pause() | PAUSING | PAUSED |
90 * | PAUSED | restart() | RESTARTING | PLAYING (if no thrd => STOPPED) |
91 * | (any) | reset() | RESETTING | STOPPED |
92 * | (any) | close() | CLOSING | CLOSED |
93 * +---------+-------------+---------------+---------------------------------+
96 /* states of the playing device */
97 #define WINE_WS_PLAYING 0
98 #define WINE_WS_PAUSED 1
99 #define WINE_WS_STOPPED 2
100 #define WINE_WS_CLOSED 3
102 /* events to be send to device */
103 enum win_wm_message {
104 WINE_WM_PAUSING = WM_USER + 1, WINE_WM_RESTARTING, WINE_WM_RESETTING, WINE_WM_HEADER,
105 WINE_WM_UPDATE, WINE_WM_BREAKLOOP, WINE_WM_CLOSING, WINE_WM_STARTING, WINE_WM_STOPPING
108 #ifdef USE_PIPE_SYNC
109 #define SIGNAL_OMR(omr) do { int x = 0; write((omr)->msg_pipe[1], &x, sizeof(x)); } while (0)
110 #define CLEAR_OMR(omr) do { int x = 0; read((omr)->msg_pipe[0], &x, sizeof(x)); } while (0)
111 #define RESET_OMR(omr) do { } while (0)
112 #define WAIT_OMR(omr, sleep) \
113 do { struct pollfd pfd; pfd.fd = (omr)->msg_pipe[0]; \
114 pfd.events = POLLIN; poll(&pfd, 1, sleep); } while (0)
115 #else
116 #define SIGNAL_OMR(omr) do { SetEvent((omr)->msg_event); } while (0)
117 #define CLEAR_OMR(omr) do { } while (0)
118 #define RESET_OMR(omr) do { ResetEvent((omr)->msg_event); } while (0)
119 #define WAIT_OMR(omr, sleep) \
120 do { WaitForSingleObject((omr)->msg_event, sleep); } while (0)
121 #endif
123 typedef struct {
124 enum win_wm_message msg; /* message identifier */
125 DWORD param; /* parameter for this message */
126 HANDLE hEvent; /* if message is synchronous, handle of event for synchro */
127 } ALSA_MSG;
129 /* implement an in-process message ring for better performance
130 * (compared to passing thru the server)
131 * this ring will be used by the input (resp output) record (resp playback) routine
133 #define ALSA_RING_BUFFER_INCREMENT 64
134 typedef struct {
135 ALSA_MSG * messages;
136 int ring_buffer_size;
137 int msg_tosave;
138 int msg_toget;
139 #ifdef USE_PIPE_SYNC
140 int msg_pipe[2];
141 #else
142 HANDLE msg_event;
143 #endif
144 CRITICAL_SECTION msg_crst;
145 } ALSA_MSG_RING;
147 typedef struct {
148 /* Windows information */
149 volatile int state; /* one of the WINE_WS_ manifest constants */
150 WAVEOPENDESC waveDesc;
151 WORD wFlags;
152 WAVEFORMATPCMEX format;
153 WAVEOUTCAPSA caps;
155 /* ALSA information (ALSA 0.9/1.x uses two different devices for playback/capture) */
156 char* device;
157 char interface_name[64];
158 snd_pcm_t* p_handle; /* handle to ALSA playback device */
159 snd_pcm_t* c_handle; /* handle to ALSA capture device */
160 snd_pcm_hw_params_t * hw_params; /* ALSA Hw params */
162 snd_ctl_t * ctl; /* control handle for the playback volume */
163 snd_ctl_elem_id_t * playback_eid; /* element id of the playback volume control */
164 snd_ctl_elem_value_t * playback_evalue; /* element value of the playback volume control */
165 snd_ctl_elem_info_t * playback_einfo; /* element info of the playback volume control */
167 snd_pcm_sframes_t (*write)(snd_pcm_t *, const void *, snd_pcm_uframes_t );
169 struct pollfd *ufds;
170 int count;
172 DWORD dwBufferSize; /* size of whole ALSA buffer in bytes */
173 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
174 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
175 DWORD dwPartialOffset; /* Offset of not yet written bytes in lpPlayPtr */
177 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
178 DWORD dwLoops; /* private copy of loop counter */
180 DWORD dwPlayedTotal; /* number of bytes actually played since opening */
181 DWORD dwWrittenTotal; /* number of bytes written to ALSA buffer since opening */
183 /* synchronization stuff */
184 HANDLE hStartUpEvent;
185 HANDLE hThread;
186 DWORD dwThreadID;
187 ALSA_MSG_RING msgRing;
189 /* DirectSound stuff */
190 DSDRIVERDESC ds_desc;
191 } WINE_WAVEOUT;
193 typedef struct {
194 /* Windows information */
195 volatile int state; /* one of the WINE_WS_ manifest constants */
196 WAVEOPENDESC waveDesc;
197 WORD wFlags;
198 WAVEFORMATPCMEX format;
199 WAVEOUTCAPSA caps;
201 /* ALSA information (ALSA 0.9/1.x uses two different devices for playback/capture) */
202 char* device;
203 char interface_name[64];
204 snd_pcm_t* p_handle; /* handle to ALSA playback device */
205 snd_pcm_t* c_handle; /* handle to ALSA capture device */
206 snd_pcm_hw_params_t * hw_params; /* ALSA Hw params */
208 snd_ctl_t * ctl; /* control handle for the playback volume */
209 snd_ctl_elem_id_t * playback_eid; /* element id of the playback volume control */
210 snd_ctl_elem_value_t * playback_evalue; /* element value of the playback volume control */
211 snd_ctl_elem_info_t * playback_einfo; /* element info of the playback volume control */
213 snd_pcm_sframes_t (*read)(snd_pcm_t *, void *, snd_pcm_uframes_t );
215 struct pollfd *ufds;
216 int count;
218 DWORD dwPeriodSize; /* size of OSS buffer period */
219 DWORD dwBufferSize; /* size of whole ALSA buffer in bytes */
220 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
221 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
223 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
224 DWORD dwLoops; /* private copy of loop counter */
226 /*DWORD dwPlayedTotal; */
227 DWORD dwTotalRecorded;
229 /* synchronization stuff */
230 HANDLE hStartUpEvent;
231 HANDLE hThread;
232 DWORD dwThreadID;
233 ALSA_MSG_RING msgRing;
235 /* DirectSound stuff */
236 DSDRIVERDESC ds_desc;
237 } WINE_WAVEIN;
239 static WINE_WAVEOUT WOutDev [MAX_WAVEOUTDRV];
240 static DWORD ALSA_WodNumDevs;
241 static WINE_WAVEIN WInDev [MAX_WAVEINDRV];
242 static DWORD ALSA_WidNumDevs;
244 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
245 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
247 /* These strings used only for tracing */
248 static const char * getCmdString(enum win_wm_message msg)
250 static char unknown[32];
251 #define MSG_TO_STR(x) case x: return #x
252 switch(msg) {
253 MSG_TO_STR(WINE_WM_PAUSING);
254 MSG_TO_STR(WINE_WM_RESTARTING);
255 MSG_TO_STR(WINE_WM_RESETTING);
256 MSG_TO_STR(WINE_WM_HEADER);
257 MSG_TO_STR(WINE_WM_UPDATE);
258 MSG_TO_STR(WINE_WM_BREAKLOOP);
259 MSG_TO_STR(WINE_WM_CLOSING);
260 MSG_TO_STR(WINE_WM_STARTING);
261 MSG_TO_STR(WINE_WM_STOPPING);
263 #undef MSG_TO_STR
264 sprintf(unknown, "UNKNOWN(0x%08x)", msg);
265 return unknown;
268 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
269 WAVEFORMATPCMEX* format)
271 TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
272 lpTime->wType, format->Format.wBitsPerSample, format->Format.nSamplesPerSec,
273 format->Format.nChannels, format->Format.nAvgBytesPerSec);
274 TRACE("Position in bytes=%lu\n", position);
276 switch (lpTime->wType) {
277 case TIME_SAMPLES:
278 lpTime->u.sample = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
279 TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
280 break;
281 case TIME_MS:
282 lpTime->u.ms = 1000.0 * position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels * format->Format.nSamplesPerSec);
283 TRACE("TIME_MS=%lu\n", lpTime->u.ms);
284 break;
285 case TIME_SMPTE:
286 position = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
287 lpTime->u.smpte.sec = position / format->Format.nSamplesPerSec;
288 position -= lpTime->u.smpte.sec * format->Format.nSamplesPerSec;
289 lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
290 lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
291 lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
292 lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
293 lpTime->u.smpte.fps = 30;
294 lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->Format.nSamplesPerSec;
295 position -= lpTime->u.smpte.frame * format->Format.nSamplesPerSec / lpTime->u.smpte.fps;
296 if (position != 0)
298 /* Round up */
299 lpTime->u.smpte.frame++;
301 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
302 lpTime->u.smpte.hour, lpTime->u.smpte.min,
303 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
304 break;
305 default:
306 FIXME("Format %d not supported ! use TIME_BYTES !\n", lpTime->wType);
307 lpTime->wType = TIME_BYTES;
308 /* fall through */
309 case TIME_BYTES:
310 lpTime->u.cb = position;
311 TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
312 break;
314 return MMSYSERR_NOERROR;
317 static BOOL supportedFormat(LPWAVEFORMATEX wf)
319 TRACE("(%p)\n",wf);
321 if (wf->nSamplesPerSec<DSBFREQUENCY_MIN||wf->nSamplesPerSec>DSBFREQUENCY_MAX)
322 return FALSE;
324 if (wf->wFormatTag == WAVE_FORMAT_PCM) {
325 if (wf->nChannels==1||wf->nChannels==2) {
326 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
327 return TRUE;
329 } else if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
330 WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE *)wf;
332 if (wf->cbSize == 22 &&
333 (IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM) ||
334 IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))) {
335 if (wf->nChannels>=1 && wf->nChannels<=6) {
336 if (wf->wBitsPerSample==wfex->Samples.wValidBitsPerSample) {
337 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16||
338 wf->wBitsPerSample==24||wf->wBitsPerSample==32) {
339 return TRUE;
341 } else
342 WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
344 } else
345 WARN("only KSDATAFORMAT_SUBTYPE_PCM and KSDATAFORMAT_SUBTYPE_IEEE_FLOAT "
346 "supported\n");
347 } else if (wf->wFormatTag == WAVE_FORMAT_MULAW || wf->wFormatTag == WAVE_FORMAT_ALAW) {
348 if (wf->wBitsPerSample==8)
349 return TRUE;
350 else
351 ERR("WAVE_FORMAT_MULAW and WAVE_FORMAT_ALAW wBitsPerSample must = 8\n");
353 } else if (wf->wFormatTag == WAVE_FORMAT_ADPCM) {
354 if (wf->wBitsPerSample==4)
355 return TRUE;
356 else
357 ERR("WAVE_FORMAT_ADPCM wBitsPerSample must = 4\n");
358 } else
359 WARN("only WAVE_FORMAT_PCM and WAVE_FORMAT_EXTENSIBLE supported\n");
361 return FALSE;
364 static void copy_format(LPWAVEFORMATEX wf1, LPWAVEFORMATPCMEX wf2)
366 ZeroMemory(wf2, sizeof(wf2));
367 if (wf1->wFormatTag == WAVE_FORMAT_PCM)
368 memcpy(wf2, wf1, sizeof(PCMWAVEFORMAT));
369 else if (wf1->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
370 memcpy(wf2, wf1, sizeof(WAVEFORMATPCMEX));
371 else
372 memcpy(wf2, wf1, sizeof(WAVEFORMATEX) + wf1->cbSize);
375 /*======================================================================*
376 * Low level WAVE implementation *
377 *======================================================================*/
379 /**************************************************************************
380 * ALSA_InitializeVolumeCtl [internal]
382 * used to initialize the PCM Volume Control
384 static int ALSA_InitializeVolumeCtl(WINE_WAVEOUT * wwo)
386 snd_ctl_t * ctl = NULL;
387 snd_ctl_card_info_t * cardinfo;
388 snd_ctl_elem_list_t * elemlist;
389 snd_ctl_elem_id_t * e_id;
390 snd_ctl_elem_info_t * einfo;
391 snd_hctl_t * hctl = NULL;
392 snd_hctl_elem_t * elem;
393 int nCtrls;
394 int i;
396 snd_ctl_card_info_alloca(&cardinfo);
397 memset(cardinfo,0,snd_ctl_card_info_sizeof());
399 snd_ctl_elem_list_alloca(&elemlist);
400 memset(elemlist,0,snd_ctl_elem_list_sizeof());
402 snd_ctl_elem_id_alloca(&e_id);
403 memset(e_id,0,snd_ctl_elem_id_sizeof());
405 snd_ctl_elem_info_alloca(&einfo);
406 memset(einfo,0,snd_ctl_elem_info_sizeof());
408 #define EXIT_ON_ERROR(f,txt) do \
410 int err; \
411 if ( (err = (f) ) < 0) \
413 ERR(txt ": %s\n", snd_strerror(err)); \
414 if (hctl) \
415 snd_hctl_close(hctl); \
416 if (ctl) \
417 snd_ctl_close(ctl); \
418 return -1; \
420 } while(0)
422 EXIT_ON_ERROR( snd_ctl_open(&ctl,"hw",0) , "ctl open failed" );
423 EXIT_ON_ERROR( snd_ctl_card_info(ctl, cardinfo), "card info failed");
424 EXIT_ON_ERROR( snd_ctl_elem_list(ctl, elemlist), "elem list failed");
426 nCtrls = snd_ctl_elem_list_get_count(elemlist);
428 EXIT_ON_ERROR( snd_hctl_open(&hctl,"hw",0), "hctl open failed");
429 EXIT_ON_ERROR( snd_hctl_load(hctl), "hctl load failed" );
431 elem=snd_hctl_first_elem(hctl);
432 for ( i= 0; i<nCtrls; i++) {
434 memset(e_id,0,snd_ctl_elem_id_sizeof());
436 snd_hctl_elem_get_id(elem,e_id);
438 TRACE("ctl: #%d '%s'%d\n",
439 snd_ctl_elem_id_get_numid(e_id),
440 snd_ctl_elem_id_get_name(e_id),
441 snd_ctl_elem_id_get_index(e_id));
443 if ( !strcmp("PCM Playback Volume", snd_ctl_elem_id_get_name(e_id)) )
445 EXIT_ON_ERROR( snd_hctl_elem_info(elem,einfo), "hctl elem info failed" );
447 /* few sanity checks... you'll never know... */
448 if ( snd_ctl_elem_info_get_type(einfo) != SND_CTL_ELEM_TYPE_INTEGER )
449 WARN("playback volume control is not an integer\n");
450 if ( !snd_ctl_elem_info_is_readable(einfo) )
451 WARN("playback volume control is readable\n");
452 if ( !snd_ctl_elem_info_is_writable(einfo) )
453 WARN("playback volume control is readable\n");
455 TRACE(" ctrl range: min=%ld max=%ld step=%ld\n",
456 snd_ctl_elem_info_get_min(einfo),
457 snd_ctl_elem_info_get_max(einfo),
458 snd_ctl_elem_info_get_step(einfo));
460 EXIT_ON_ERROR( snd_ctl_elem_id_malloc(&wwo->playback_eid), "elem id malloc failed" );
461 EXIT_ON_ERROR( snd_ctl_elem_info_malloc(&wwo->playback_einfo), "elem info malloc failed" );
462 EXIT_ON_ERROR( snd_ctl_elem_value_malloc(&wwo->playback_evalue), "elem value malloc failed" );
464 /* ok, now we can safely save these objects for later */
465 snd_ctl_elem_id_copy(wwo->playback_eid, e_id);
466 snd_ctl_elem_info_copy(wwo->playback_einfo, einfo);
467 snd_ctl_elem_value_set_id(wwo->playback_evalue, wwo->playback_eid);
468 wwo->ctl = ctl;
471 elem=snd_hctl_elem_next(elem);
473 snd_hctl_close(hctl);
474 #undef EXIT_ON_ERROR
475 return 0;
478 /**************************************************************************
479 * ALSA_XRUNRecovery [internal]
481 * used to recovery from XRUN errors (buffer underflow/overflow)
483 static int ALSA_XRUNRecovery(WINE_WAVEOUT * wwo, int err)
485 if (err == -EPIPE) { /* under-run */
486 err = snd_pcm_prepare(wwo->p_handle);
487 if (err < 0)
488 ERR( "underrun recovery failed. prepare failed: %s\n", snd_strerror(err));
489 return 0;
490 } else if (err == -ESTRPIPE) {
491 while ((err = snd_pcm_resume(wwo->p_handle)) == -EAGAIN)
492 sleep(1); /* wait until the suspend flag is released */
493 if (err < 0) {
494 err = snd_pcm_prepare(wwo->p_handle);
495 if (err < 0)
496 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
498 return 0;
500 return err;
503 /**************************************************************************
504 * ALSA_TraceParameters [internal]
506 * used to trace format changes, hw and sw parameters
508 static void ALSA_TraceParameters(snd_pcm_hw_params_t * hw_params, snd_pcm_sw_params_t * sw, int full)
510 int err;
511 snd_pcm_format_t format;
512 snd_pcm_access_t access;
514 err = snd_pcm_hw_params_get_access(hw_params, &access);
515 err = snd_pcm_hw_params_get_format(hw_params, &format);
517 #define X(x) ((x)? "true" : "false")
518 if (full)
519 TRACE("FLAGS: sampleres=%s overrng=%s pause=%s resume=%s syncstart=%s batch=%s block=%s double=%s "
520 "halfd=%s joint=%s \n",
521 X(snd_pcm_hw_params_can_mmap_sample_resolution(hw_params)),
522 X(snd_pcm_hw_params_can_overrange(hw_params)),
523 X(snd_pcm_hw_params_can_pause(hw_params)),
524 X(snd_pcm_hw_params_can_resume(hw_params)),
525 X(snd_pcm_hw_params_can_sync_start(hw_params)),
526 X(snd_pcm_hw_params_is_batch(hw_params)),
527 X(snd_pcm_hw_params_is_block_transfer(hw_params)),
528 X(snd_pcm_hw_params_is_double(hw_params)),
529 X(snd_pcm_hw_params_is_half_duplex(hw_params)),
530 X(snd_pcm_hw_params_is_joint_duplex(hw_params)));
531 #undef X
533 if (access >= 0)
534 TRACE("access=%s\n", snd_pcm_access_name(access));
535 else
537 snd_pcm_access_mask_t * acmask;
538 snd_pcm_access_mask_alloca(&acmask);
539 snd_pcm_hw_params_get_access_mask(hw_params, acmask);
540 for ( access = SND_PCM_ACCESS_MMAP_INTERLEAVED; access <= SND_PCM_ACCESS_LAST; access++)
541 if (snd_pcm_access_mask_test(acmask, access))
542 TRACE("access=%s\n", snd_pcm_access_name(access));
545 if (format >= 0)
547 TRACE("format=%s\n", snd_pcm_format_name(format));
550 else
552 snd_pcm_format_mask_t * fmask;
554 snd_pcm_format_mask_alloca(&fmask);
555 snd_pcm_hw_params_get_format_mask(hw_params, fmask);
556 for ( format = SND_PCM_FORMAT_S8; format <= SND_PCM_FORMAT_LAST ; format++)
557 if ( snd_pcm_format_mask_test(fmask, format) )
558 TRACE("format=%s\n", snd_pcm_format_name(format));
561 do {
562 int err=0;
563 unsigned int val=0;
564 err = snd_pcm_hw_params_get_channels(hw_params, &val);
565 if (err<0) {
566 unsigned int min = 0;
567 unsigned int max = 0;
568 err = snd_pcm_hw_params_get_channels_min(hw_params, &min),
569 err = snd_pcm_hw_params_get_channels_max(hw_params, &max);
570 TRACE("channels_min=%u, channels_min_max=%u\n", min, max);
571 } else {
572 TRACE("channels_min=%d\n", val);
574 } while(0);
575 do {
576 int err=0;
577 snd_pcm_uframes_t val=0;
578 err = snd_pcm_hw_params_get_buffer_size(hw_params, &val);
579 if (err<0) {
580 snd_pcm_uframes_t min = 0;
581 snd_pcm_uframes_t max = 0;
582 err = snd_pcm_hw_params_get_buffer_size_min(hw_params, &min),
583 err = snd_pcm_hw_params_get_buffer_size_max(hw_params, &max);
584 TRACE("buffer_size_min=%lu, buffer_size_min_max=%lu\n", min, max);
585 } else {
586 TRACE("buffer_size_min=%lu\n", val);
588 } while(0);
590 #define X(x) do { \
591 int err=0; \
592 int dir=0; \
593 unsigned int val=0; \
594 err = snd_pcm_hw_params_get_##x(hw_params,&val, &dir); \
595 if (err<0) { \
596 unsigned int min = 0; \
597 unsigned int max = 0; \
598 err = snd_pcm_hw_params_get_##x##_min(hw_params, &min, &dir); \
599 err = snd_pcm_hw_params_get_##x##_max(hw_params, &max, &dir); \
600 TRACE(#x "_min=%u " #x "_max=%u\n", min, max); \
601 } else \
602 TRACE(#x "=%d\n", val); \
603 } while(0)
605 X(rate);
606 X(buffer_time);
607 X(periods);
608 do {
609 int err=0;
610 int dir=0;
611 snd_pcm_uframes_t val=0;
612 err = snd_pcm_hw_params_get_period_size(hw_params, &val, &dir);
613 if (err<0) {
614 snd_pcm_uframes_t min = 0;
615 snd_pcm_uframes_t max = 0;
616 err = snd_pcm_hw_params_get_period_size_min(hw_params, &min, &dir),
617 err = snd_pcm_hw_params_get_period_size_max(hw_params, &max, &dir);
618 TRACE("period_size_min=%lu, period_size_min_max=%lu\n", min, max);
619 } else {
620 TRACE("period_size_min=%lu\n", val);
622 } while(0);
624 X(period_time);
625 X(tick_time);
626 #undef X
628 if (!sw)
629 return;
634 /* return a string duplicated on the win32 process heap, free with HeapFree */
635 static char* ALSA_strdup(char *s) {
636 char *result = HeapAlloc(GetProcessHeap(), 0, strlen(s)+1);
637 strcpy(result, s);
638 return result;
641 /******************************************************************
642 * ALSA_GetDeviceFromReg
644 * Returns either "default" or reads the registry so the user can
645 * override the playback/record device used.
647 char *ALSA_GetDeviceFromReg(char *value)
649 DWORD res;
650 DWORD type;
651 HKEY playbackKey = 0;
652 char *result = NULL;
653 DWORD resultSize;
655 res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\ALSA", 0, KEY_QUERY_VALUE, &playbackKey);
656 if (res != ERROR_SUCCESS) goto end;
658 res = RegQueryValueExA(playbackKey, value, NULL, &type, NULL, &resultSize);
659 if (res != ERROR_SUCCESS) goto end;
661 if (type != REG_SZ) {
662 ERR("Registry key [HKEY_LOCAL_MACHINE\\Software\\Wine\\Wine\\ALSA\\%s] must be a string\n", value);
663 goto end;
666 result = HeapAlloc(GetProcessHeap(), 0, resultSize);
667 res = RegQueryValueExA(playbackKey, value, NULL, NULL, result, &resultSize);
669 end:
670 if (!result) result = ALSA_strdup("default");
671 if (playbackKey) RegCloseKey(playbackKey);
672 return result;
675 /******************************************************************
676 * ALSA_WaveInit
678 * Initialize internal structures from ALSA information
680 LONG ALSA_WaveInit(void)
682 snd_pcm_t* h;
683 snd_pcm_info_t * info;
684 snd_pcm_hw_params_t * hw_params;
685 unsigned int ratemin=0;
686 unsigned int ratemax=0;
687 unsigned int chmin=0;
688 unsigned int chmax=0;
689 int dir=0;
690 int err=0;
691 WINE_WAVEOUT* wwo;
692 WINE_WAVEIN* wwi;
694 wwo = &WOutDev[0];
696 /* FIXME: use better values */
697 wwo->device = ALSA_GetDeviceFromReg("PlaybackDevice");
698 TRACE("using waveout device \"%s\"\n", wwo->device);
700 snprintf(wwo->interface_name, sizeof(wwo->interface_name), "winealsa: %s", wwo->device);
702 wwo->caps.wMid = 0x0002;
703 wwo->caps.wPid = 0x0104;
704 strcpy(wwo->caps.szPname, "SB16 Wave Out");
705 wwo->caps.vDriverVersion = 0x0100;
706 wwo->caps.dwFormats = 0x00000000;
707 wwo->caps.dwSupport = WAVECAPS_VOLUME;
708 strcpy(wwo->ds_desc.szDesc, "WineALSA DirectSound Driver");
709 strcpy(wwo->ds_desc.szDrvName, "winealsa.drv");
711 if (!wine_dlopen("libasound.so.2", RTLD_LAZY|RTLD_GLOBAL, NULL, 0))
713 ERR("Error: ALSA lib needs to be loaded with flags RTLD_LAZY and RTLD_GLOBAL.\n");
714 return -1;
717 snd_pcm_info_alloca(&info);
718 snd_pcm_hw_params_alloca(&hw_params);
720 #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)
722 h = NULL;
723 ALSA_WodNumDevs = 0;
724 EXIT_ON_ERROR( snd_pcm_open(&h, wwo->device, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK) , "open pcm" );
725 if (!h) return -1;
726 ALSA_WodNumDevs++;
728 EXIT_ON_ERROR( snd_pcm_info(h, info) , "pcm info" );
730 TRACE("dev=%d id=%s name=%s subdev=%d subdev_name=%s subdev_avail=%d subdev_num=%d stream=%s subclass=%s \n",
731 snd_pcm_info_get_device(info),
732 snd_pcm_info_get_id(info),
733 snd_pcm_info_get_name(info),
734 snd_pcm_info_get_subdevice(info),
735 snd_pcm_info_get_subdevice_name(info),
736 snd_pcm_info_get_subdevices_avail(info),
737 snd_pcm_info_get_subdevices_count(info),
738 snd_pcm_stream_name(snd_pcm_info_get_stream(info)),
739 (snd_pcm_info_get_subclass(info) == SND_PCM_SUBCLASS_GENERIC_MIX ? "GENERIC MIX": "MULTI MIX"));
741 EXIT_ON_ERROR( snd_pcm_hw_params_any(h, hw_params) , "pcm hw params" );
742 #undef EXIT_ON_ERROR
744 err = snd_pcm_hw_params_get_rate_min(hw_params, &ratemin, &dir);
745 err = snd_pcm_hw_params_get_rate_max(hw_params, &ratemax, &dir);
746 err = snd_pcm_hw_params_get_channels_min(hw_params, &chmin);
747 err = snd_pcm_hw_params_get_channels_max(hw_params, &chmax);
748 if (TRACE_ON(wave))
749 ALSA_TraceParameters(hw_params, NULL, TRUE);
752 snd_pcm_format_mask_t * fmask;
754 snd_pcm_format_mask_alloca(&fmask);
755 snd_pcm_hw_params_get_format_mask(hw_params, fmask);
757 #define X(r,v) \
758 if ( (r) >= ratemin && ( (r) <= ratemax || ratemax == -1) ) \
760 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_U8)) \
762 if (chmin <= 1 && 1 <= chmax) \
763 wwo->caps.dwFormats |= WAVE_FORMAT_##v##M08; \
764 if (chmin <= 2 && 2 <= chmax) \
765 wwo->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
767 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_S16_LE)) \
769 if (chmin <= 1 && 1 <= chmax) \
770 wwo->caps.dwFormats |= WAVE_FORMAT_##v##M16; \
771 if (chmin <= 2 && 2 <= chmax) \
772 wwo->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
775 X(11025,1);
776 X(22050,2);
777 X(44100,4);
778 X(48000,48);
779 X(96000,96);
780 #undef X
783 if ( chmin > 1) FIXME("-\n");
784 wwo->caps.wChannels = chmax;
785 if (chmin <= 2 && 2 <= chmax)
786 wwo->caps.dwSupport |= WAVECAPS_LRVOLUME;
788 /* FIXME: always true ? */
789 wwo->caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
792 snd_pcm_access_mask_t * acmask;
793 snd_pcm_access_mask_alloca(&acmask);
794 snd_pcm_hw_params_get_access_mask(hw_params, acmask);
796 /* FIXME: NONITERLEAVED and COMPLEX are not supported right now */
797 if ( snd_pcm_access_mask_test( acmask, SND_PCM_ACCESS_MMAP_INTERLEAVED ) )
798 wwo->caps.dwSupport |= WAVECAPS_DIRECTSOUND;
801 TRACE("Configured with dwFmts=%08lx dwSupport=%08lx\n",
802 wwo->caps.dwFormats, wwo->caps.dwSupport);
804 snd_pcm_close(h);
806 ALSA_InitializeVolumeCtl(wwo);
808 wwi = &WInDev[0];
810 /* FIXME: use better values */
811 wwi->device = ALSA_GetDeviceFromReg("RecordDevice");
812 TRACE("using wavein device \"%s\"\n", wwi->device);
814 snprintf(wwi->interface_name, sizeof(wwi->interface_name), "winealsa: %s", wwi->device);
816 wwi->caps.wMid = 0x0002;
817 wwi->caps.wPid = 0x0104;
818 strcpy(wwi->caps.szPname, "SB16 Wave In");
819 wwi->caps.vDriverVersion = 0x0100;
820 wwi->caps.dwFormats = 0x00000000;
821 wwi->caps.dwSupport = WAVECAPS_VOLUME;
822 strcpy(wwi->ds_desc.szDesc, "WineALSA DirectSound Driver");
823 strcpy(wwi->ds_desc.szDrvName, "winealsa.drv");
825 snd_pcm_info_alloca(&info);
826 snd_pcm_hw_params_alloca(&hw_params);
828 #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)
830 h = NULL;
831 ALSA_WidNumDevs = 0;
832 EXIT_ON_ERROR( snd_pcm_open(&h, wwi->device, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK) , "open pcm" );
833 if (!h) return -1;
834 ALSA_WidNumDevs++;
836 EXIT_ON_ERROR( snd_pcm_info(h, info) , "pcm info" );
838 TRACE("dev=%d id=%s name=%s subdev=%d subdev_name=%s subdev_avail=%d subdev_num=%d stream=%s subclass=%s \n",
839 snd_pcm_info_get_device(info),
840 snd_pcm_info_get_id(info),
841 snd_pcm_info_get_name(info),
842 snd_pcm_info_get_subdevice(info),
843 snd_pcm_info_get_subdevice_name(info),
844 snd_pcm_info_get_subdevices_avail(info),
845 snd_pcm_info_get_subdevices_count(info),
846 snd_pcm_stream_name(snd_pcm_info_get_stream(info)),
847 (snd_pcm_info_get_subclass(info) == SND_PCM_SUBCLASS_GENERIC_MIX ? "GENERIC MIX": "MULTI MIX"));
849 EXIT_ON_ERROR( snd_pcm_hw_params_any(h, hw_params) , "pcm hw params" );
850 #undef EXIT_ON_ERROR
851 err = snd_pcm_hw_params_get_rate_min(hw_params, &ratemin, &dir);
852 err = snd_pcm_hw_params_get_rate_max(hw_params, &ratemax, &dir);
853 err = snd_pcm_hw_params_get_channels_min(hw_params, &chmin);
854 err = snd_pcm_hw_params_get_channels_max(hw_params, &chmax);
856 if (TRACE_ON(wave))
857 ALSA_TraceParameters(hw_params, NULL, TRUE);
860 snd_pcm_format_mask_t * fmask;
862 snd_pcm_format_mask_alloca(&fmask);
863 snd_pcm_hw_params_get_format_mask(hw_params, fmask);
865 #define X(r,v) \
866 if ( (r) >= ratemin && ( (r) <= ratemax || ratemax == -1) ) \
868 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_U8)) \
870 if (chmin <= 1 && 1 <= chmax) \
871 wwi->caps.dwFormats |= WAVE_FORMAT_##v##M08; \
872 if (chmin <= 2 && 2 <= chmax) \
873 wwi->caps.dwFormats |= WAVE_FORMAT_##v##S08; \
875 if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_S16_LE)) \
877 if (chmin <= 1 && 1 <= chmax) \
878 wwi->caps.dwFormats |= WAVE_FORMAT_##v##M16; \
879 if (chmin <= 2 && 2 <= chmax) \
880 wwi->caps.dwFormats |= WAVE_FORMAT_##v##S16; \
883 X(11025,1);
884 X(22050,2);
885 X(44100,4);
886 X(48000,48);
887 X(96000,96);
888 #undef X
891 if ( chmin > 1) FIXME("-\n");
892 wwi->caps.wChannels = chmax;
893 if (chmin <= 2 && 2 <= chmax)
894 wwi->caps.dwSupport |= WAVECAPS_LRVOLUME;
896 /* FIXME: always true ? */
897 wwi->caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
900 snd_pcm_access_mask_t * acmask;
901 snd_pcm_access_mask_alloca(&acmask);
902 snd_pcm_hw_params_get_access_mask(hw_params, acmask);
904 /* FIXME: NONITERLEAVED and COMPLEX are not supported right now */
905 if ( snd_pcm_access_mask_test( acmask, SND_PCM_ACCESS_MMAP_INTERLEAVED ) ) {
906 #if 0
907 wwi->caps.dwSupport |= WAVECAPS_DIRECTSOUND;
908 #endif
912 TRACE("Configured with dwFmts=%08lx dwSupport=%08lx\n",
913 wwi->caps.dwFormats, wwi->caps.dwSupport);
915 snd_pcm_close(h);
917 return 0;
920 /******************************************************************
921 * ALSA_InitRingMessage
923 * Initialize the ring of messages for passing between driver's caller and playback/record
924 * thread
926 static int ALSA_InitRingMessage(ALSA_MSG_RING* omr)
928 omr->msg_toget = 0;
929 omr->msg_tosave = 0;
930 #ifdef USE_PIPE_SYNC
931 if (pipe(omr->msg_pipe) < 0) {
932 omr->msg_pipe[0] = -1;
933 omr->msg_pipe[1] = -1;
934 ERR("could not create pipe, error=%s\n", strerror(errno));
936 #else
937 omr->msg_event = CreateEventA(NULL, FALSE, FALSE, NULL);
938 #endif
939 omr->ring_buffer_size = ALSA_RING_BUFFER_INCREMENT;
940 omr->messages = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,omr->ring_buffer_size * sizeof(ALSA_MSG));
942 InitializeCriticalSection(&omr->msg_crst);
943 return 0;
946 /******************************************************************
947 * ALSA_DestroyRingMessage
950 static int ALSA_DestroyRingMessage(ALSA_MSG_RING* omr)
952 #ifdef USE_PIPE_SYNC
953 close(omr->msg_pipe[0]);
954 close(omr->msg_pipe[1]);
955 #else
956 CloseHandle(omr->msg_event);
957 #endif
958 HeapFree(GetProcessHeap(),0,omr->messages);
959 DeleteCriticalSection(&omr->msg_crst);
960 return 0;
963 /******************************************************************
964 * ALSA_AddRingMessage
966 * Inserts a new message into the ring (should be called from DriverProc derivated routines)
968 static int ALSA_AddRingMessage(ALSA_MSG_RING* omr, enum win_wm_message msg, DWORD param, BOOL wait)
970 HANDLE hEvent = INVALID_HANDLE_VALUE;
972 EnterCriticalSection(&omr->msg_crst);
973 if ((omr->msg_toget == ((omr->msg_tosave + 1) % omr->ring_buffer_size)))
975 int old_ring_buffer_size = omr->ring_buffer_size;
976 omr->ring_buffer_size += ALSA_RING_BUFFER_INCREMENT;
977 TRACE("omr->ring_buffer_size=%d\n",omr->ring_buffer_size);
978 omr->messages = HeapReAlloc(GetProcessHeap(),0,omr->messages, omr->ring_buffer_size * sizeof(ALSA_MSG));
979 /* Now we need to rearrange the ring buffer so that the new
980 buffers just allocated are in between omr->msg_tosave and
981 omr->msg_toget.
983 if (omr->msg_tosave < omr->msg_toget)
985 memmove(&(omr->messages[omr->msg_toget + ALSA_RING_BUFFER_INCREMENT]),
986 &(omr->messages[omr->msg_toget]),
987 sizeof(ALSA_MSG)*(old_ring_buffer_size - omr->msg_toget)
989 omr->msg_toget += ALSA_RING_BUFFER_INCREMENT;
992 if (wait)
994 hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
995 if (hEvent == INVALID_HANDLE_VALUE)
997 ERR("can't create event !?\n");
998 LeaveCriticalSection(&omr->msg_crst);
999 return 0;
1001 if (omr->msg_toget != omr->msg_tosave && omr->messages[omr->msg_toget].msg != WINE_WM_HEADER)
1002 FIXME("two fast messages in the queue!!!! toget = %d(%s), tosave=%d(%s)\n",
1003 omr->msg_toget,getCmdString(omr->messages[omr->msg_toget].msg),
1004 omr->msg_tosave,getCmdString(omr->messages[omr->msg_tosave].msg));
1006 /* fast messages have to be added at the start of the queue */
1007 omr->msg_toget = (omr->msg_toget + omr->ring_buffer_size - 1) % omr->ring_buffer_size;
1009 omr->messages[omr->msg_toget].msg = msg;
1010 omr->messages[omr->msg_toget].param = param;
1011 omr->messages[omr->msg_toget].hEvent = hEvent;
1013 else
1015 omr->messages[omr->msg_tosave].msg = msg;
1016 omr->messages[omr->msg_tosave].param = param;
1017 omr->messages[omr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
1018 omr->msg_tosave = (omr->msg_tosave + 1) % omr->ring_buffer_size;
1020 LeaveCriticalSection(&omr->msg_crst);
1021 /* signal a new message */
1022 SIGNAL_OMR(omr);
1023 if (wait)
1025 /* wait for playback/record thread to have processed the message */
1026 WaitForSingleObject(hEvent, INFINITE);
1027 CloseHandle(hEvent);
1029 return 1;
1032 /******************************************************************
1033 * ALSA_RetrieveRingMessage
1035 * Get a message from the ring. Should be called by the playback/record thread.
1037 static int ALSA_RetrieveRingMessage(ALSA_MSG_RING* omr,
1038 enum win_wm_message *msg, DWORD *param, HANDLE *hEvent)
1040 EnterCriticalSection(&omr->msg_crst);
1042 if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
1044 LeaveCriticalSection(&omr->msg_crst);
1045 return 0;
1048 *msg = omr->messages[omr->msg_toget].msg;
1049 omr->messages[omr->msg_toget].msg = 0;
1050 *param = omr->messages[omr->msg_toget].param;
1051 *hEvent = omr->messages[omr->msg_toget].hEvent;
1052 omr->msg_toget = (omr->msg_toget + 1) % omr->ring_buffer_size;
1053 CLEAR_OMR(omr);
1054 LeaveCriticalSection(&omr->msg_crst);
1055 return 1;
1058 /******************************************************************
1059 * ALSA_PeekRingMessage
1061 * Peek at a message from the ring but do not remove it.
1062 * Should be called by the playback/record thread.
1064 static int ALSA_PeekRingMessage(ALSA_MSG_RING* omr,
1065 enum win_wm_message *msg,
1066 DWORD *param, HANDLE *hEvent)
1068 EnterCriticalSection(&omr->msg_crst);
1070 if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
1072 LeaveCriticalSection(&omr->msg_crst);
1073 return 0;
1076 *msg = omr->messages[omr->msg_toget].msg;
1077 *param = omr->messages[omr->msg_toget].param;
1078 *hEvent = omr->messages[omr->msg_toget].hEvent;
1079 LeaveCriticalSection(&omr->msg_crst);
1080 return 1;
1083 /*======================================================================*
1084 * Low level WAVE OUT implementation *
1085 *======================================================================*/
1087 /**************************************************************************
1088 * wodNotifyClient [internal]
1090 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1092 TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
1094 switch (wMsg) {
1095 case WOM_OPEN:
1096 case WOM_CLOSE:
1097 case WOM_DONE:
1098 if (wwo->wFlags != DCB_NULL &&
1099 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags, (HDRVR)wwo->waveDesc.hWave,
1100 wMsg, wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
1101 WARN("can't notify client !\n");
1102 return MMSYSERR_ERROR;
1104 break;
1105 default:
1106 FIXME("Unknown callback message %u\n", wMsg);
1107 return MMSYSERR_INVALPARAM;
1109 return MMSYSERR_NOERROR;
1112 /**************************************************************************
1113 * wodUpdatePlayedTotal [internal]
1116 static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo, snd_pcm_status_t* ps)
1118 snd_pcm_sframes_t delay = 0;
1119 snd_pcm_delay(wwo->p_handle, &delay);
1120 if (snd_pcm_state(wwo->p_handle) != SND_PCM_STATE_RUNNING)
1121 delay=0;
1122 wwo->dwPlayedTotal = wwo->dwWrittenTotal - snd_pcm_frames_to_bytes(wwo->p_handle, delay);
1123 return TRUE;
1126 /**************************************************************************
1127 * wodPlayer_BeginWaveHdr [internal]
1129 * Makes the specified lpWaveHdr the currently playing wave header.
1130 * If the specified wave header is a begin loop and we're not already in
1131 * a loop, setup the loop.
1133 static void wodPlayer_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1135 wwo->lpPlayPtr = lpWaveHdr;
1137 if (!lpWaveHdr) return;
1139 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
1140 if (wwo->lpLoopPtr) {
1141 WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1142 } else {
1143 TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1144 wwo->lpLoopPtr = lpWaveHdr;
1145 /* Windows does not touch WAVEHDR.dwLoops,
1146 * so we need to make an internal copy */
1147 wwo->dwLoops = lpWaveHdr->dwLoops;
1150 wwo->dwPartialOffset = 0;
1153 /**************************************************************************
1154 * wodPlayer_PlayPtrNext [internal]
1156 * Advance the play pointer to the next waveheader, looping if required.
1158 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEOUT* wwo)
1160 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1162 wwo->dwPartialOffset = 0;
1163 if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
1164 /* We're at the end of a loop, loop if required */
1165 if (--wwo->dwLoops > 0) {
1166 wwo->lpPlayPtr = wwo->lpLoopPtr;
1167 } else {
1168 /* Handle overlapping loops correctly */
1169 if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
1170 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
1171 /* shall we consider the END flag for the closing loop or for
1172 * the opening one or for both ???
1173 * code assumes for closing loop only
1175 } else {
1176 lpWaveHdr = lpWaveHdr->lpNext;
1178 wwo->lpLoopPtr = NULL;
1179 wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
1181 } else {
1182 /* We're not in a loop. Advance to the next wave header */
1183 wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
1186 return lpWaveHdr;
1189 /**************************************************************************
1190 * wodPlayer_DSPWait [internal]
1191 * Returns the number of milliseconds to wait for the DSP buffer to play a
1192 * period
1194 static DWORD wodPlayer_DSPWait(const WINE_WAVEOUT *wwo)
1196 /* time for one period to be played */
1197 unsigned int val=0;
1198 int dir=0;
1199 int err=0;
1200 err = snd_pcm_hw_params_get_period_time(wwo->hw_params, &val, &dir);
1201 return val / 1000;
1204 /**************************************************************************
1205 * wodPlayer_NotifyWait [internal]
1206 * Returns the number of milliseconds to wait before attempting to notify
1207 * completion of the specified wavehdr.
1208 * This is based on the number of bytes remaining to be written in the
1209 * wave.
1211 static DWORD wodPlayer_NotifyWait(const WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1213 DWORD dwMillis;
1215 if (lpWaveHdr->reserved < wwo->dwPlayedTotal) {
1216 dwMillis = 1;
1217 } else {
1218 dwMillis = (lpWaveHdr->reserved - wwo->dwPlayedTotal) * 1000 / wwo->format.Format.nAvgBytesPerSec;
1219 if (!dwMillis) dwMillis = 1;
1222 return dwMillis;
1226 /**************************************************************************
1227 * wodPlayer_WriteMaxFrags [internal]
1228 * Writes the maximum number of frames possible to the DSP and returns
1229 * the number of frames written.
1231 static int wodPlayer_WriteMaxFrags(WINE_WAVEOUT* wwo, DWORD* frames)
1233 /* Only attempt to write to free frames */
1234 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1235 DWORD dwLength = snd_pcm_bytes_to_frames(wwo->p_handle, lpWaveHdr->dwBufferLength - wwo->dwPartialOffset);
1236 int toWrite = min(dwLength, *frames);
1237 int written;
1239 TRACE("Writing wavehdr %p.%lu[%lu]\n", lpWaveHdr, wwo->dwPartialOffset, lpWaveHdr->dwBufferLength);
1241 written = (wwo->write)(wwo->p_handle, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
1242 if ( written < 0)
1244 /* XRUN occurred. let's try to recover */
1245 ALSA_XRUNRecovery(wwo, written);
1246 written = (wwo->write)(wwo->p_handle, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
1248 if (written <= 0)
1250 /* still in error */
1251 ERR("Error in writing wavehdr. Reason: %s\n", snd_strerror(written));
1252 return written;
1255 wwo->dwPartialOffset += snd_pcm_frames_to_bytes(wwo->p_handle, written);
1256 if ( wwo->dwPartialOffset >= lpWaveHdr->dwBufferLength) {
1257 /* this will be used to check if the given wave header has been fully played or not... */
1258 wwo->dwPartialOffset = lpWaveHdr->dwBufferLength;
1259 /* If we wrote all current wavehdr, skip to the next one */
1260 wodPlayer_PlayPtrNext(wwo);
1262 *frames -= written;
1263 wwo->dwWrittenTotal += snd_pcm_frames_to_bytes(wwo->p_handle, written);
1265 return written;
1269 /**************************************************************************
1270 * wodPlayer_NotifyCompletions [internal]
1272 * Notifies and remove from queue all wavehdrs which have been played to
1273 * the speaker (ie. they have cleared the ALSA buffer). If force is true,
1274 * we notify all wavehdrs and remove them all from the queue even if they
1275 * are unplayed or part of a loop.
1277 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1279 LPWAVEHDR lpWaveHdr;
1281 /* Start from lpQueuePtr and keep notifying until:
1282 * - we hit an unwritten wavehdr
1283 * - we hit the beginning of a running loop
1284 * - we hit a wavehdr which hasn't finished playing
1286 #if 0
1287 while ((lpWaveHdr = wwo->lpQueuePtr) &&
1288 (force ||
1289 (lpWaveHdr != wwo->lpPlayPtr &&
1290 lpWaveHdr != wwo->lpLoopPtr &&
1291 lpWaveHdr->reserved <= wwo->dwPlayedTotal))) {
1293 wwo->lpQueuePtr = lpWaveHdr->lpNext;
1295 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1296 lpWaveHdr->dwFlags |= WHDR_DONE;
1298 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1300 #else
1301 for (;;)
1303 lpWaveHdr = wwo->lpQueuePtr;
1304 if (!lpWaveHdr) {TRACE("Empty queue\n"); break;}
1305 if (!force)
1307 if (lpWaveHdr == wwo->lpPlayPtr) {TRACE("play %p\n", lpWaveHdr); break;}
1308 if (lpWaveHdr == wwo->lpLoopPtr) {TRACE("loop %p\n", lpWaveHdr); break;}
1309 if (lpWaveHdr->reserved > wwo->dwPlayedTotal){TRACE("still playing %p (%lu/%lu)\n", lpWaveHdr, lpWaveHdr->reserved, wwo->dwPlayedTotal);break;}
1311 wwo->lpQueuePtr = lpWaveHdr->lpNext;
1313 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1314 lpWaveHdr->dwFlags |= WHDR_DONE;
1316 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1318 #endif
1319 return (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
1320 wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
1324 void wait_for_poll(snd_pcm_t *handle, struct pollfd *ufds, unsigned int count)
1326 unsigned short revents;
1328 if (snd_pcm_state(handle) != SND_PCM_STATE_RUNNING)
1329 return;
1331 while (1) {
1332 poll(ufds, count, -1);
1333 snd_pcm_poll_descriptors_revents(handle, ufds, count, &revents);
1335 if (revents & POLLERR)
1336 return;
1338 /*if (revents & POLLOUT)
1339 return 0;*/
1344 /**************************************************************************
1345 * wodPlayer_Reset [internal]
1347 * wodPlayer helper. Resets current output stream.
1349 static void wodPlayer_Reset(WINE_WAVEOUT* wwo)
1351 enum win_wm_message msg;
1352 DWORD param;
1353 HANDLE ev;
1354 int err;
1356 /* flush all possible output */
1357 wait_for_poll(wwo->p_handle, wwo->ufds, wwo->count);
1359 wodUpdatePlayedTotal(wwo, NULL);
1360 /* updates current notify list */
1361 wodPlayer_NotifyCompletions(wwo, FALSE);
1363 if ( (err = snd_pcm_drop(wwo->p_handle)) < 0) {
1364 FIXME("flush: %s\n", snd_strerror(err));
1365 wwo->hThread = 0;
1366 wwo->state = WINE_WS_STOPPED;
1367 ExitThread(-1);
1369 if ( (err = snd_pcm_prepare(wwo->p_handle)) < 0 )
1370 ERR("pcm prepare failed: %s\n", snd_strerror(err));
1372 /* remove any buffer */
1373 wodPlayer_NotifyCompletions(wwo, TRUE);
1375 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1376 wwo->state = WINE_WS_STOPPED;
1377 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1378 /* Clear partial wavehdr */
1379 wwo->dwPartialOffset = 0;
1381 /* remove any existing message in the ring */
1382 EnterCriticalSection(&wwo->msgRing.msg_crst);
1383 /* return all pending headers in queue */
1384 while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
1386 if (msg != WINE_WM_HEADER)
1388 FIXME("shouldn't have headers left\n");
1389 SetEvent(ev);
1390 continue;
1392 ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
1393 ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
1395 wodNotifyClient(wwo, WOM_DONE, param, 0);
1397 RESET_OMR(&wwo->msgRing);
1398 LeaveCriticalSection(&wwo->msgRing.msg_crst);
1401 /**************************************************************************
1402 * wodPlayer_ProcessMessages [internal]
1404 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
1406 LPWAVEHDR lpWaveHdr;
1407 enum win_wm_message msg;
1408 DWORD param;
1409 HANDLE ev;
1410 int err;
1412 while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
1413 TRACE("Received %s %lx\n", getCmdString(msg), param);
1415 switch (msg) {
1416 case WINE_WM_PAUSING:
1417 if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_RUNNING )
1419 err = snd_pcm_pause(wwo->p_handle, 1);
1420 if ( err < 0 )
1421 ERR("pcm_pause failed: %s\n", snd_strerror(err));
1423 wwo->state = WINE_WS_PAUSED;
1424 SetEvent(ev);
1425 break;
1426 case WINE_WM_RESTARTING:
1427 if (wwo->state == WINE_WS_PAUSED)
1429 if ( snd_pcm_state(wwo->p_handle) == SND_PCM_STATE_PAUSED )
1431 err = snd_pcm_pause(wwo->p_handle, 0);
1432 if ( err < 0 )
1433 ERR("pcm_pause failed: %s\n", snd_strerror(err));
1435 wwo->state = WINE_WS_PLAYING;
1437 SetEvent(ev);
1438 break;
1439 case WINE_WM_HEADER:
1440 lpWaveHdr = (LPWAVEHDR)param;
1442 /* insert buffer at the end of queue */
1444 LPWAVEHDR* wh;
1445 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1446 *wh = lpWaveHdr;
1448 if (!wwo->lpPlayPtr)
1449 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
1450 if (wwo->state == WINE_WS_STOPPED)
1451 wwo->state = WINE_WS_PLAYING;
1452 break;
1453 case WINE_WM_RESETTING:
1454 wodPlayer_Reset(wwo);
1455 SetEvent(ev);
1456 break;
1457 case WINE_WM_UPDATE:
1458 wodUpdatePlayedTotal(wwo, NULL);
1459 SetEvent(ev);
1460 break;
1461 case WINE_WM_BREAKLOOP:
1462 if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
1463 /* ensure exit at end of current loop */
1464 wwo->dwLoops = 1;
1466 SetEvent(ev);
1467 break;
1468 case WINE_WM_CLOSING:
1469 /* sanity check: this should not happen since the device must have been reset before */
1470 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1471 wwo->hThread = 0;
1472 wwo->state = WINE_WS_CLOSED;
1473 SetEvent(ev);
1474 ExitThread(0);
1475 /* shouldn't go here */
1476 default:
1477 FIXME("unknown message %d\n", msg);
1478 break;
1483 /**************************************************************************
1484 * wodPlayer_FeedDSP [internal]
1485 * Feed as much sound data as we can into the DSP and return the number of
1486 * milliseconds before it will be necessary to feed the DSP again.
1488 static DWORD wodPlayer_FeedDSP(WINE_WAVEOUT* wwo)
1490 DWORD availInQ;
1492 wodUpdatePlayedTotal(wwo, NULL);
1493 availInQ = snd_pcm_avail_update(wwo->p_handle);
1495 #if 0
1496 /* input queue empty and output buffer with less than one fragment to play */
1497 if (!wwo->lpPlayPtr && wwo->dwBufferSize < availInQ + wwo->dwFragmentSize) {
1498 TRACE("Run out of wavehdr:s...\n");
1499 return INFINITE;
1501 #endif
1503 /* no more room... no need to try to feed */
1504 if (availInQ > 0) {
1505 /* Feed from partial wavehdr */
1506 if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0) {
1507 wodPlayer_WriteMaxFrags(wwo, &availInQ);
1510 /* Feed wavehdrs until we run out of wavehdrs or DSP space */
1511 if (wwo->dwPartialOffset == 0 && wwo->lpPlayPtr) {
1512 do {
1513 TRACE("Setting time to elapse for %p to %lu\n",
1514 wwo->lpPlayPtr, wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength);
1515 /* note the value that dwPlayedTotal will return when this wave finishes playing */
1516 wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
1517 } while (wodPlayer_WriteMaxFrags(wwo, &availInQ) && wwo->lpPlayPtr && availInQ > 0);
1521 return wodPlayer_DSPWait(wwo);
1524 /**************************************************************************
1525 * wodPlayer [internal]
1527 static DWORD CALLBACK wodPlayer(LPVOID pmt)
1529 WORD uDevID = (DWORD)pmt;
1530 WINE_WAVEOUT* wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
1531 DWORD dwNextFeedTime = INFINITE; /* Time before DSP needs feeding */
1532 DWORD dwNextNotifyTime = INFINITE; /* Time before next wave completion */
1533 DWORD dwSleepTime;
1535 wwo->state = WINE_WS_STOPPED;
1536 SetEvent(wwo->hStartUpEvent);
1538 for (;;) {
1539 /** Wait for the shortest time before an action is required. If there
1540 * are no pending actions, wait forever for a command.
1542 dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
1543 TRACE("waiting %lums (%lu,%lu)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
1544 WAIT_OMR(&wwo->msgRing, dwSleepTime);
1545 wodPlayer_ProcessMessages(wwo);
1546 if (wwo->state == WINE_WS_PLAYING) {
1547 dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1548 dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1549 if (dwNextFeedTime == INFINITE) {
1550 /* FeedDSP ran out of data, but before giving up, */
1551 /* check that a notification didn't give us more */
1552 wodPlayer_ProcessMessages(wwo);
1553 if (wwo->lpPlayPtr) {
1554 TRACE("recovering\n");
1555 dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1558 } else {
1559 dwNextFeedTime = dwNextNotifyTime = INFINITE;
1564 /**************************************************************************
1565 * wodGetDevCaps [internal]
1567 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSA lpCaps, DWORD dwSize)
1569 TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1571 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1573 if (wDevID >= MAX_WAVEOUTDRV) {
1574 TRACE("MAX_WAVOUTDRV reached !\n");
1575 return MMSYSERR_BADDEVICEID;
1578 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1579 return MMSYSERR_NOERROR;
1582 /**************************************************************************
1583 * wodOpen [internal]
1585 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1587 WINE_WAVEOUT* wwo;
1588 snd_pcm_hw_params_t * hw_params;
1589 snd_pcm_sw_params_t * sw_params;
1590 snd_pcm_access_t access;
1591 snd_pcm_format_t format = -1;
1592 unsigned int rate;
1593 unsigned int buffer_time = 500000;
1594 unsigned int period_time = 10000;
1595 snd_pcm_uframes_t buffer_size;
1596 snd_pcm_uframes_t period_size;
1597 int flags;
1598 snd_pcm_t * pcm;
1599 int err=0;
1600 int dir=0;
1602 snd_pcm_hw_params_alloca(&hw_params);
1603 snd_pcm_sw_params_alloca(&sw_params);
1605 TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
1606 if (lpDesc == NULL) {
1607 WARN("Invalid Parameter !\n");
1608 return MMSYSERR_INVALPARAM;
1610 if (wDevID >= MAX_WAVEOUTDRV) {
1611 TRACE("MAX_WAVOUTDRV reached !\n");
1612 return MMSYSERR_BADDEVICEID;
1615 /* only PCM format is supported so far... */
1616 if (!supportedFormat(lpDesc->lpFormat)) {
1617 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1618 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1619 lpDesc->lpFormat->nSamplesPerSec);
1620 return WAVERR_BADFORMAT;
1623 if (dwFlags & WAVE_FORMAT_QUERY) {
1624 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1625 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1626 lpDesc->lpFormat->nSamplesPerSec);
1627 return MMSYSERR_NOERROR;
1630 wwo = &WOutDev[wDevID];
1632 if ((dwFlags & WAVE_DIRECTSOUND) && !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
1633 /* not supported, ignore it */
1634 dwFlags &= ~WAVE_DIRECTSOUND;
1636 wwo->p_handle = 0;
1637 flags = SND_PCM_NONBLOCK;
1638 if ( dwFlags & WAVE_DIRECTSOUND )
1639 flags |= SND_PCM_ASYNC;
1641 if ( (err = snd_pcm_open(&pcm, wwo->device, SND_PCM_STREAM_PLAYBACK, flags)) < 0)
1643 ERR("Error open: %s\n", snd_strerror(err));
1644 return MMSYSERR_NOTENABLED;
1647 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1649 memcpy(&wwo->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
1650 copy_format(lpDesc->lpFormat, &wwo->format);
1652 if (wwo->format.Format.wBitsPerSample == 0) {
1653 WARN("Resetting zeroed wBitsPerSample\n");
1654 wwo->format.Format.wBitsPerSample = 8 *
1655 (wwo->format.Format.nAvgBytesPerSec /
1656 wwo->format.Format.nSamplesPerSec) /
1657 wwo->format.Format.nChannels;
1660 snd_pcm_hw_params_any(pcm, hw_params);
1662 #define EXIT_ON_ERROR(f,e,txt) do \
1664 int err; \
1665 if ( (err = (f) ) < 0) \
1667 ERR(txt ": %s\n", snd_strerror(err)); \
1668 snd_pcm_close(pcm); \
1669 return e; \
1671 } while(0)
1673 access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
1674 if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
1675 WARN("mmap not available. switching to standard write.\n");
1676 access = SND_PCM_ACCESS_RW_INTERLEAVED;
1677 EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
1678 wwo->write = snd_pcm_writei;
1680 else
1681 wwo->write = snd_pcm_mmap_writei;
1683 EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwo->format.Format.nChannels), MMSYSERR_INVALPARAM, "unable to set required channels");
1685 if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
1686 ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
1687 IsEqualGUID(&wwo->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
1688 format = (wwo->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
1689 (wwo->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
1690 (wwo->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
1691 (wwo->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
1692 } else if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
1693 IsEqualGUID(&wwo->format.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)){
1694 format = (wwo->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_FLOAT_LE : -1;
1695 } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
1696 FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
1697 snd_pcm_close(pcm);
1698 return WAVERR_BADFORMAT;
1699 } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
1700 FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
1701 snd_pcm_close(pcm);
1702 return WAVERR_BADFORMAT;
1703 } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
1704 FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
1705 snd_pcm_close(pcm);
1706 return WAVERR_BADFORMAT;
1707 } else {
1708 ERR("invalid format: %0x04x\n", wwo->format.Format.wFormatTag);
1709 snd_pcm_close(pcm);
1710 return WAVERR_BADFORMAT;
1713 EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), MMSYSERR_INVALPARAM, "unable to set required format");
1715 rate = wwo->format.Format.nSamplesPerSec;
1716 dir=0;
1717 err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
1718 if (err < 0) {
1719 ERR("Rate %ld Hz not available for playback: %s\n", wwo->format.Format.nSamplesPerSec, snd_strerror(rate));
1720 snd_pcm_close(pcm);
1721 return WAVERR_BADFORMAT;
1723 if (rate != wwo->format.Format.nSamplesPerSec) {
1724 ERR("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwo->format.Format.nSamplesPerSec, rate);
1725 snd_pcm_close(pcm);
1726 return WAVERR_BADFORMAT;
1728 dir=0;
1729 EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
1730 dir=0;
1731 EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
1733 EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
1735 err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
1736 err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
1738 snd_pcm_sw_params_current(pcm, sw_params);
1739 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");
1740 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
1741 EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
1742 EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
1743 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
1744 EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
1745 #undef EXIT_ON_ERROR
1747 snd_pcm_prepare(pcm);
1749 if (TRACE_ON(wave))
1750 ALSA_TraceParameters(hw_params, sw_params, FALSE);
1752 /* now, we can save all required data for later use... */
1753 if ( wwo->hw_params )
1754 snd_pcm_hw_params_free(wwo->hw_params);
1755 snd_pcm_hw_params_malloc(&(wwo->hw_params));
1756 snd_pcm_hw_params_copy(wwo->hw_params, hw_params);
1758 wwo->dwBufferSize = buffer_size;
1759 wwo->lpQueuePtr = wwo->lpPlayPtr = wwo->lpLoopPtr = NULL;
1760 wwo->p_handle = pcm;
1761 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1762 wwo->dwPartialOffset = 0;
1764 ALSA_InitRingMessage(&wwo->msgRing);
1766 wwo->count = snd_pcm_poll_descriptors_count (wwo->p_handle);
1767 if (wwo->count <= 0) {
1768 ERR("Invalid poll descriptors count\n");
1769 return MMSYSERR_ERROR;
1772 wwo->ufds = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct pollfd) * wwo->count);
1773 if (wwo->ufds == NULL) {
1774 ERR("No enough memory\n");
1775 return MMSYSERR_NOMEM;
1777 if ((err = snd_pcm_poll_descriptors(wwo->p_handle, wwo->ufds, wwo->count)) < 0) {
1778 ERR("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
1779 return MMSYSERR_ERROR;
1782 if (!(dwFlags & WAVE_DIRECTSOUND)) {
1783 wwo->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
1784 wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
1785 WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
1786 CloseHandle(wwo->hStartUpEvent);
1787 } else {
1788 wwo->hThread = INVALID_HANDLE_VALUE;
1789 wwo->dwThreadID = 0;
1791 wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
1793 TRACE("handle=%08lx \n", (DWORD)wwo->p_handle);
1794 /* if (wwo->dwFragmentSize % wwo->format.Format.nBlockAlign)
1795 ERR("Fragment doesn't contain an integral number of data blocks\n");
1797 TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
1798 wwo->format.Format.wBitsPerSample, wwo->format.Format.nAvgBytesPerSec,
1799 wwo->format.Format.nSamplesPerSec, wwo->format.Format.nChannels,
1800 wwo->format.Format.nBlockAlign);
1802 return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
1806 /**************************************************************************
1807 * wodClose [internal]
1809 static DWORD wodClose(WORD wDevID)
1811 DWORD ret = MMSYSERR_NOERROR;
1812 WINE_WAVEOUT* wwo;
1814 TRACE("(%u);\n", wDevID);
1816 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1817 WARN("bad device ID !\n");
1818 return MMSYSERR_BADDEVICEID;
1821 wwo = &WOutDev[wDevID];
1822 if (wwo->lpQueuePtr) {
1823 WARN("buffers still playing !\n");
1824 ret = WAVERR_STILLPLAYING;
1825 } else {
1826 if (wwo->hThread != INVALID_HANDLE_VALUE) {
1827 ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1829 ALSA_DestroyRingMessage(&wwo->msgRing);
1831 snd_pcm_hw_params_free(wwo->hw_params);
1832 wwo->hw_params = NULL;
1834 snd_pcm_close(wwo->p_handle);
1835 wwo->p_handle = NULL;
1837 ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1840 HeapFree(GetProcessHeap(), 0, wwo->ufds);
1841 return ret;
1845 /**************************************************************************
1846 * wodWrite [internal]
1849 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1851 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1853 /* first, do the sanity checks... */
1854 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1855 WARN("bad dev ID !\n");
1856 return MMSYSERR_BADDEVICEID;
1859 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1860 return WAVERR_UNPREPARED;
1862 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1863 return WAVERR_STILLPLAYING;
1865 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1866 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1867 lpWaveHdr->lpNext = 0;
1869 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1871 return MMSYSERR_NOERROR;
1874 /**************************************************************************
1875 * wodPrepare [internal]
1877 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1879 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1881 if (wDevID >= MAX_WAVEOUTDRV) {
1882 WARN("bad device ID !\n");
1883 return MMSYSERR_BADDEVICEID;
1886 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1887 return WAVERR_STILLPLAYING;
1889 lpWaveHdr->dwFlags |= WHDR_PREPARED;
1890 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1891 return MMSYSERR_NOERROR;
1894 /**************************************************************************
1895 * wodUnprepare [internal]
1897 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1899 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1901 if (wDevID >= MAX_WAVEOUTDRV) {
1902 WARN("bad device ID !\n");
1903 return MMSYSERR_BADDEVICEID;
1906 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1907 return WAVERR_STILLPLAYING;
1909 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1910 lpWaveHdr->dwFlags |= WHDR_DONE;
1912 return MMSYSERR_NOERROR;
1915 /**************************************************************************
1916 * wodPause [internal]
1918 static DWORD wodPause(WORD wDevID)
1920 TRACE("(%u);!\n", wDevID);
1922 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1923 WARN("bad device ID !\n");
1924 return MMSYSERR_BADDEVICEID;
1927 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1929 return MMSYSERR_NOERROR;
1932 /**************************************************************************
1933 * wodRestart [internal]
1935 static DWORD wodRestart(WORD wDevID)
1937 TRACE("(%u);\n", wDevID);
1939 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1940 WARN("bad device ID !\n");
1941 return MMSYSERR_BADDEVICEID;
1944 if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1945 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1948 /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1949 /* FIXME: Myst crashes with this ... hmm -MM
1950 return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1953 return MMSYSERR_NOERROR;
1956 /**************************************************************************
1957 * wodReset [internal]
1959 static DWORD wodReset(WORD wDevID)
1961 TRACE("(%u);\n", wDevID);
1963 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1964 WARN("bad device ID !\n");
1965 return MMSYSERR_BADDEVICEID;
1968 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1970 return MMSYSERR_NOERROR;
1973 /**************************************************************************
1974 * wodGetPosition [internal]
1976 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1978 WINE_WAVEOUT* wwo;
1980 TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1982 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
1983 WARN("bad device ID !\n");
1984 return MMSYSERR_BADDEVICEID;
1987 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1989 wwo = &WOutDev[wDevID];
1990 ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1992 return bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->format);
1995 /**************************************************************************
1996 * wodBreakLoop [internal]
1998 static DWORD wodBreakLoop(WORD wDevID)
2000 TRACE("(%u);\n", wDevID);
2002 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
2003 WARN("bad device ID !\n");
2004 return MMSYSERR_BADDEVICEID;
2006 ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
2007 return MMSYSERR_NOERROR;
2010 /**************************************************************************
2011 * wodGetVolume [internal]
2013 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
2015 WORD left, right;
2016 WINE_WAVEOUT* wwo;
2017 int count;
2018 long min, max;
2020 TRACE("(%u, %p);\n", wDevID, lpdwVol);
2021 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
2022 WARN("bad device ID !\n");
2023 return MMSYSERR_BADDEVICEID;
2025 wwo = &WOutDev[wDevID];
2026 count = snd_ctl_elem_info_get_count(wwo->playback_einfo);
2027 min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
2028 max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
2030 #define VOLUME_ALSA_TO_WIN(x) (((x)-min) * 65536 /(max-min))
2031 if (lpdwVol == NULL)
2032 return MMSYSERR_NOTENABLED;
2034 switch (count)
2036 case 2:
2037 left = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
2038 right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 1));
2039 break;
2040 case 1:
2041 left = right = VOLUME_ALSA_TO_WIN(snd_ctl_elem_value_get_integer(wwo->playback_evalue, 0));
2042 break;
2043 default:
2044 WARN("%d channels mixer not supported\n", count);
2045 return MMSYSERR_NOERROR;
2047 #undef VOLUME_ALSA_TO_WIN
2049 TRACE("left=%d right=%d !\n", left, right);
2050 *lpdwVol = MAKELONG( left, right );
2051 return MMSYSERR_NOERROR;
2054 /**************************************************************************
2055 * wodSetVolume [internal]
2057 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
2059 WORD left, right;
2060 WINE_WAVEOUT* wwo;
2061 int count, err;
2062 long min, max;
2064 TRACE("(%u, %08lX);\n", wDevID, dwParam);
2065 if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].p_handle == NULL) {
2066 WARN("bad device ID !\n");
2067 return MMSYSERR_BADDEVICEID;
2069 wwo = &WOutDev[wDevID];
2070 count=snd_ctl_elem_info_get_count(wwo->playback_einfo);
2071 min = snd_ctl_elem_info_get_min(wwo->playback_einfo);
2072 max = snd_ctl_elem_info_get_max(wwo->playback_einfo);
2074 left = LOWORD(dwParam);
2075 right = HIWORD(dwParam);
2077 #define VOLUME_WIN_TO_ALSA(x) ( (((x) * (max-min)) / 65536) + min )
2078 switch (count)
2080 case 2:
2081 snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
2082 snd_ctl_elem_value_set_integer(wwo->playback_evalue, 1, VOLUME_WIN_TO_ALSA(right));
2083 break;
2084 case 1:
2085 snd_ctl_elem_value_set_integer(wwo->playback_evalue, 0, VOLUME_WIN_TO_ALSA(left));
2086 break;
2087 default:
2088 WARN("%d channels mixer not supported\n", count);
2090 #undef VOLUME_WIN_TO_ALSA
2091 if ( (err = snd_ctl_elem_write(wwo->ctl, wwo->playback_evalue)) < 0)
2093 ERR("error writing snd_ctl_elem_value: %s\n", snd_strerror(err));
2095 return MMSYSERR_NOERROR;
2098 /**************************************************************************
2099 * wodGetNumDevs [internal]
2101 static DWORD wodGetNumDevs(void)
2103 return ALSA_WodNumDevs;
2106 /**************************************************************************
2107 * wodDevInterfaceSize [internal]
2109 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2111 TRACE("(%u, %p)\n", wDevID, dwParam1);
2113 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2114 NULL, 0 ) * sizeof(WCHAR);
2115 return MMSYSERR_NOERROR;
2118 /**************************************************************************
2119 * wodDevInterface [internal]
2121 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2123 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2124 NULL, 0 ) * sizeof(WCHAR))
2126 MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
2127 dwParam1, dwParam2 / sizeof(WCHAR));
2128 return MMSYSERR_NOERROR;
2130 return MMSYSERR_INVALPARAM;
2133 /**************************************************************************
2134 * wodMessage (WINEALSA.@)
2136 DWORD WINAPI ALSA_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
2137 DWORD dwParam1, DWORD dwParam2)
2139 TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
2140 wDevID, wMsg, dwUser, dwParam1, dwParam2);
2142 switch (wMsg) {
2143 case DRVM_INIT:
2144 case DRVM_EXIT:
2145 case DRVM_ENABLE:
2146 case DRVM_DISABLE:
2147 /* FIXME: Pretend this is supported */
2148 return 0;
2149 case WODM_OPEN: return wodOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2150 case WODM_CLOSE: return wodClose (wDevID);
2151 case WODM_GETDEVCAPS: return wodGetDevCaps (wDevID, (LPWAVEOUTCAPSA)dwParam1, dwParam2);
2152 case WODM_GETNUMDEVS: return wodGetNumDevs ();
2153 case WODM_GETPITCH: return MMSYSERR_NOTSUPPORTED;
2154 case WODM_SETPITCH: return MMSYSERR_NOTSUPPORTED;
2155 case WODM_GETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
2156 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
2157 case WODM_WRITE: return wodWrite (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2158 case WODM_PAUSE: return wodPause (wDevID);
2159 case WODM_GETPOS: return wodGetPosition (wDevID, (LPMMTIME)dwParam1, dwParam2);
2160 case WODM_BREAKLOOP: return wodBreakLoop (wDevID);
2161 case WODM_PREPARE: return wodPrepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2162 case WODM_UNPREPARE: return wodUnprepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2163 case WODM_GETVOLUME: return wodGetVolume (wDevID, (LPDWORD)dwParam1);
2164 case WODM_SETVOLUME: return wodSetVolume (wDevID, dwParam1);
2165 case WODM_RESTART: return wodRestart (wDevID);
2166 case WODM_RESET: return wodReset (wDevID);
2167 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2168 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2169 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
2170 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
2172 default:
2173 FIXME("unknown message %d!\n", wMsg);
2175 return MMSYSERR_NOTSUPPORTED;
2178 /*======================================================================*
2179 * Low level DSOUND implementation *
2180 *======================================================================*/
2182 typedef struct IDsDriverImpl IDsDriverImpl;
2183 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
2185 struct IDsDriverImpl
2187 /* IUnknown fields */
2188 IDsDriverVtbl *lpVtbl;
2189 DWORD ref;
2190 /* IDsDriverImpl fields */
2191 UINT wDevID;
2192 IDsDriverBufferImpl*primary;
2195 struct IDsDriverBufferImpl
2197 /* IUnknown fields */
2198 IDsDriverBufferVtbl *lpVtbl;
2199 DWORD ref;
2200 /* IDsDriverBufferImpl fields */
2201 IDsDriverImpl* drv;
2203 CRITICAL_SECTION mmap_crst;
2204 LPVOID mmap_buffer;
2205 DWORD mmap_buflen_bytes;
2206 snd_pcm_uframes_t mmap_buflen_frames;
2207 snd_pcm_channel_area_t * mmap_areas;
2208 snd_async_handler_t * mmap_async_handler;
2211 static void DSDB_CheckXRUN(IDsDriverBufferImpl* pdbi)
2213 WINE_WAVEOUT * wwo = &(WOutDev[pdbi->drv->wDevID]);
2214 snd_pcm_state_t state = snd_pcm_state(wwo->p_handle);
2216 if ( state == SND_PCM_STATE_XRUN )
2218 int err = snd_pcm_prepare(wwo->p_handle);
2219 TRACE("xrun occurred\n");
2220 if ( err < 0 )
2221 ERR("recovery from xrun failed, prepare failed: %s\n", snd_strerror(err));
2223 else if ( state == SND_PCM_STATE_SUSPENDED )
2225 int err = snd_pcm_resume(wwo->p_handle);
2226 TRACE("recovery from suspension occurred\n");
2227 if (err < 0 && err != -EAGAIN){
2228 err = snd_pcm_prepare(wwo->p_handle);
2229 if (err < 0)
2230 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
2235 static void DSDB_MMAPCopy(IDsDriverBufferImpl* pdbi)
2237 WINE_WAVEOUT * wwo = &(WOutDev[pdbi->drv->wDevID]);
2238 unsigned int channels;
2239 snd_pcm_format_t format;
2240 snd_pcm_uframes_t period_size;
2241 snd_pcm_sframes_t avail;
2242 int err;
2243 int dir=0;
2245 if ( !pdbi->mmap_buffer || !wwo->hw_params || !wwo->p_handle)
2246 return;
2248 err = snd_pcm_hw_params_get_channels(wwo->hw_params, &channels);
2249 err = snd_pcm_hw_params_get_format(wwo->hw_params, &format);
2250 dir=0;
2251 err = snd_pcm_hw_params_get_period_size(wwo->hw_params, &period_size, &dir);
2252 avail = snd_pcm_avail_update(wwo->p_handle);
2254 DSDB_CheckXRUN(pdbi);
2256 TRACE("avail=%d format=%s channels=%d\n", (int)avail, snd_pcm_format_name(format), channels );
2258 while (avail >= period_size)
2260 const snd_pcm_channel_area_t *areas;
2261 snd_pcm_uframes_t ofs;
2262 snd_pcm_uframes_t frames;
2263 int err;
2265 frames = avail / period_size * period_size; /* round down to a multiple of period_size */
2267 EnterCriticalSection(&pdbi->mmap_crst);
2269 snd_pcm_mmap_begin(wwo->p_handle, &areas, &ofs, &frames);
2270 snd_pcm_areas_copy(areas, ofs, pdbi->mmap_areas, ofs, channels, frames, format);
2271 err = snd_pcm_mmap_commit(wwo->p_handle, ofs, frames);
2273 LeaveCriticalSection(&pdbi->mmap_crst);
2275 if ( err != (snd_pcm_sframes_t) frames)
2276 ERR("mmap partially failed.\n");
2278 avail = snd_pcm_avail_update(wwo->p_handle);
2282 static void DSDB_PCMCallback(snd_async_handler_t *ahandler)
2284 /* snd_pcm_t * handle = snd_async_handler_get_pcm(ahandler); */
2285 IDsDriverBufferImpl* pdbi = snd_async_handler_get_callback_private(ahandler);
2286 TRACE("callback called\n");
2287 DSDB_MMAPCopy(pdbi);
2290 static int DSDB_CreateMMAP(IDsDriverBufferImpl* pdbi)
2292 WINE_WAVEOUT * wwo = &(WOutDev[pdbi->drv->wDevID]);
2293 snd_pcm_format_t format;
2294 snd_pcm_uframes_t frames;
2295 unsigned int channels;
2296 unsigned int bits_per_sample;
2297 unsigned int bits_per_frame;
2298 snd_pcm_channel_area_t * a;
2299 unsigned int c;
2300 int err;
2302 err = snd_pcm_hw_params_get_format(wwo->hw_params, &format);
2303 err = snd_pcm_hw_params_get_buffer_size(wwo->hw_params, &frames);
2304 err = snd_pcm_hw_params_get_channels(wwo->hw_params, &channels);
2305 bits_per_sample = snd_pcm_format_physical_width(format);
2306 bits_per_frame = bits_per_sample * channels;
2309 if (TRACE_ON(wave))
2310 ALSA_TraceParameters(wwo->hw_params, NULL, FALSE);
2312 TRACE("format=%s frames=%ld channels=%d bits_per_sample=%d bits_per_frame=%d\n",
2313 snd_pcm_format_name(format), frames, channels, bits_per_sample, bits_per_frame);
2315 pdbi->mmap_buflen_frames = frames;
2316 pdbi->mmap_buflen_bytes = snd_pcm_frames_to_bytes( wwo->p_handle, frames );
2317 pdbi->mmap_buffer = HeapAlloc(GetProcessHeap(),0,pdbi->mmap_buflen_bytes);
2318 if (!pdbi->mmap_buffer)
2319 return DSERR_OUTOFMEMORY;
2321 snd_pcm_format_set_silence(format, pdbi->mmap_buffer, frames );
2323 TRACE("created mmap buffer of %ld frames (%ld bytes) at %p\n",
2324 frames, pdbi->mmap_buflen_bytes, pdbi->mmap_buffer);
2326 pdbi->mmap_areas = HeapAlloc(GetProcessHeap(),0,channels*sizeof(snd_pcm_channel_area_t));
2327 if (!pdbi->mmap_areas)
2328 return DSERR_OUTOFMEMORY;
2330 a = pdbi->mmap_areas;
2331 for (c = 0; c < channels; c++, a++)
2333 a->addr = pdbi->mmap_buffer;
2334 a->first = bits_per_sample * c;
2335 a->step = bits_per_frame;
2336 TRACE("Area %d: addr=%p first=%d step=%d\n", c, a->addr, a->first, a->step);
2339 InitializeCriticalSection(&pdbi->mmap_crst);
2341 err = snd_async_add_pcm_handler(&pdbi->mmap_async_handler, wwo->p_handle, DSDB_PCMCallback, pdbi);
2342 if ( err < 0 )
2344 ERR("add_pcm_handler failed. reason: %s\n", snd_strerror(err));
2345 return DSERR_GENERIC;
2348 return DS_OK;
2351 static void DSDB_DestroyMMAP(IDsDriverBufferImpl* pdbi)
2353 TRACE("mmap buffer %p destroyed\n", pdbi->mmap_buffer);
2354 HeapFree(GetProcessHeap(), 0, pdbi->mmap_areas);
2355 HeapFree(GetProcessHeap(), 0, pdbi->mmap_buffer);
2356 pdbi->mmap_areas = NULL;
2357 pdbi->mmap_buffer = NULL;
2358 DeleteCriticalSection(&pdbi->mmap_crst);
2362 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
2364 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2365 FIXME("(): stub!\n");
2366 return DSERR_UNSUPPORTED;
2369 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
2371 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2372 TRACE("(%p)\n",iface);
2373 return ++This->ref;
2376 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
2378 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2379 TRACE("(%p)\n",iface);
2380 if (--This->ref)
2381 return This->ref;
2382 if (This == This->drv->primary)
2383 This->drv->primary = NULL;
2384 DSDB_DestroyMMAP(This);
2385 HeapFree(GetProcessHeap(), 0, This);
2386 return 0;
2389 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
2390 LPVOID*ppvAudio1,LPDWORD pdwLen1,
2391 LPVOID*ppvAudio2,LPDWORD pdwLen2,
2392 DWORD dwWritePosition,DWORD dwWriteLen,
2393 DWORD dwFlags)
2395 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2396 TRACE("(%p)\n",iface);
2397 return DSERR_UNSUPPORTED;
2400 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
2401 LPVOID pvAudio1,DWORD dwLen1,
2402 LPVOID pvAudio2,DWORD dwLen2)
2404 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2405 TRACE("(%p)\n",iface);
2406 return DSERR_UNSUPPORTED;
2409 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
2410 LPWAVEFORMATEX pwfx)
2412 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2413 TRACE("(%p,%p)\n",iface,pwfx);
2414 return DSERR_BUFFERLOST;
2417 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
2419 /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
2420 TRACE("(%p,%ld): stub\n",iface,dwFreq);
2421 return DSERR_UNSUPPORTED;
2424 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
2426 DWORD vol;
2427 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2428 TRACE("(%p,%p)\n",iface,pVolPan);
2429 vol = pVolPan->dwTotalLeftAmpFactor | (pVolPan->dwTotalRightAmpFactor << 16);
2431 if (wodSetVolume(This->drv->wDevID, vol) != MMSYSERR_NOERROR) {
2432 WARN("wodSetVolume failed\n");
2433 return DSERR_INVALIDPARAM;
2436 return DS_OK;
2439 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
2441 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2442 TRACE("(%p,%ld): stub\n",iface,dwNewPos);
2443 return DSERR_UNSUPPORTED;
2446 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
2447 LPDWORD lpdwPlay, LPDWORD lpdwWrite)
2449 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2450 WINE_WAVEOUT * wwo = &(WOutDev[This->drv->wDevID]);
2451 snd_pcm_uframes_t hw_ptr;
2452 snd_pcm_uframes_t period_size;
2453 int dir;
2454 int err;
2456 if (wwo->hw_params == NULL) return DSERR_GENERIC;
2458 dir=0;
2459 err = snd_pcm_hw_params_get_period_size(wwo->hw_params, &period_size, &dir);
2461 if (wwo->p_handle == NULL) return DSERR_GENERIC;
2462 /** we need to track down buffer underruns */
2463 DSDB_CheckXRUN(This);
2465 EnterCriticalSection(&This->mmap_crst);
2466 /* FIXME: snd_pcm_mmap_hw_ptr() should not be accessed by a user app. */
2467 /* It will NOT return what why want anyway. */
2468 hw_ptr = _snd_pcm_mmap_hw_ptr(wwo->p_handle);
2469 if (lpdwPlay)
2470 *lpdwPlay = snd_pcm_frames_to_bytes(wwo->p_handle, hw_ptr/ period_size * period_size) % This->mmap_buflen_bytes;
2471 if (lpdwWrite)
2472 *lpdwWrite = snd_pcm_frames_to_bytes(wwo->p_handle, (hw_ptr / period_size + 1) * period_size ) % This->mmap_buflen_bytes;
2473 LeaveCriticalSection(&This->mmap_crst);
2475 TRACE("hw_ptr=0x%08x, playpos=%ld, writepos=%ld\n", (unsigned int)hw_ptr, lpdwPlay?*lpdwPlay:-1, lpdwWrite?*lpdwWrite:-1);
2476 return DS_OK;
2479 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
2481 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2482 WINE_WAVEOUT * wwo = &(WOutDev[This->drv->wDevID]);
2483 snd_pcm_state_t state;
2484 int err;
2486 TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
2488 if (wwo->p_handle == NULL) return DSERR_GENERIC;
2490 state = snd_pcm_state(wwo->p_handle);
2491 if ( state == SND_PCM_STATE_SETUP )
2493 err = snd_pcm_prepare(wwo->p_handle);
2494 state = snd_pcm_state(wwo->p_handle);
2496 if ( state == SND_PCM_STATE_PREPARED )
2498 DSDB_MMAPCopy(This);
2499 err = snd_pcm_start(wwo->p_handle);
2501 return DS_OK;
2504 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
2506 IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
2507 WINE_WAVEOUT * wwo = &(WOutDev[This->drv->wDevID]);
2508 int err;
2509 DWORD play;
2510 DWORD write;
2512 TRACE("(%p)\n",iface);
2514 if (wwo->p_handle == NULL) return DSERR_GENERIC;
2516 /* ring buffer wrap up detection */
2517 IDsDriverBufferImpl_GetPosition(iface, &play, &write);
2518 if ( play > write)
2520 TRACE("writepos wrapper up\n");
2521 return DS_OK;
2524 if ( ( err = snd_pcm_drop(wwo->p_handle)) < 0 )
2526 ERR("error while stopping pcm: %s\n", snd_strerror(err));
2527 return DSERR_GENERIC;
2529 return DS_OK;
2532 static IDsDriverBufferVtbl dsdbvt =
2534 IDsDriverBufferImpl_QueryInterface,
2535 IDsDriverBufferImpl_AddRef,
2536 IDsDriverBufferImpl_Release,
2537 IDsDriverBufferImpl_Lock,
2538 IDsDriverBufferImpl_Unlock,
2539 IDsDriverBufferImpl_SetFormat,
2540 IDsDriverBufferImpl_SetFrequency,
2541 IDsDriverBufferImpl_SetVolumePan,
2542 IDsDriverBufferImpl_SetPosition,
2543 IDsDriverBufferImpl_GetPosition,
2544 IDsDriverBufferImpl_Play,
2545 IDsDriverBufferImpl_Stop
2548 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
2550 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2551 FIXME("(%p): stub!\n",iface);
2552 return DSERR_UNSUPPORTED;
2555 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
2557 IDsDriverImpl *This = (IDsDriverImpl *)iface;
2558 TRACE("(%p)\n",iface);
2559 This->ref++;
2560 return This->ref;
2563 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
2565 IDsDriverImpl *This = (IDsDriverImpl *)iface;
2566 TRACE("(%p)\n",iface);
2567 if (--This->ref)
2568 return This->ref;
2569 HeapFree(GetProcessHeap(),0,This);
2570 return 0;
2573 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
2575 IDsDriverImpl *This = (IDsDriverImpl *)iface;
2576 TRACE("(%p,%p)\n",iface,pDesc);
2577 memcpy(pDesc, &(WOutDev[This->wDevID].ds_desc), sizeof(DSDRIVERDESC));
2578 pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
2579 DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK;
2580 pDesc->dnDevNode = WOutDev[This->wDevID].waveDesc.dnDevNode;
2581 pDesc->wVxdId = 0;
2582 pDesc->wReserved = 0;
2583 pDesc->ulDeviceNum = This->wDevID;
2584 pDesc->dwHeapType = DSDHEAP_NOHEAP;
2585 pDesc->pvDirectDrawHeap = NULL;
2586 pDesc->dwMemStartAddress = 0;
2587 pDesc->dwMemEndAddress = 0;
2588 pDesc->dwMemAllocExtra = 0;
2589 pDesc->pvReserved1 = NULL;
2590 pDesc->pvReserved2 = NULL;
2591 return DS_OK;
2594 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
2596 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2597 TRACE("(%p)\n",iface);
2598 return DS_OK;
2601 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
2603 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2604 TRACE("(%p)\n",iface);
2605 return DS_OK;
2608 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
2610 IDsDriverImpl *This = (IDsDriverImpl *)iface;
2611 TRACE("(%p,%p)\n",iface,pCaps);
2612 memset(pCaps, 0, sizeof(*pCaps));
2614 pCaps->dwFlags = DSCAPS_PRIMARYMONO;
2615 if ( WOutDev[This->wDevID].caps.wChannels == 2 )
2616 pCaps->dwFlags |= DSCAPS_PRIMARYSTEREO;
2618 if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 ) )
2619 pCaps->dwFlags |= DSCAPS_PRIMARY8BIT;
2621 if ( WOutDev[This->wDevID].caps.dwFormats & (WAVE_FORMAT_1S16 | WAVE_FORMAT_2S16 | WAVE_FORMAT_4S16))
2622 pCaps->dwFlags |= DSCAPS_PRIMARY16BIT;
2624 pCaps->dwPrimaryBuffers = 1;
2625 TRACE("caps=0x%X\n",(unsigned int)pCaps->dwFlags);
2626 pCaps->dwMinSecondarySampleRate = DSBFREQUENCY_MIN;
2627 pCaps->dwMaxSecondarySampleRate = DSBFREQUENCY_MAX;
2629 /* the other fields only apply to secondary buffers, which we don't support
2630 * (unless we want to mess with wavetable synthesizers and MIDI) */
2631 return DS_OK;
2634 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
2635 LPWAVEFORMATEX pwfx,
2636 DWORD dwFlags, DWORD dwCardAddress,
2637 LPDWORD pdwcbBufferSize,
2638 LPBYTE *ppbBuffer,
2639 LPVOID *ppvObj)
2641 IDsDriverImpl *This = (IDsDriverImpl *)iface;
2642 IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
2643 int err;
2645 TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
2646 /* we only support primary buffers */
2647 if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
2648 return DSERR_UNSUPPORTED;
2649 if (This->primary)
2650 return DSERR_ALLOCATED;
2651 if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
2652 return DSERR_CONTROLUNAVAIL;
2654 *ippdsdb = (IDsDriverBufferImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
2655 if (*ippdsdb == NULL)
2656 return DSERR_OUTOFMEMORY;
2657 (*ippdsdb)->lpVtbl = &dsdbvt;
2658 (*ippdsdb)->ref = 1;
2659 (*ippdsdb)->drv = This;
2661 err = DSDB_CreateMMAP((*ippdsdb));
2662 if ( err != DS_OK )
2664 HeapFree(GetProcessHeap(), 0, *ippdsdb);
2665 *ippdsdb = NULL;
2666 return err;
2668 *ppbBuffer = (*ippdsdb)->mmap_buffer;
2669 *pdwcbBufferSize = (*ippdsdb)->mmap_buflen_bytes;
2671 This->primary = *ippdsdb;
2673 /* buffer is ready to go */
2674 TRACE("buffer created at %p\n", *ippdsdb);
2675 return DS_OK;
2678 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
2679 PIDSDRIVERBUFFER pBuffer,
2680 LPVOID *ppvObj)
2682 /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
2683 TRACE("(%p,%p): stub\n",iface,pBuffer);
2684 return DSERR_INVALIDCALL;
2687 static IDsDriverVtbl dsdvt =
2689 IDsDriverImpl_QueryInterface,
2690 IDsDriverImpl_AddRef,
2691 IDsDriverImpl_Release,
2692 IDsDriverImpl_GetDriverDesc,
2693 IDsDriverImpl_Open,
2694 IDsDriverImpl_Close,
2695 IDsDriverImpl_GetCaps,
2696 IDsDriverImpl_CreateSoundBuffer,
2697 IDsDriverImpl_DuplicateSoundBuffer
2700 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
2702 IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
2704 TRACE("driver created\n");
2706 /* the HAL isn't much better than the HEL if we can't do mmap() */
2707 if (!(WOutDev[wDevID].caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
2708 ERR("DirectSound flag not set\n");
2709 MESSAGE("This sound card's driver does not support direct access\n");
2710 MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
2711 return MMSYSERR_NOTSUPPORTED;
2714 *idrv = (IDsDriverImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
2715 if (!*idrv)
2716 return MMSYSERR_NOMEM;
2717 (*idrv)->lpVtbl = &dsdvt;
2718 (*idrv)->ref = 1;
2720 (*idrv)->wDevID = wDevID;
2721 (*idrv)->primary = NULL;
2722 return MMSYSERR_NOERROR;
2725 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2727 memcpy(desc, &(WOutDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
2728 return MMSYSERR_NOERROR;
2731 /*======================================================================*
2732 * Low level WAVE IN implementation *
2733 *======================================================================*/
2735 /**************************************************************************
2736 * widNotifyClient [internal]
2738 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
2740 TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
2742 switch (wMsg) {
2743 case WIM_OPEN:
2744 case WIM_CLOSE:
2745 case WIM_DATA:
2746 if (wwi->wFlags != DCB_NULL &&
2747 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags, (HDRVR)wwi->waveDesc.hWave,
2748 wMsg, wwi->waveDesc.dwInstance, dwParam1, dwParam2)) {
2749 WARN("can't notify client !\n");
2750 return MMSYSERR_ERROR;
2752 break;
2753 default:
2754 FIXME("Unknown callback message %u\n", wMsg);
2755 return MMSYSERR_INVALPARAM;
2757 return MMSYSERR_NOERROR;
2760 /**************************************************************************
2761 * widGetDevCaps [internal]
2763 static DWORD widGetDevCaps(WORD wDevID, LPWAVEOUTCAPSA lpCaps, DWORD dwSize)
2765 TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
2767 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
2769 if (wDevID >= MAX_WAVEINDRV) {
2770 TRACE("MAX_WAVOUTDRV reached !\n");
2771 return MMSYSERR_BADDEVICEID;
2774 memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
2775 return MMSYSERR_NOERROR;
2778 /**************************************************************************
2779 * widRecorder_ReadHeaders [internal]
2781 static void widRecorder_ReadHeaders(WINE_WAVEIN * wwi)
2783 enum win_wm_message tmp_msg;
2784 DWORD tmp_param;
2785 HANDLE tmp_ev;
2786 WAVEHDR* lpWaveHdr;
2788 while (ALSA_RetrieveRingMessage(&wwi->msgRing, &tmp_msg, &tmp_param, &tmp_ev)) {
2789 if (tmp_msg == WINE_WM_HEADER) {
2790 LPWAVEHDR* wh;
2791 lpWaveHdr = (LPWAVEHDR)tmp_param;
2792 lpWaveHdr->lpNext = 0;
2794 if (wwi->lpQueuePtr == 0)
2795 wwi->lpQueuePtr = lpWaveHdr;
2796 else {
2797 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2798 *wh = lpWaveHdr;
2800 } else {
2801 ERR("should only have headers left\n");
2806 /**************************************************************************
2807 * widRecorder [internal]
2809 static DWORD CALLBACK widRecorder(LPVOID pmt)
2811 WORD uDevID = (DWORD)pmt;
2812 WINE_WAVEIN* wwi = (WINE_WAVEIN*)&WInDev[uDevID];
2813 WAVEHDR* lpWaveHdr;
2814 DWORD dwSleepTime;
2815 DWORD bytesRead;
2816 LPVOID buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, wwi->dwPeriodSize);
2817 char *pOffset = buffer;
2818 enum win_wm_message msg;
2819 DWORD param;
2820 HANDLE ev;
2821 DWORD frames_per_period;
2823 wwi->state = WINE_WS_STOPPED;
2824 wwi->dwTotalRecorded = 0;
2825 wwi->lpQueuePtr = NULL;
2827 SetEvent(wwi->hStartUpEvent);
2829 /* make sleep time to be # of ms to output a period */
2830 dwSleepTime = (1024/*wwi-dwPeriodSize => overrun!*/ * 1000) / wwi->format.Format.nAvgBytesPerSec;
2831 frames_per_period = snd_pcm_bytes_to_frames(wwi->p_handle, wwi->dwPeriodSize);
2832 TRACE("sleeptime=%ld ms\n", dwSleepTime);
2834 for (;;) {
2835 /* wait for dwSleepTime or an event in thread's queue */
2836 /* FIXME: could improve wait time depending on queue state,
2837 * ie, number of queued fragments
2839 if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
2841 int periods;
2842 DWORD frames;
2843 DWORD bytes;
2844 DWORD read;
2846 lpWaveHdr = wwi->lpQueuePtr;
2847 /* read all the fragments accumulated so far */
2848 frames = snd_pcm_avail_update(wwi->p_handle);
2849 bytes = snd_pcm_frames_to_bytes(wwi->p_handle, frames);
2850 TRACE("frames = %ld bytes = %ld\n", frames, bytes);
2851 periods = bytes / wwi->dwPeriodSize;
2852 while ((periods > 0) && (wwi->lpQueuePtr))
2854 periods--;
2855 bytes = wwi->dwPeriodSize;
2856 TRACE("bytes = %ld\n",bytes);
2857 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwPeriodSize)
2859 /* directly read fragment in wavehdr */
2860 read = wwi->read(wwi->p_handle, lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded, frames_per_period);
2861 bytesRead = snd_pcm_frames_to_bytes(wwi->p_handle, read);
2863 TRACE("bytesRead=%ld (direct)\n", bytesRead);
2864 if (bytesRead != (DWORD) -1)
2866 /* update number of bytes recorded in current buffer and by this device */
2867 lpWaveHdr->dwBytesRecorded += bytesRead;
2868 wwi->dwTotalRecorded += bytesRead;
2870 /* buffer is full. notify client */
2871 if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2873 /* must copy the value of next waveHdr, because we have no idea of what
2874 * will be done with the content of lpWaveHdr in callback
2876 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
2878 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2879 lpWaveHdr->dwFlags |= WHDR_DONE;
2881 wwi->lpQueuePtr = lpNext;
2882 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2883 lpWaveHdr = lpNext;
2885 } else {
2886 TRACE("read(%s, %p, %ld) failed (%s)\n", wwi->device,
2887 lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2888 frames_per_period, strerror(errno));
2891 else
2893 /* read the fragment in a local buffer */
2894 read = wwi->read(wwi->p_handle, buffer, frames_per_period);
2895 bytesRead = snd_pcm_frames_to_bytes(wwi->p_handle, read);
2896 pOffset = buffer;
2898 TRACE("bytesRead=%ld (local)\n", bytesRead);
2900 if (bytesRead == (DWORD) -1) {
2901 TRACE("read(%s, %p, %ld) failed (%s)\n", wwi->device,
2902 buffer, frames_per_period, strerror(errno));
2903 continue;
2906 /* copy data in client buffers */
2907 while (bytesRead != (DWORD) -1 && bytesRead > 0)
2909 DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
2911 memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2912 pOffset,
2913 dwToCopy);
2915 /* update number of bytes recorded in current buffer and by this device */
2916 lpWaveHdr->dwBytesRecorded += dwToCopy;
2917 wwi->dwTotalRecorded += dwToCopy;
2918 bytesRead -= dwToCopy;
2919 pOffset += dwToCopy;
2921 /* client buffer is full. notify client */
2922 if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2924 /* must copy the value of next waveHdr, because we have no idea of what
2925 * will be done with the content of lpWaveHdr in callback
2927 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
2928 TRACE("lpNext=%p\n", lpNext);
2930 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2931 lpWaveHdr->dwFlags |= WHDR_DONE;
2933 wwi->lpQueuePtr = lpNext;
2934 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2936 lpWaveHdr = lpNext;
2937 if (!lpNext && bytesRead) {
2938 /* before we give up, check for more header messages */
2939 while (ALSA_PeekRingMessage(&wwi->msgRing, &msg, &param, &ev))
2941 if (msg == WINE_WM_HEADER) {
2942 LPWAVEHDR hdr;
2943 ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev);
2944 hdr = ((LPWAVEHDR)param);
2945 TRACE("msg = %s, hdr = %p, ev = %p\n", getCmdString(msg), hdr, ev);
2946 hdr->lpNext = 0;
2947 if (lpWaveHdr == 0) {
2948 /* new head of queue */
2949 wwi->lpQueuePtr = lpWaveHdr = hdr;
2950 } else {
2951 /* insert buffer at the end of queue */
2952 LPWAVEHDR* wh;
2953 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2954 *wh = hdr;
2956 } else
2957 break;
2960 if (lpWaveHdr == 0) {
2961 /* no more buffer to copy data to, but we did read more.
2962 * what hasn't been copied will be dropped
2964 WARN("buffer under run! %lu bytes dropped.\n", bytesRead);
2965 wwi->lpQueuePtr = NULL;
2966 break;
2975 WAIT_OMR(&wwi->msgRing, dwSleepTime);
2977 while (ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev))
2979 TRACE("msg=%s param=0x%lx\n", getCmdString(msg), param);
2980 switch (msg) {
2981 case WINE_WM_PAUSING:
2982 wwi->state = WINE_WS_PAUSED;
2983 /*FIXME("Device should stop recording\n");*/
2984 SetEvent(ev);
2985 break;
2986 case WINE_WM_STARTING:
2987 wwi->state = WINE_WS_PLAYING;
2988 snd_pcm_start(wwi->p_handle);
2989 SetEvent(ev);
2990 break;
2991 case WINE_WM_HEADER:
2992 lpWaveHdr = (LPWAVEHDR)param;
2993 lpWaveHdr->lpNext = 0;
2995 /* insert buffer at the end of queue */
2997 LPWAVEHDR* wh;
2998 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2999 *wh = lpWaveHdr;
3001 break;
3002 case WINE_WM_STOPPING:
3003 if (wwi->state != WINE_WS_STOPPED)
3005 snd_pcm_drain(wwi->p_handle);
3007 /* read any headers in queue */
3008 widRecorder_ReadHeaders(wwi);
3010 /* return current buffer to app */
3011 lpWaveHdr = wwi->lpQueuePtr;
3012 if (lpWaveHdr)
3014 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
3015 TRACE("stop %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
3016 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
3017 lpWaveHdr->dwFlags |= WHDR_DONE;
3018 wwi->lpQueuePtr = lpNext;
3019 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
3022 wwi->state = WINE_WS_STOPPED;
3023 SetEvent(ev);
3024 break;
3025 case WINE_WM_RESETTING:
3026 if (wwi->state != WINE_WS_STOPPED)
3028 snd_pcm_drain(wwi->p_handle);
3030 wwi->state = WINE_WS_STOPPED;
3031 wwi->dwTotalRecorded = 0;
3033 /* read any headers in queue */
3034 widRecorder_ReadHeaders(wwi);
3036 /* return all buffers to the app */
3037 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
3038 TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
3039 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
3040 lpWaveHdr->dwFlags |= WHDR_DONE;
3041 wwi->lpQueuePtr = lpWaveHdr->lpNext;
3042 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
3045 wwi->lpQueuePtr = NULL;
3046 SetEvent(ev);
3047 break;
3048 case WINE_WM_CLOSING:
3049 wwi->hThread = 0;
3050 wwi->state = WINE_WS_CLOSED;
3051 SetEvent(ev);
3052 HeapFree(GetProcessHeap(), 0, buffer);
3053 ExitThread(0);
3054 /* shouldn't go here */
3055 case WINE_WM_UPDATE:
3056 SetEvent(ev);
3057 break;
3059 default:
3060 FIXME("unknown message %d\n", msg);
3061 break;
3065 ExitThread(0);
3066 /* just for not generating compilation warnings... should never be executed */
3067 return 0;
3070 /**************************************************************************
3071 * widOpen [internal]
3073 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
3075 WINE_WAVEIN* wwi;
3076 snd_pcm_hw_params_t * hw_params;
3077 snd_pcm_sw_params_t * sw_params;
3078 snd_pcm_access_t access;
3079 snd_pcm_format_t format;
3080 unsigned int rate;
3081 unsigned int buffer_time = 500000;
3082 unsigned int period_time = 10000;
3083 snd_pcm_uframes_t buffer_size;
3084 snd_pcm_uframes_t period_size;
3085 int flags;
3086 snd_pcm_t * pcm;
3087 int err;
3088 int dir;
3090 snd_pcm_hw_params_alloca(&hw_params);
3091 snd_pcm_sw_params_alloca(&sw_params);
3093 TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
3094 if (lpDesc == NULL) {
3095 WARN("Invalid Parameter !\n");
3096 return MMSYSERR_INVALPARAM;
3098 if (wDevID >= MAX_WAVEOUTDRV) {
3099 TRACE("MAX_WAVOUTDRV reached !\n");
3100 return MMSYSERR_BADDEVICEID;
3103 /* only PCM format is supported so far... */
3104 if (!supportedFormat(lpDesc->lpFormat)) {
3105 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
3106 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
3107 lpDesc->lpFormat->nSamplesPerSec);
3108 return WAVERR_BADFORMAT;
3111 if (dwFlags & WAVE_FORMAT_QUERY) {
3112 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
3113 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
3114 lpDesc->lpFormat->nSamplesPerSec);
3115 return MMSYSERR_NOERROR;
3118 wwi = &WInDev[wDevID];
3120 if ((dwFlags & WAVE_DIRECTSOUND) && !(wwi->caps.dwSupport & WAVECAPS_DIRECTSOUND))
3121 /* not supported, ignore it */
3122 dwFlags &= ~WAVE_DIRECTSOUND;
3124 wwi->p_handle = 0;
3125 flags = SND_PCM_NONBLOCK;
3126 if ( dwFlags & WAVE_DIRECTSOUND )
3127 flags |= SND_PCM_ASYNC;
3129 if ( (err=snd_pcm_open(&pcm, wwi->device, SND_PCM_STREAM_CAPTURE, dwFlags)) < 0 )
3131 ERR("Error open: %s\n", snd_strerror(err));
3132 return MMSYSERR_NOTENABLED;
3135 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
3137 memcpy(&wwi->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
3138 copy_format(lpDesc->lpFormat, &wwi->format);
3140 if (wwi->format.Format.wBitsPerSample == 0) {
3141 WARN("Resetting zeroed wBitsPerSample\n");
3142 wwi->format.Format.wBitsPerSample = 8 *
3143 (wwi->format.Format.nAvgBytesPerSec /
3144 wwi->format.Format.nSamplesPerSec) /
3145 wwi->format.Format.nChannels;
3148 snd_pcm_hw_params_any(pcm, hw_params);
3150 #define EXIT_ON_ERROR(f,e,txt) do \
3152 int err; \
3153 if ( (err = (f) ) < 0) \
3155 ERR(txt ": %s\n", snd_strerror(err)); \
3156 snd_pcm_close(pcm); \
3157 return e; \
3159 } while(0)
3161 access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
3162 if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
3163 WARN("mmap not available. switching to standard write.\n");
3164 access = SND_PCM_ACCESS_RW_INTERLEAVED;
3165 EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
3166 wwi->read = snd_pcm_readi;
3168 else
3169 wwi->read = snd_pcm_mmap_readi;
3171 EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwi->format.Format.nChannels), MMSYSERR_INVALPARAM, "unable to set required channels");
3173 if ((wwi->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
3174 ((wwi->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
3175 IsEqualGUID(&wwi->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
3176 format = (wwi->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
3177 (wwi->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
3178 (wwi->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
3179 (wwi->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
3180 } else if ((wwi->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
3181 IsEqualGUID(&wwi->format.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)){
3182 format = (wwi->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_FLOAT_LE : -1;
3183 } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
3184 FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
3185 snd_pcm_close(pcm);
3186 return WAVERR_BADFORMAT;
3187 } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
3188 FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
3189 snd_pcm_close(pcm);
3190 return WAVERR_BADFORMAT;
3191 } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
3192 FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
3193 snd_pcm_close(pcm);
3194 return WAVERR_BADFORMAT;
3195 } else {
3196 ERR("invalid format: %0x04x\n", wwi->format.Format.wFormatTag);
3197 snd_pcm_close(pcm);
3198 return WAVERR_BADFORMAT;
3201 EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), MMSYSERR_INVALPARAM, "unable to set required format");
3203 rate = wwi->format.Format.nSamplesPerSec;
3204 dir = 0;
3205 err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
3206 if (err < 0) {
3207 ERR("Rate %ld Hz not available for playback: %s\n", wwi->format.Format.nSamplesPerSec, snd_strerror(rate));
3208 snd_pcm_close(pcm);
3209 return WAVERR_BADFORMAT;
3211 if (rate != wwi->format.Format.nSamplesPerSec) {
3212 ERR("Rate doesn't match (requested %ld Hz, got %d Hz)\n", wwi->format.Format.nSamplesPerSec, rate);
3213 snd_pcm_close(pcm);
3214 return WAVERR_BADFORMAT;
3217 dir=0;
3218 EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
3219 dir=0;
3220 EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
3222 EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
3224 dir=0;
3225 err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
3226 err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
3228 snd_pcm_sw_params_current(pcm, sw_params);
3229 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");
3230 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
3231 EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
3232 EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
3233 EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
3234 EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
3235 #undef EXIT_ON_ERROR
3237 snd_pcm_prepare(pcm);
3239 if (TRACE_ON(wave))
3240 ALSA_TraceParameters(hw_params, sw_params, FALSE);
3242 /* now, we can save all required data for later use... */
3243 if ( wwi->hw_params )
3244 snd_pcm_hw_params_free(wwi->hw_params);
3245 snd_pcm_hw_params_malloc(&(wwi->hw_params));
3246 snd_pcm_hw_params_copy(wwi->hw_params, hw_params);
3248 wwi->dwBufferSize = buffer_size;
3249 wwi->lpQueuePtr = wwi->lpPlayPtr = wwi->lpLoopPtr = NULL;
3250 wwi->p_handle = pcm;
3252 ALSA_InitRingMessage(&wwi->msgRing);
3254 wwi->count = snd_pcm_poll_descriptors_count (wwi->p_handle);
3255 if (wwi->count <= 0) {
3256 ERR("Invalid poll descriptors count\n");
3257 return MMSYSERR_ERROR;
3260 wwi->ufds = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct pollfd) * wwi->count);
3261 if (wwi->ufds == NULL) {
3262 ERR("No enough memory\n");
3263 return MMSYSERR_NOMEM;
3265 if ((err = snd_pcm_poll_descriptors(wwi->p_handle, wwi->ufds, wwi->count)) < 0) {
3266 ERR("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
3267 return MMSYSERR_ERROR;
3270 wwi->dwPeriodSize = period_size;
3271 /*if (wwi->dwFragmentSize % wwi->format.Format.nBlockAlign)
3272 ERR("Fragment doesn't contain an integral number of data blocks\n");
3274 TRACE("dwPeriodSize=%lu\n", wwi->dwPeriodSize);
3275 TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
3276 wwi->format.Format.wBitsPerSample, wwi->format.Format.nAvgBytesPerSec,
3277 wwi->format.Format.nSamplesPerSec, wwi->format.Format.nChannels,
3278 wwi->format.Format.nBlockAlign);
3280 if (!(dwFlags & WAVE_DIRECTSOUND)) {
3281 wwi->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
3282 wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
3283 WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
3284 CloseHandle(wwi->hStartUpEvent);
3285 } else {
3286 wwi->hThread = INVALID_HANDLE_VALUE;
3287 wwi->dwThreadID = 0;
3289 wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
3291 return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
3295 /**************************************************************************
3296 * widClose [internal]
3298 static DWORD widClose(WORD wDevID)
3300 DWORD ret = MMSYSERR_NOERROR;
3301 WINE_WAVEIN* wwi;
3303 TRACE("(%u);\n", wDevID);
3305 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3306 WARN("bad device ID !\n");
3307 return MMSYSERR_BADDEVICEID;
3310 wwi = &WInDev[wDevID];
3311 if (wwi->lpQueuePtr) {
3312 WARN("buffers still playing !\n");
3313 ret = WAVERR_STILLPLAYING;
3314 } else {
3315 if (wwi->hThread != INVALID_HANDLE_VALUE) {
3316 ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
3318 ALSA_DestroyRingMessage(&wwi->msgRing);
3320 snd_pcm_hw_params_free(wwi->hw_params);
3321 wwi->hw_params = NULL;
3323 snd_pcm_close(wwi->p_handle);
3324 wwi->p_handle = NULL;
3326 ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
3329 HeapFree(GetProcessHeap(), 0, wwi->ufds);
3330 return ret;
3333 /**************************************************************************
3334 * widAddBuffer [internal]
3337 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3339 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3341 /* first, do the sanity checks... */
3342 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3343 WARN("bad dev ID !\n");
3344 return MMSYSERR_BADDEVICEID;
3347 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
3348 return WAVERR_UNPREPARED;
3350 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3351 return WAVERR_STILLPLAYING;
3353 lpWaveHdr->dwFlags &= ~WHDR_DONE;
3354 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
3355 lpWaveHdr->lpNext = 0;
3357 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
3359 return MMSYSERR_NOERROR;
3362 /**************************************************************************
3363 * widPrepare [internal]
3365 static DWORD widPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3367 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3369 if (wDevID >= MAX_WAVEINDRV) {
3370 WARN("bad device ID !\n");
3371 return MMSYSERR_BADDEVICEID;
3374 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3375 return WAVERR_STILLPLAYING;
3377 lpWaveHdr->dwFlags |= WHDR_PREPARED;
3378 lpWaveHdr->dwFlags &= ~WHDR_DONE;
3379 return MMSYSERR_NOERROR;
3382 /**************************************************************************
3383 * widUnprepare [internal]
3385 static DWORD widUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3387 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3389 if (wDevID >= MAX_WAVEINDRV) {
3390 WARN("bad device ID !\n");
3391 return MMSYSERR_BADDEVICEID;
3394 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
3395 return WAVERR_STILLPLAYING;
3397 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
3398 lpWaveHdr->dwFlags |= WHDR_DONE;
3400 return MMSYSERR_NOERROR;
3403 /**************************************************************************
3404 * widStart [internal]
3407 static DWORD widStart(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3409 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3411 /* first, do the sanity checks... */
3412 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3413 WARN("bad dev ID !\n");
3414 return MMSYSERR_BADDEVICEID;
3417 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
3419 Sleep(500);
3421 return MMSYSERR_NOERROR;
3424 /**************************************************************************
3425 * widStop [internal]
3428 static DWORD widStop(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
3430 TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
3432 /* first, do the sanity checks... */
3433 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].p_handle == NULL) {
3434 WARN("bad dev ID !\n");
3435 return MMSYSERR_BADDEVICEID;
3438 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
3440 return MMSYSERR_NOERROR;
3443 /**************************************************************************
3444 * widReset [internal]
3446 static DWORD widReset(WORD wDevID)
3448 TRACE("(%u);\n", wDevID);
3449 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
3450 WARN("can't reset !\n");
3451 return MMSYSERR_INVALHANDLE;
3453 ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
3454 return MMSYSERR_NOERROR;
3457 /**************************************************************************
3458 * widGetPosition [internal]
3460 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
3462 WINE_WAVEIN* wwi;
3464 TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
3466 if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
3467 WARN("can't get pos !\n");
3468 return MMSYSERR_INVALHANDLE;
3471 if (lpTime == NULL) {
3472 WARN("invalid parameter: lpTime = NULL\n");
3473 return MMSYSERR_INVALPARAM;
3476 wwi = &WInDev[wDevID];
3477 ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_UPDATE, 0, TRUE);
3479 return bytes_to_mmtime(lpTime, wwi->dwTotalRecorded, &wwi->format);
3482 /**************************************************************************
3483 * widGetNumDevs [internal]
3485 static DWORD widGetNumDevs(void)
3487 return ALSA_WidNumDevs;
3490 /**************************************************************************
3491 * widDevInterfaceSize [internal]
3493 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
3495 TRACE("(%u, %p)\n", wDevID, dwParam1);
3497 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3498 NULL, 0 ) * sizeof(WCHAR);
3499 return MMSYSERR_NOERROR;
3502 /**************************************************************************
3503 * widDevInterface [internal]
3505 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
3507 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3508 NULL, 0 ) * sizeof(WCHAR))
3510 MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
3511 dwParam1, dwParam2 / sizeof(WCHAR));
3512 return MMSYSERR_NOERROR;
3514 return MMSYSERR_INVALPARAM;
3517 /**************************************************************************
3518 * widDsCreate [internal]
3520 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
3522 TRACE("(%d,%p)\n",wDevID,drv);
3524 /* the HAL isn't much better than the HEL if we can't do mmap() */
3525 FIXME("DirectSoundCapture not implemented\n");
3526 MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
3527 return MMSYSERR_NOTSUPPORTED;
3530 /**************************************************************************
3531 * widDsDesc [internal]
3533 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
3535 memcpy(desc, &(WInDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
3536 return MMSYSERR_NOERROR;
3539 /**************************************************************************
3540 * widMessage (WINEALSA.@)
3542 DWORD WINAPI ALSA_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
3543 DWORD dwParam1, DWORD dwParam2)
3545 TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
3546 wDevID, wMsg, dwUser, dwParam1, dwParam2);
3548 switch (wMsg) {
3549 case DRVM_INIT:
3550 case DRVM_EXIT:
3551 case DRVM_ENABLE:
3552 case DRVM_DISABLE:
3553 /* FIXME: Pretend this is supported */
3554 return 0;
3555 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
3556 case WIDM_CLOSE: return widClose (wDevID);
3557 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3558 case WIDM_PREPARE: return widPrepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3559 case WIDM_UNPREPARE: return widUnprepare (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3560 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEOUTCAPSA)dwParam1, dwParam2);
3561 case WIDM_GETNUMDEVS: return widGetNumDevs ();
3562 case WIDM_GETPOS: return widGetPosition (wDevID, (LPMMTIME)dwParam1, dwParam2);
3563 case WIDM_RESET: return widReset (wDevID);
3564 case WIDM_START: return widStart (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3565 case WIDM_STOP: return widStop (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3566 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
3567 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
3568 case DRV_QUERYDSOUNDIFACE: return widDsCreate (wDevID, (PIDSCDRIVER*)dwParam1);
3569 case DRV_QUERYDSOUNDDESC: return widDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
3570 default:
3571 FIXME("unknown message %d!\n", wMsg);
3573 return MMSYSERR_NOTSUPPORTED;
3576 #endif
3578 #if !(defined(HAVE_ALSA) && ((SND_LIB_MAJOR == 0 && SND_LIB_MINOR >= 9) || SND_LIB_MAJOR >= 1))
3580 /**************************************************************************
3581 * widMessage (WINEALSA.@)
3583 DWORD WINAPI ALSA_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3584 DWORD dwParam1, DWORD dwParam2)
3586 FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3587 return MMSYSERR_NOTENABLED;
3590 #endif
3592 #ifndef HAVE_ALSA
3594 /**************************************************************************
3595 * wodMessage (WINEALSA.@)
3597 DWORD WINAPI ALSA_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
3598 DWORD dwParam1, DWORD dwParam2)
3600 FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3601 return MMSYSERR_NOTENABLED;
3604 #endif /* HAVE_ALSA */