ntdll: Use the win16 current directory for win16 processes.
[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         WARN("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_RUNNING)
494         CheckXRUN(This);
495     else
496     {
497         snd_pcm_uframes_t used = CommitAll(This);
498
499         if (This->mmap_pos > used)
500             hw_pptr = This->mmap_pos - used;
501         else
502             hw_pptr = This->mmap_buflen_frames - used + This->mmap_pos;
503
504         hw_wptr = hw_pptr + (This->mmap_writeahead > used ? used : This->mmap_writeahead);
505         hw_wptr %= This->mmap_buflen_frames;
506         hw_pptr %= This->mmap_buflen_frames;
507
508         TRACE("At position: %ld (%ld) - Used %ld\n", hw_pptr, This->mmap_pos, used);
509     }
510
511     LeaveCriticalSection(&This->pcm_crst);
512
513     if (lpdwPlay)
514         *lpdwPlay = snd_pcm_frames_to_bytes(This->pcm, hw_pptr);
515     if (lpdwWrite)
516         *lpdwWrite = snd_pcm_frames_to_bytes(This->pcm, hw_wptr);
517
518     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);
519     return DS_OK;
520 }
521
522 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
523 {
524     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
525     TRACE("(%p,%x,%x,%x)\n",iface,dwRes1,dwRes2,dwFlags);
526
527     /* **** */
528     EnterCriticalSection(&This->pcm_crst);
529     snd_pcm_start(This->pcm);
530     CommitAll(This);
531     /* **** */
532     LeaveCriticalSection(&This->pcm_crst);
533     return DS_OK;
534 }
535
536 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
537 {
538     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
539     TRACE("(%p)\n",iface);
540
541     /* **** */
542     EnterCriticalSection(&This->pcm_crst);
543     snd_pcm_drop(This->pcm);
544     snd_pcm_prepare(This->pcm);
545     /* **** */
546     LeaveCriticalSection(&This->pcm_crst);
547     return DS_OK;
548 }
549
550 static const IDsDriverBufferVtbl dsdbvt =
551 {
552     IDsDriverBufferImpl_QueryInterface,
553     IDsDriverBufferImpl_AddRef,
554     IDsDriverBufferImpl_Release,
555     IDsDriverBufferImpl_Lock,
556     IDsDriverBufferImpl_Unlock,
557     IDsDriverBufferImpl_SetFormat,
558     IDsDriverBufferImpl_SetFrequency,
559     IDsDriverBufferImpl_SetVolumePan,
560     IDsDriverBufferImpl_SetPosition,
561     IDsDriverBufferImpl_GetPosition,
562     IDsDriverBufferImpl_Play,
563     IDsDriverBufferImpl_Stop
564 };
565
566 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
567 {
568     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
569     FIXME("(%p): stub!\n",iface);
570     return DSERR_UNSUPPORTED;
571 }
572
573 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
574 {
575     IDsDriverImpl *This = (IDsDriverImpl *)iface;
576     ULONG refCount = InterlockedIncrement(&This->ref);
577
578     TRACE("(%p)->(ref before=%u)\n",This, refCount - 1);
579
580     return refCount;
581 }
582
583 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
584 {
585     IDsDriverImpl *This = (IDsDriverImpl *)iface;
586     ULONG refCount = InterlockedDecrement(&This->ref);
587
588     TRACE("(%p)->(ref before=%u)\n",This, refCount + 1);
589
590     if (refCount)
591         return refCount;
592
593     HeapFree(GetProcessHeap(), 0, This);
594     return 0;
595 }
596
597 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
598 {
599     IDsDriverImpl *This = (IDsDriverImpl *)iface;
600     TRACE("(%p,%p)\n",iface,pDesc);
601     memcpy(pDesc, &(WOutDev[This->wDevID].ds_desc), sizeof(DSDRIVERDESC));
602     pDesc->dwFlags              = DSDDESC_DONTNEEDPRIMARYLOCK | DSDDESC_DONTNEEDSECONDARYLOCK | DSDDESC_DONTNEEDWRITELEAD;
603     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
604     pDesc->wVxdId               = 0;
605     pDesc->wReserved            = 0;
606     pDesc->ulDeviceNum          = This->wDevID;
607     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
608     pDesc->pvDirectDrawHeap     = NULL;
609     pDesc->dwMemStartAddress    = 0xDEAD0000;
610     pDesc->dwMemEndAddress      = 0xDEAF0000;
611     pDesc->dwMemAllocExtra      = 0;
612     pDesc->pvReserved1          = NULL;
613     pDesc->pvReserved2          = NULL;
614     return DS_OK;
615 }
616
617 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
618 {
619     HRESULT hr = S_OK;
620     IDsDriverImpl *This = (IDsDriverImpl *)iface;
621     int err=0;
622     snd_pcm_t *pcm = NULL;
623     snd_pcm_hw_params_t *hw_params;
624
625     /* While this is not really needed, it is a good idea to do this,
626      * to see if sound can be initialized */
627
628     hw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof());
629
630     if (!hw_params)
631     {
632         hr = DSERR_OUTOFMEMORY;
633         goto unalloc;
634     }
635
636     err = snd_pcm_open(&pcm, WOutDev[This->wDevID].pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
637     if (err < 0) goto err;
638     err = snd_pcm_hw_params_any(pcm, hw_params);
639     if (err < 0) goto err;
640     err = snd_pcm_hw_params_set_access (pcm, hw_params, SND_PCM_ACCESS_MMAP_INTERLEAVED);
641     if (err < 0) goto err;
642
643     TRACE("Success\n");
644     snd_pcm_close(pcm);
645     goto unalloc;
646
647     err:
648     hr = DSERR_GENERIC;
649     FIXME("Failed to open device: %s\n", snd_strerror(err));
650     if (pcm)
651         snd_pcm_close(pcm);
652     unalloc:
653     HeapFree(GetProcessHeap(), 0, hw_params);
654     if (hr != S_OK)
655         WARN("--> %08x\n", hr);
656     return hr;
657 }
658
659 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
660 {
661     IDsDriverImpl *This = (IDsDriverImpl *)iface;
662     TRACE("(%p) stub, harmless\n",This);
663     return DS_OK;
664 }
665
666 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
667 {
668     IDsDriverImpl *This = (IDsDriverImpl *)iface;
669     TRACE("(%p,%p)\n",iface,pCaps);
670     memcpy(pCaps, &(WOutDev[This->wDevID].ds_caps), sizeof(DSDRIVERCAPS));
671     return DS_OK;
672 }
673
674 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
675                                                       LPWAVEFORMATEX pwfx,
676                                                       DWORD dwFlags, DWORD dwCardAddress,
677                                                       LPDWORD pdwcbBufferSize,
678                                                       LPBYTE *ppbBuffer,
679                                                       LPVOID *ppvObj)
680 {
681     IDsDriverImpl *This = (IDsDriverImpl *)iface;
682     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
683     HRESULT err;
684
685     TRACE("(%p,%p,%x,%x)\n",iface,pwfx,dwFlags,dwCardAddress);
686     /* we only support primary buffers... for now */
687     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
688         return DSERR_UNSUPPORTED;
689     if (This->primary)
690         return DSERR_ALLOCATED;
691
692     *ippdsdb = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDsDriverBufferImpl));
693     if (*ippdsdb == NULL)
694         return DSERR_OUTOFMEMORY;
695
696     (*ippdsdb)->hw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof());
697     (*ippdsdb)->sw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_sw_params_sizeof());
698     if (!(*ippdsdb)->hw_params || !(*ippdsdb)->sw_params)
699     {
700         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->sw_params);
701         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->hw_params);
702         return DSERR_OUTOFMEMORY;
703     }
704     (*ippdsdb)->lpVtbl  = &dsdbvt;
705     (*ippdsdb)->ref     = 1;
706     (*ippdsdb)->drv     = This;
707     InitializeCriticalSection(&(*ippdsdb)->pcm_crst);
708     (*ippdsdb)->pcm_crst.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ALSA_DSOUTPUT.pcm_crst");
709
710     /* SetFormat has to re-initialize pcm here anyway */
711     err = SetFormat(*ippdsdb, pwfx, FALSE);
712     if (FAILED(err))
713     {
714         WARN("Error occurred: %08x\n", err);
715         goto err;
716     }
717
718     if (dwFlags & DSBCAPS_PRIMARYBUFFER)
719         This->primary = *ippdsdb;
720
721     *pdwcbBufferSize = (*ippdsdb)->mmap_buflen_bytes;
722     *ppbBuffer = (*ippdsdb)->mmap_buffer;
723
724     /* buffer is ready to go */
725     TRACE("buffer created at %p\n", *ippdsdb);
726     return err;
727
728     err:
729     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->sw_params);
730     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->hw_params);
731     HeapFree(GetProcessHeap(), 0, *ippdsdb);
732     *ippdsdb = NULL;
733     return err;
734 }
735
736 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
737                                                          PIDSDRIVERBUFFER pBuffer,
738                                                          LPVOID *ppvObj)
739 {
740     IDsDriverImpl *This = (IDsDriverImpl *)iface;
741     FIXME("(%p,%p): stub\n",This,pBuffer);
742     return DSERR_INVALIDCALL;
743 }
744
745 static const IDsDriverVtbl dsdvt =
746 {
747     IDsDriverImpl_QueryInterface,
748     IDsDriverImpl_AddRef,
749     IDsDriverImpl_Release,
750     IDsDriverImpl_GetDriverDesc,
751     IDsDriverImpl_Open,
752     IDsDriverImpl_Close,
753     IDsDriverImpl_GetCaps,
754     IDsDriverImpl_CreateSoundBuffer,
755     IDsDriverImpl_DuplicateSoundBuffer
756 };
757
758 DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
759 {
760     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
761
762     TRACE("driver created\n");
763
764     /* the HAL isn't much better than the HEL if we can't do mmap() */
765     if (!(WOutDev[wDevID].outcaps.dwSupport & WAVECAPS_DIRECTSOUND))
766     {
767         WARN("MMAP not supported for this device, falling back to waveout, should be harmless\n");
768         return MMSYSERR_NOTSUPPORTED;
769     }
770
771     *idrv = HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
772     if (!*idrv)
773         return MMSYSERR_NOMEM;
774     (*idrv)->lpVtbl     = &dsdvt;
775     (*idrv)->ref        = 1;
776
777     (*idrv)->wDevID     = wDevID;
778     (*idrv)->primary    = NULL;
779     return MMSYSERR_NOERROR;
780 }
781
782 DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
783 {
784     memcpy(desc, &(WOutDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
785     return MMSYSERR_NOERROR;
786 }
787
788 #endif /* HAVE_ALSA */