winealsa: Minor fixes to ds output.
[wine] / dlls / winealsa.drv / dsoutput.c
1 /*
2  * Sample Wine Driver for Advanced Linux Sound System (ALSA)
3  *      Based on version <final> of the ALSA API
4  *
5  * Copyright    2002 Eric Pouech
6  *              2002 Marco Pietrobono
7  *              2003 Christian Costa : WaveIn support
8  *              2006-2007 Maarten Lankhorst
9  *
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.
14  *
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.
19  *
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 /*======================================================================*
26  *              Low level dsound output implementation                  *
27  *======================================================================*/
28
29 #include "config.h"
30 #include "wine/port.h"
31
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <string.h>
36 #ifdef HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
39 #include <errno.h>
40 #include <limits.h>
41 #include <fcntl.h>
42 #ifdef HAVE_SYS_IOCTL_H
43 # include <sys/ioctl.h>
44 #endif
45 #ifdef HAVE_SYS_MMAN_H
46 # include <sys/mman.h>
47 #endif
48 #include "windef.h"
49 #include "winbase.h"
50 #include "wingdi.h"
51 #include "winerror.h"
52 #include "winuser.h"
53 #include "mmddk.h"
54
55 #include "alsa.h"
56 #include "wine/library.h"
57 #include "wine/unicode.h"
58 #include "wine/debug.h"
59
60 #ifdef HAVE_ALSA
61
62 WINE_DEFAULT_DEBUG_CHANNEL(dsalsa);
63
64 typedef struct IDsDriverImpl IDsDriverImpl;
65 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
66
67 struct IDsDriverImpl
68 {
69     /* IUnknown fields */
70     const IDsDriverVtbl *lpVtbl;
71     LONG ref;
72
73     /* IDsDriverImpl fields */
74     IDsDriverBufferImpl* primary;
75     UINT wDevID;
76 };
77
78 struct IDsDriverBufferImpl
79 {
80     const IDsDriverBufferVtbl *lpVtbl;
81     LONG ref;
82     IDsDriverImpl* drv;
83
84     CRITICAL_SECTION pcm_crst;
85     LPVOID mmap_buffer;
86     DWORD mmap_buflen_bytes;
87
88     snd_pcm_t *pcm;
89     snd_pcm_hw_params_t *hw_params;
90     snd_pcm_sw_params_t *sw_params;
91     snd_pcm_uframes_t mmap_buflen_frames, mmap_pos, mmap_commitahead, mmap_writeahead;
92 };
93
94 /** Fill buffers, for starting and stopping
95  * Alsa won't start playing until everything is filled up
96  * This also updates mmap_pos
97  *
98  * Returns: Amount of periods in use so snd_pcm_avail_update
99  * doesn't have to be called up to 4x in GetPosition()
100  */
101 static snd_pcm_uframes_t CommitAll(IDsDriverBufferImpl *This)
102 {
103     const snd_pcm_channel_area_t *areas;
104     snd_pcm_uframes_t used;
105     const snd_pcm_uframes_t commitahead = This->mmap_commitahead;
106
107     used = This->mmap_buflen_frames - snd_pcm_avail_update(This->pcm);
108     TRACE("%p needs to commit to %lu, used: %lu\n", This, commitahead, used);
109     if (used < commitahead)
110     {
111         snd_pcm_uframes_t done, putin = commitahead - used;
112         snd_pcm_mmap_begin(This->pcm, &areas, &This->mmap_pos, &putin);
113         done = snd_pcm_mmap_commit(This->pcm, This->mmap_pos, putin);
114         This->mmap_pos += done;
115         used += done;
116         putin = commitahead - used;
117
118         if (This->mmap_pos == This->mmap_buflen_frames && (snd_pcm_sframes_t)putin > 0)
119         {
120             snd_pcm_mmap_begin(This->pcm, &areas, &This->mmap_pos, &putin);
121             done = snd_pcm_mmap_commit(This->pcm, This->mmap_pos, putin);
122             This->mmap_pos += done;
123             used += done;
124         }
125     }
126
127     if (This->mmap_pos == This->mmap_buflen_frames)
128         This->mmap_pos = 0;
129
130     return used;
131 }
132
133 static void CheckXRUN(IDsDriverBufferImpl* This)
134 {
135     snd_pcm_state_t state = snd_pcm_state(This->pcm);
136     snd_pcm_sframes_t delay;
137     int err;
138
139     snd_pcm_hwsync(This->pcm);
140     snd_pcm_delay(This->pcm, &delay);
141     if ( state == SND_PCM_STATE_XRUN )
142     {
143         err = snd_pcm_prepare(This->pcm);
144         CommitAll(This);
145         snd_pcm_start(This->pcm);
146         WARN("xrun occurred\n");
147         if ( err < 0 )
148             ERR("recovery from xrun failed, prepare failed: %s\n", snd_strerror(err));
149     }
150     else if ( state == SND_PCM_STATE_SUSPENDED )
151     {
152         int err = snd_pcm_resume(This->pcm);
153         TRACE("recovery from suspension occurred\n");
154         if (err < 0 && err != -EAGAIN){
155             err = snd_pcm_prepare(This->pcm);
156             if (err < 0)
157                 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
158         }
159     } else if ( state != SND_PCM_STATE_RUNNING ) {
160         FIXME("Unhandled state: %d\n", state);
161     }
162 }
163
164 /**
165  * Allocate the memory-mapped buffer for direct sound, and set up the
166  * callback.
167  */
168 static int DSDB_CreateMMAP(IDsDriverBufferImpl* pdbi)
169 {
170     snd_pcm_t *pcm = pdbi->pcm;
171     snd_pcm_format_t format;
172     snd_pcm_uframes_t frames, ofs, avail, psize, boundary;
173     unsigned int channels, bits_per_sample, bits_per_frame;
174     int err, mmap_mode;
175     const snd_pcm_channel_area_t *areas;
176     snd_pcm_hw_params_t *hw_params = pdbi->hw_params;
177     snd_pcm_sw_params_t *sw_params = pdbi->sw_params;
178
179     mmap_mode = snd_pcm_type(pcm);
180
181     if (mmap_mode == SND_PCM_TYPE_HW)
182         TRACE("mmap'd buffer is a direct hardware buffer.\n");
183     else if (mmap_mode == SND_PCM_TYPE_DMIX)
184         TRACE("mmap'd buffer is an ALSA dmix buffer\n");
185     else
186         TRACE("mmap'd buffer is an ALSA type %d buffer\n", mmap_mode);
187
188     err = snd_pcm_hw_params_get_period_size(hw_params, &psize, NULL);
189
190     err = snd_pcm_hw_params_get_format(hw_params, &format);
191     err = snd_pcm_hw_params_get_buffer_size(hw_params, &frames);
192     err = snd_pcm_hw_params_get_channels(hw_params, &channels);
193     bits_per_sample = snd_pcm_format_physical_width(format);
194     bits_per_frame = bits_per_sample * channels;
195
196     if (TRACE_ON(dsalsa))
197         ALSA_TraceParameters(hw_params, NULL, FALSE);
198
199     TRACE("format=%s  frames=%ld  channels=%d  bits_per_sample=%d  bits_per_frame=%d\n",
200           snd_pcm_format_name(format), frames, channels, bits_per_sample, bits_per_frame);
201
202     pdbi->mmap_buflen_frames = frames;
203     pdbi->mmap_buflen_bytes = snd_pcm_frames_to_bytes( pcm, frames );
204
205     snd_pcm_sw_params_current(pcm, sw_params);
206     snd_pcm_sw_params_set_start_threshold(pcm, sw_params, 0);
207     snd_pcm_sw_params_get_boundary(sw_params, &boundary);
208     snd_pcm_sw_params_set_stop_threshold(pcm, sw_params, boundary);
209     snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, INT_MAX);
210     snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0);
211     snd_pcm_sw_params_set_avail_min(pcm, sw_params, 0);
212     snd_pcm_sw_params_set_xrun_mode(pcm, sw_params, SND_PCM_XRUN_NONE);
213     err = snd_pcm_sw_params(pcm, sw_params);
214
215     avail = snd_pcm_avail_update(pcm);
216     if (avail < 0)
217     {
218         ERR("No buffer is available: %s.\n", snd_strerror(avail));
219         return DSERR_GENERIC;
220     }
221     err = snd_pcm_mmap_begin(pcm, &areas, &ofs, &avail);
222     if ( err < 0 )
223     {
224         ERR("Can't map sound device for direct access: %s\n", snd_strerror(err));
225         return DSERR_GENERIC;
226     }
227     snd_pcm_format_set_silence(format, areas->addr, pdbi->mmap_buflen_frames);
228     err = snd_pcm_mmap_commit(pcm, ofs, avail);
229     pdbi->mmap_buffer = areas->addr;
230
231     TRACE("created mmap buffer of %ld frames (%d bytes) at %p\n",
232         frames, pdbi->mmap_buflen_bytes, pdbi->mmap_buffer);
233
234     return DS_OK;
235 }
236
237 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
238 {
239     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
240     FIXME("(): stub!\n");
241     return DSERR_UNSUPPORTED;
242 }
243
244 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
245 {
246     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
247     ULONG refCount = InterlockedIncrement(&This->ref);
248
249     TRACE("(%p)->(ref before=%u)\n",This, refCount - 1);
250
251     return refCount;
252 }
253
254 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
255 {
256     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
257     ULONG refCount = InterlockedDecrement(&This->ref);
258
259     TRACE("(%p)->(ref before=%u)\n",This, refCount + 1);
260
261     if (refCount)
262         return refCount;
263
264     TRACE("mmap buffer %p destroyed\n", This->mmap_buffer);
265
266     if (This == This->drv->primary)
267         This->drv->primary = NULL;
268
269     This->pcm_crst.DebugInfo->Spare[0] = 0;
270     DeleteCriticalSection(&This->pcm_crst);
271
272     snd_pcm_drop(This->pcm);
273     snd_pcm_close(This->pcm);
274     This->pcm = NULL;
275     HeapFree(GetProcessHeap(), 0, This->sw_params);
276     HeapFree(GetProcessHeap(), 0, This->hw_params);
277     HeapFree(GetProcessHeap(), 0, This);
278     return 0;
279 }
280
281 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
282                                                LPVOID*ppvAudio1,LPDWORD pdwLen1,
283                                                LPVOID*ppvAudio2,LPDWORD pdwLen2,
284                                                DWORD dwWritePosition,DWORD dwWriteLen,
285                                                DWORD dwFlags)
286 {
287     FIXME("(%p) stub\n", iface);
288     return DSERR_UNSUPPORTED;
289 }
290
291 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
292                                                  LPVOID pvAudio1,DWORD dwLen1,
293                                                  LPVOID pvAudio2,DWORD dwLen2)
294 {
295     FIXME("(%p) stub\n", iface);
296     return DSERR_UNSUPPORTED;
297 }
298
299 static int warnonce;
300
301 static HRESULT SetFormat(IDsDriverBufferImpl *This, LPWAVEFORMATEX pwfx, BOOL forced)
302 {
303     snd_pcm_t *pcm = NULL;
304     snd_pcm_hw_params_t *hw_params = This->hw_params;
305     unsigned int buffer_time = 500000;
306     snd_pcm_format_t format = -1;
307     snd_pcm_uframes_t psize;
308     DWORD rate = pwfx->nSamplesPerSec;
309     int err=0;
310
311     switch (pwfx->wBitsPerSample)
312     {
313         case  8: format = SND_PCM_FORMAT_U8; break;
314         case 16: format = SND_PCM_FORMAT_S16_LE; break;
315         case 24: format = SND_PCM_FORMAT_S24_LE; break;
316         case 32: format = SND_PCM_FORMAT_S32_LE; break;
317         default: FIXME("Unsupported bpp: %d\n", pwfx->wBitsPerSample); return DSERR_GENERIC;
318     }
319
320     /* **** */
321     EnterCriticalSection(&This->pcm_crst);
322
323     err = snd_pcm_open(&pcm, WOutDev[This->drv->wDevID].pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
324
325     if (err < 0)
326     {
327         if (errno != EBUSY || !This->pcm)
328         {
329             /* **** */
330             LeaveCriticalSection(&This->pcm_crst);
331             WARN("Cannot open sound device: %s\n", snd_strerror(err));
332             return DSERR_GENERIC;
333         }
334         snd_pcm_drop(This->pcm);
335         snd_pcm_close(This->pcm);
336         This->pcm = NULL;
337         err = snd_pcm_open(&pcm, WOutDev[This->drv->wDevID].pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
338         if (err < 0)
339         {
340             /* **** */
341             LeaveCriticalSection(&This->pcm_crst);
342             WARN("Cannot open sound device: %s\n", snd_strerror(err));
343             return DSERR_BUFFERLOST;
344         }
345     }
346
347     /* Set some defaults */
348     snd_pcm_hw_params_any(pcm, hw_params);
349     err = snd_pcm_hw_params_set_channels(pcm, hw_params, pwfx->nChannels);
350     if (err < 0) { WARN("Could not set channels to %d\n", pwfx->nChannels); goto err; }
351
352     err = snd_pcm_hw_params_set_format(pcm, hw_params, format);
353     if (err < 0) { WARN("Could not set format to %d bpp\n", pwfx->wBitsPerSample); goto err; }
354
355     /* Alsa's rate resampling is only used if the application specifically requests
356      * a buffer at a certain frequency, else it is better to disable it due to unwanted
357      * side effects, which may include: Less granular pointer, changing buffer sizes, etc
358      */
359 #if SND_LIB_VERSION >= 0x010009
360     snd_pcm_hw_params_set_rate_resample(pcm, hw_params, 0 && forced);
361 #endif
362
363     err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, NULL);
364     if (err < 0) { rate = pwfx->nSamplesPerSec; WARN("Could not set rate\n"); goto err; }
365
366     if (!ALSA_NearMatch(rate, pwfx->nSamplesPerSec))
367     {
368         WARN("Could not set sound rate to %d, but instead to %d\n", pwfx->nSamplesPerSec, rate);
369         pwfx->nSamplesPerSec = rate;
370         pwfx->nAvgBytesPerSec = rate * pwfx->nBlockAlign;
371         /* Let DirectSound detect this */
372     }
373
374     snd_pcm_hw_params_set_periods_integer(pcm, hw_params);
375     snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, NULL);
376     buffer_time = 10000;
377     snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &buffer_time, NULL);
378     err = snd_pcm_hw_params(pcm, hw_params);
379     err = snd_pcm_sw_params(pcm, This->sw_params);
380     snd_pcm_prepare(pcm);
381
382     err = snd_pcm_hw_params_get_period_size(hw_params, &psize, NULL);
383     TRACE("Period size is: %lu\n", psize);
384
385     /* If period size is 'high', try to commit less
386      * dmix needs at least 2 buffers to work successfully but prefers 3
387      * however it seems to work ok if I just commit 2 1/2 buffers
388      */
389     if (psize >= 512)
390     {
391         if (psize == 1024 && ++warnonce == 1)
392             FIXME("Your alsa dmix period size is 1024, try decreasing it to 512 if possible\n");
393         else if (psize > 512)
394             WARN("Your alsa period size is excessively high (%lu)\n", psize);
395         This->mmap_commitahead = 2 * psize + psize/2;
396         This->mmap_writeahead = 2 * psize;
397     }
398     else
399     {
400         This->mmap_commitahead = 3 * psize;
401         while (This->mmap_commitahead <= 512)
402             This->mmap_commitahead += psize;
403         This->mmap_writeahead = This->mmap_commitahead;
404     }
405
406     if (This->pcm)
407     {
408         snd_pcm_drop(This->pcm);
409         snd_pcm_close(This->pcm);
410     }
411     This->pcm = pcm;
412
413     snd_pcm_prepare(This->pcm);
414     DSDB_CreateMMAP(This);
415
416     /* **** */
417     LeaveCriticalSection(&This->pcm_crst);
418     return S_OK;
419
420     err:
421     if (err < 0)
422         WARN("Failed to apply changes: %s\n", snd_strerror(err));
423
424     if (!This->pcm)
425         This->pcm = pcm;
426     else
427         snd_pcm_close(pcm);
428
429     if (This->pcm)
430         snd_pcm_hw_params_current(This->pcm, This->hw_params);
431
432     /* **** */
433     LeaveCriticalSection(&This->pcm_crst);
434     return DSERR_BADFORMAT;
435 }
436
437 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface, LPWAVEFORMATEX pwfx)
438 {
439     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
440     HRESULT hr = S_OK;
441
442     TRACE("(%p, %p)\n", iface, pwfx);
443
444     hr = SetFormat(This, pwfx, TRUE);
445
446     if (hr == S_OK)
447         /* Buffer size / Location changed, so tell dsound to recreate */
448         return DSERR_BUFFERLOST;
449     return hr;
450 }
451
452 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
453 {
454     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
455     FIXME("(%p,%d): stub\n",iface,dwFreq);
456     return S_OK;
457 }
458
459 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
460 {
461     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
462     FIXME("(%p,%p): stub\n",This,pVolPan);
463     /* TODO: Bring volume control back */
464     return DS_OK;
465 }
466
467 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
468 {
469     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
470     /* I don't even think alsa allows this */
471     FIXME("(%p,%d): stub\n",iface,dwNewPos);
472     return DSERR_UNSUPPORTED;
473 }
474
475 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
476                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
477 {
478     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
479     snd_pcm_uframes_t hw_pptr=0, hw_wptr=0;
480     snd_pcm_state_t state;
481
482     EnterCriticalSection(&This->pcm_crst);
483
484     if (!This->pcm)
485     {
486         FIXME("Bad pointer for pcm: %p\n", This->pcm);
487         LeaveCriticalSection(&This->pcm_crst);
488         return DSERR_GENERIC;
489     }
490
491     state = snd_pcm_state(This->pcm);
492
493     if (state != SND_PCM_STATE_PREPARED && state != SND_PCM_STATE_RUNNING)
494     {
495         CheckXRUN(This);
496         state = snd_pcm_state(This->pcm);
497     }
498     if (state == SND_PCM_STATE_RUNNING)
499     {
500         snd_pcm_uframes_t used = CommitAll(This);
501
502         if (This->mmap_pos > used)
503             hw_pptr = This->mmap_pos - used;
504         else
505             hw_pptr = This->mmap_buflen_frames - used + This->mmap_pos;
506
507         hw_wptr = hw_pptr + (This->mmap_writeahead > used ? used : This->mmap_writeahead);
508         hw_wptr %= This->mmap_buflen_frames;
509         hw_pptr %= This->mmap_buflen_frames;
510
511         TRACE("At position: %ld (%ld) - Used %ld\n", hw_pptr, This->mmap_pos, used);
512     }
513
514     LeaveCriticalSection(&This->pcm_crst);
515
516     if (lpdwPlay)
517         *lpdwPlay = snd_pcm_frames_to_bytes(This->pcm, hw_pptr);
518     if (lpdwWrite)
519         *lpdwWrite = snd_pcm_frames_to_bytes(This->pcm, hw_wptr);
520
521     TRACE("hw_pptr=0x%08x, hw_wptr=0x%08x playpos=%d, writepos=%d\n", (unsigned int)hw_pptr, (unsigned int)hw_wptr, lpdwPlay?*lpdwPlay:-1, lpdwWrite?*lpdwWrite:-1);
522     return DS_OK;
523 }
524
525 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
526 {
527     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
528     TRACE("(%p,%x,%x,%x)\n",iface,dwRes1,dwRes2,dwFlags);
529
530     /* **** */
531     EnterCriticalSection(&This->pcm_crst);
532     snd_pcm_start(This->pcm);
533     CommitAll(This);
534     /* **** */
535     LeaveCriticalSection(&This->pcm_crst);
536     return DS_OK;
537 }
538
539 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
540 {
541     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
542     TRACE("(%p)\n",iface);
543
544     /* **** */
545     EnterCriticalSection(&This->pcm_crst);
546     snd_pcm_drop(This->pcm);
547     snd_pcm_prepare(This->pcm);
548     /* **** */
549     LeaveCriticalSection(&This->pcm_crst);
550     return DS_OK;
551 }
552
553 static const IDsDriverBufferVtbl dsdbvt =
554 {
555     IDsDriverBufferImpl_QueryInterface,
556     IDsDriverBufferImpl_AddRef,
557     IDsDriverBufferImpl_Release,
558     IDsDriverBufferImpl_Lock,
559     IDsDriverBufferImpl_Unlock,
560     IDsDriverBufferImpl_SetFormat,
561     IDsDriverBufferImpl_SetFrequency,
562     IDsDriverBufferImpl_SetVolumePan,
563     IDsDriverBufferImpl_SetPosition,
564     IDsDriverBufferImpl_GetPosition,
565     IDsDriverBufferImpl_Play,
566     IDsDriverBufferImpl_Stop
567 };
568
569 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
570 {
571     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
572     FIXME("(%p): stub!\n",iface);
573     return DSERR_UNSUPPORTED;
574 }
575
576 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
577 {
578     IDsDriverImpl *This = (IDsDriverImpl *)iface;
579     ULONG refCount = InterlockedIncrement(&This->ref);
580
581     TRACE("(%p)->(ref before=%u)\n",This, refCount - 1);
582
583     return refCount;
584 }
585
586 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
587 {
588     IDsDriverImpl *This = (IDsDriverImpl *)iface;
589     ULONG refCount = InterlockedDecrement(&This->ref);
590
591     TRACE("(%p)->(ref before=%u)\n",This, refCount + 1);
592
593     if (refCount)
594         return refCount;
595
596     HeapFree(GetProcessHeap(), 0, This);
597     return 0;
598 }
599
600 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
601 {
602     IDsDriverImpl *This = (IDsDriverImpl *)iface;
603     TRACE("(%p,%p)\n",iface,pDesc);
604     memcpy(pDesc, &(WOutDev[This->wDevID].ds_desc), sizeof(DSDRIVERDESC));
605     pDesc->dwFlags              = DSDDESC_DONTNEEDPRIMARYLOCK | DSDDESC_DONTNEEDSECONDARYLOCK | DSDDESC_DONTNEEDWRITELEAD;
606     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
607     pDesc->wVxdId               = 0;
608     pDesc->wReserved            = 0;
609     pDesc->ulDeviceNum          = This->wDevID;
610     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
611     pDesc->pvDirectDrawHeap     = NULL;
612     pDesc->dwMemStartAddress    = 0xDEAD0000;
613     pDesc->dwMemEndAddress      = 0xDEAF0000;
614     pDesc->dwMemAllocExtra      = 0;
615     pDesc->pvReserved1          = NULL;
616     pDesc->pvReserved2          = NULL;
617     return DS_OK;
618 }
619
620 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
621 {
622     HRESULT hr = S_OK;
623     IDsDriverImpl *This = (IDsDriverImpl *)iface;
624     int err=0;
625     snd_pcm_t *pcm = NULL;
626     snd_pcm_hw_params_t *hw_params;
627
628     /* While this is not really needed, it is a good idea to do this,
629      * to see if sound can be initialized */
630
631     hw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof());
632
633     if (!hw_params)
634     {
635         hr = DSERR_OUTOFMEMORY;
636         goto unalloc;
637     }
638
639     err = snd_pcm_open(&pcm, WOutDev[This->wDevID].pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
640     if (err < 0) goto err;
641     err = snd_pcm_hw_params_any(pcm, hw_params);
642     if (err < 0) goto err;
643     err = snd_pcm_hw_params_set_access (pcm, hw_params, SND_PCM_ACCESS_MMAP_INTERLEAVED);
644     if (err < 0) goto err;
645
646     TRACE("Success\n");
647     snd_pcm_close(pcm);
648     goto unalloc;
649
650     err:
651     hr = DSERR_GENERIC;
652     FIXME("Failed to open device: %s\n", snd_strerror(err));
653     if (pcm)
654         snd_pcm_close(pcm);
655     unalloc:
656     HeapFree(GetProcessHeap(), 0, hw_params);
657     if (hr != S_OK)
658         WARN("--> %08x\n", hr);
659     return hr;
660 }
661
662 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
663 {
664     IDsDriverImpl *This = (IDsDriverImpl *)iface;
665     TRACE("(%p) stub, harmless\n",This);
666     return DS_OK;
667 }
668
669 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
670 {
671     IDsDriverImpl *This = (IDsDriverImpl *)iface;
672     TRACE("(%p,%p)\n",iface,pCaps);
673     memcpy(pCaps, &(WOutDev[This->wDevID].ds_caps), sizeof(DSDRIVERCAPS));
674     return DS_OK;
675 }
676
677 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
678                                                       LPWAVEFORMATEX pwfx,
679                                                       DWORD dwFlags, DWORD dwCardAddress,
680                                                       LPDWORD pdwcbBufferSize,
681                                                       LPBYTE *ppbBuffer,
682                                                       LPVOID *ppvObj)
683 {
684     IDsDriverImpl *This = (IDsDriverImpl *)iface;
685     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
686     HRESULT err;
687
688     TRACE("(%p,%p,%x,%x)\n",iface,pwfx,dwFlags,dwCardAddress);
689     /* we only support primary buffers... for now */
690     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
691         return DSERR_UNSUPPORTED;
692     if (This->primary)
693         return DSERR_ALLOCATED;
694
695     *ippdsdb = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDsDriverBufferImpl));
696     if (*ippdsdb == NULL)
697         return DSERR_OUTOFMEMORY;
698
699     (*ippdsdb)->hw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof());
700     (*ippdsdb)->sw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_sw_params_sizeof());
701     if (!(*ippdsdb)->hw_params || !(*ippdsdb)->sw_params)
702     {
703         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->sw_params);
704         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->hw_params);
705         return DSERR_OUTOFMEMORY;
706     }
707     (*ippdsdb)->lpVtbl  = &dsdbvt;
708     (*ippdsdb)->ref     = 1;
709     (*ippdsdb)->drv     = This;
710     InitializeCriticalSection(&(*ippdsdb)->pcm_crst);
711     (*ippdsdb)->pcm_crst.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ALSA_DSOUTPUT.pcm_crst");
712
713     /* SetFormat has to re-initialize pcm here anyway */
714     err = SetFormat(*ippdsdb, pwfx, FALSE);
715     if (FAILED(err))
716     {
717         WARN("Error occurred: %08x\n", err);
718         goto err;
719     }
720
721     if (dwFlags & DSBCAPS_PRIMARYBUFFER)
722         This->primary = *ippdsdb;
723
724     *pdwcbBufferSize = (*ippdsdb)->mmap_buflen_bytes;
725     *ppbBuffer = (*ippdsdb)->mmap_buffer;
726
727     /* buffer is ready to go */
728     TRACE("buffer created at %p\n", *ippdsdb);
729     return err;
730
731     err:
732     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->sw_params);
733     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->hw_params);
734     HeapFree(GetProcessHeap(), 0, *ippdsdb);
735     *ippdsdb = NULL;
736     return err;
737 }
738
739 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
740                                                          PIDSDRIVERBUFFER pBuffer,
741                                                          LPVOID *ppvObj)
742 {
743     IDsDriverImpl *This = (IDsDriverImpl *)iface;
744     FIXME("(%p,%p): stub\n",This,pBuffer);
745     return DSERR_INVALIDCALL;
746 }
747
748 static const IDsDriverVtbl dsdvt =
749 {
750     IDsDriverImpl_QueryInterface,
751     IDsDriverImpl_AddRef,
752     IDsDriverImpl_Release,
753     IDsDriverImpl_GetDriverDesc,
754     IDsDriverImpl_Open,
755     IDsDriverImpl_Close,
756     IDsDriverImpl_GetCaps,
757     IDsDriverImpl_CreateSoundBuffer,
758     IDsDriverImpl_DuplicateSoundBuffer
759 };
760
761 DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
762 {
763     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
764
765     TRACE("driver created\n");
766
767     /* the HAL isn't much better than the HEL if we can't do mmap() */
768     if (!(WOutDev[wDevID].outcaps.dwSupport & WAVECAPS_DIRECTSOUND))
769     {
770         WARN("MMAP not supported for this device, falling back to waveout, should be harmless\n");
771         return MMSYSERR_NOTSUPPORTED;
772     }
773
774     *idrv = HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
775     if (!*idrv)
776         return MMSYSERR_NOMEM;
777     (*idrv)->lpVtbl     = &dsdvt;
778     (*idrv)->ref        = 1;
779
780     (*idrv)->wDevID     = wDevID;
781     (*idrv)->primary    = NULL;
782     return MMSYSERR_NOERROR;
783 }
784
785 DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
786 {
787     memcpy(desc, &(WOutDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
788     return MMSYSERR_NOERROR;
789 }
790
791 #endif /* HAVE_ALSA */