winealsa: Remove forceformat and 2 orphan LeaveCriticalSection.
[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;
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     pdbi->mmap_pos = ofs + snd_pcm_mmap_commit(pcm, ofs, 0);
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     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
288     snd_pcm_uframes_t writepos;
289
290     TRACE("%d bytes from %d\n", dwWriteLen, dwWritePosition);
291
292     /* **** */
293     EnterCriticalSection(&This->pcm_crst);
294
295     if (dwFlags & DSBLOCK_ENTIREBUFFER)
296         dwWriteLen = This->mmap_buflen_bytes;
297
298     if (dwWriteLen > This->mmap_buflen_bytes || dwWritePosition >= This->mmap_buflen_bytes)
299     {
300         /* **** */
301         LeaveCriticalSection(&This->pcm_crst);
302         return DSERR_INVALIDPARAM;
303     }
304
305     if (ppvAudio2) *ppvAudio2 = NULL;
306     if (pdwLen2) *pdwLen2 = 0;
307
308     *ppvAudio1 = (LPBYTE)This->mmap_buffer + dwWritePosition;
309     *pdwLen1 = dwWriteLen;
310
311     if (dwWritePosition+dwWriteLen > This->mmap_buflen_bytes)
312     {
313         DWORD remainder = This->mmap_buflen_bytes - dwWritePosition;
314         *pdwLen1 = remainder;
315
316         if (ppvAudio2 && pdwLen2)
317         {
318             *ppvAudio2 = This->mmap_buffer;
319             *pdwLen2 = dwWriteLen - remainder;
320         }
321         else dwWriteLen = remainder;
322     }
323
324     writepos = snd_pcm_bytes_to_frames(This->pcm, dwWritePosition);
325     if (writepos == This->mmap_pos)
326     {
327         const snd_pcm_channel_area_t *areas;
328         snd_pcm_uframes_t writelen = snd_pcm_bytes_to_frames(This->pcm, dwWriteLen), putin = writelen;
329         TRACE("Hit mmap_pos, locking data!\n");
330         snd_pcm_mmap_begin(This->pcm, &areas, &This->mmap_pos, &putin);
331     }
332
333     LeaveCriticalSection(&This->pcm_crst);
334     /* **** */
335     return DS_OK;
336 }
337
338 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
339                                                  LPVOID pvAudio1,DWORD dwLen1,
340                                                  LPVOID pvAudio2,DWORD dwLen2)
341 {
342     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
343     snd_pcm_uframes_t writepos;
344
345     if (!dwLen1)
346         return DS_OK;
347
348     /* **** */
349     EnterCriticalSection(&This->pcm_crst);
350
351     writepos = snd_pcm_bytes_to_frames(This->pcm, (DWORD_PTR)pvAudio1 - (DWORD_PTR)This->mmap_buffer);
352     if (writepos == This->mmap_pos)
353     {
354         const snd_pcm_channel_area_t *areas;
355         snd_pcm_uframes_t writelen = snd_pcm_bytes_to_frames(This->pcm, dwLen1);
356         TRACE("Committing data\n");
357         This->mmap_pos += snd_pcm_mmap_commit(This->pcm, This->mmap_pos, writelen);
358         if (This->mmap_pos == This->mmap_buflen_frames)
359             This->mmap_pos = 0;
360         if (!This->mmap_pos && dwLen2)
361         {
362             writelen = snd_pcm_bytes_to_frames(This->pcm, dwLen2);
363             snd_pcm_mmap_begin(This->pcm, &areas, &This->mmap_pos, &writelen);
364             This->mmap_pos += snd_pcm_mmap_commit(This->pcm, This->mmap_pos, writelen);
365             assert(This->mmap_pos < This->mmap_buflen_frames);
366         }
367     }
368     LeaveCriticalSection(&This->pcm_crst);
369     /* **** */
370
371     return DS_OK;
372 }
373
374 static HRESULT SetFormat(IDsDriverBufferImpl *This, LPWAVEFORMATEX pwfx)
375 {
376     snd_pcm_t *pcm = NULL;
377     snd_pcm_hw_params_t *hw_params = This->hw_params;
378     unsigned int buffer_time = 500000;
379     snd_pcm_format_t format = -1;
380     snd_pcm_uframes_t psize;
381     DWORD rate = pwfx->nSamplesPerSec;
382     int err=0;
383
384     switch (pwfx->wBitsPerSample)
385     {
386         case  8: format = SND_PCM_FORMAT_U8; break;
387         case 16: format = SND_PCM_FORMAT_S16_LE; break;
388         case 24: format = SND_PCM_FORMAT_S24_LE; break;
389         case 32: format = SND_PCM_FORMAT_S32_LE; break;
390         default: FIXME("Unsupported bpp: %d\n", pwfx->wBitsPerSample); return DSERR_GENERIC;
391     }
392
393     err = snd_pcm_open(&pcm, WOutDev[This->drv->wDevID].pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
394     if (err < 0)
395     {
396         if (errno != EBUSY || !This->pcm)
397         {
398             WARN("Cannot open sound device: %s\n", snd_strerror(err));
399             return DSERR_GENERIC;
400         }
401         snd_pcm_drop(This->pcm);
402         snd_pcm_close(This->pcm);
403         This->pcm = NULL;
404         err = snd_pcm_open(&pcm, WOutDev[This->drv->wDevID].pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
405         if (err < 0)
406         {
407             WARN("Cannot open sound device: %s\n", snd_strerror(err));
408             return DSERR_BUFFERLOST;
409         }
410     }
411
412     /* Set some defaults */
413     snd_pcm_hw_params_any(pcm, hw_params);
414     err = snd_pcm_hw_params_set_channels(pcm, hw_params, pwfx->nChannels);
415     if (err < 0) { WARN("Could not set channels to %d\n", pwfx->nChannels); goto err; }
416
417     err = snd_pcm_hw_params_set_format(pcm, hw_params, format);
418     if (err < 0) { WARN("Could not set format to %d bpp\n", pwfx->wBitsPerSample); goto err; }
419
420     /* Alsa's rate resampling is only used if the application specifically requests
421      * a buffer at a certain frequency, else it is better to disable it due to unwanted
422      * side effects, which may include: Less granular pointer, changing buffer sizes, etc
423      */
424 #if SND_LIB_VERSION >= 0x010009
425     snd_pcm_hw_params_set_rate_resample(pcm, hw_params, 0);
426 #endif
427
428     err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, NULL);
429     if (err < 0) { rate = pwfx->nSamplesPerSec; WARN("Could not set rate\n"); goto err; }
430
431     if (!ALSA_NearMatch(rate, pwfx->nSamplesPerSec))
432     {
433         WARN("Could not set sound rate to %d, but instead to %d\n", pwfx->nSamplesPerSec, rate);
434         pwfx->nSamplesPerSec = rate;
435         pwfx->nAvgBytesPerSec = rate * pwfx->nBlockAlign;
436         /* Let DirectSound detect this */
437     }
438
439     snd_pcm_hw_params_set_periods_integer(pcm, hw_params);
440     snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, NULL);
441     buffer_time = 10000;
442     snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &buffer_time, NULL);
443     err = snd_pcm_hw_params(pcm, hw_params);
444     err = snd_pcm_sw_params(pcm, This->sw_params);
445     snd_pcm_prepare(pcm);
446
447     err = snd_pcm_hw_params_get_period_size(hw_params, &psize, NULL);
448     TRACE("Period size is: %lu\n", psize);
449
450     /* ALSA needs at least 3 buffers to work successfully */
451     This->mmap_commitahead = 3 * psize;
452     while (This->mmap_commitahead <= 512)
453         This->mmap_commitahead += psize;
454
455     if (This->pcm)
456     {
457         snd_pcm_drop(This->pcm);
458         snd_pcm_close(This->pcm);
459     }
460     This->pcm = pcm;
461     snd_pcm_prepare(This->pcm);
462     DSDB_CreateMMAP(This);
463     return S_OK;
464
465     err:
466     if (err < 0)
467         WARN("Failed to apply changes: %s\n", snd_strerror(err));
468
469     if (!This->pcm)
470         This->pcm = pcm;
471     else
472         snd_pcm_close(pcm);
473
474     if (This->pcm)
475         snd_pcm_hw_params_current(This->pcm, This->hw_params);
476
477     return DSERR_BADFORMAT;
478 }
479
480 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface, LPWAVEFORMATEX pwfx)
481 {
482     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
483     HRESULT hr = S_OK;
484
485     TRACE("(%p, %p)\n", iface, pwfx);
486
487     /* **** */
488     EnterCriticalSection(&This->pcm_crst);
489     hr = SetFormat(This, pwfx);
490     /* **** */
491     LeaveCriticalSection(&This->pcm_crst);
492
493     if (hr == DS_OK)
494         return S_FALSE;
495     return hr;
496 }
497
498 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
499 {
500     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
501     FIXME("(%p,%d): stub\n",iface,dwFreq);
502     return S_OK;
503 }
504
505 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
506 {
507     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
508     FIXME("(%p,%p): stub\n",This,pVolPan);
509     /* TODO: Bring volume control back */
510     return DS_OK;
511 }
512
513 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
514 {
515     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
516     /* I don't even think alsa allows this */
517     FIXME("(%p,%d): stub\n",iface,dwNewPos);
518     return DSERR_UNSUPPORTED;
519 }
520
521 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
522                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
523 {
524     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
525     snd_pcm_uframes_t hw_pptr, hw_wptr;
526     snd_pcm_state_t state;
527
528     /* **** */
529     EnterCriticalSection(&This->pcm_crst);
530
531     if (!This->pcm)
532     {
533         FIXME("Bad pointer for pcm: %p\n", This->pcm);
534         LeaveCriticalSection(&This->pcm_crst);
535         return DSERR_GENERIC;
536     }
537
538     if (!lpdwPlay && !lpdwWrite)
539         CommitAll(This);
540
541     state = snd_pcm_state(This->pcm);
542
543     if (state != SND_PCM_STATE_PREPARED && state != SND_PCM_STATE_RUNNING)
544     {
545         CheckXRUN(This);
546         state = snd_pcm_state(This->pcm);
547     }
548     if (state == SND_PCM_STATE_RUNNING)
549     {
550         snd_pcm_uframes_t used = This->mmap_buflen_frames - snd_pcm_avail_update(This->pcm);
551
552         if (This->mmap_pos > used)
553             hw_pptr = This->mmap_pos - used;
554         else
555             hw_pptr = This->mmap_buflen_frames + This->mmap_pos - used;
556         hw_pptr %= This->mmap_buflen_frames;
557
558         TRACE("At position: %ld (%ld) - Used %ld\n", hw_pptr, This->mmap_pos, used);
559     }
560     else hw_pptr = This->mmap_pos;
561     hw_wptr = This->mmap_pos;
562
563     LeaveCriticalSection(&This->pcm_crst);
564     /* **** */
565
566     if (lpdwPlay)
567         *lpdwPlay = snd_pcm_frames_to_bytes(This->pcm, hw_pptr);
568     if (lpdwWrite)
569         *lpdwWrite = snd_pcm_frames_to_bytes(This->pcm, hw_wptr);
570
571     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);
572     return DS_OK;
573 }
574
575 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
576 {
577     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
578     TRACE("(%p,%x,%x,%x)\n",iface,dwRes1,dwRes2,dwFlags);
579
580     /* **** */
581     EnterCriticalSection(&This->pcm_crst);
582     snd_pcm_start(This->pcm);
583     /* **** */
584     LeaveCriticalSection(&This->pcm_crst);
585     return DS_OK;
586 }
587
588 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
589 {
590     const snd_pcm_channel_area_t *areas;
591     snd_pcm_uframes_t avail;
592     snd_pcm_format_t format;
593     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
594     TRACE("(%p)\n",iface);
595
596     /* **** */
597     EnterCriticalSection(&This->pcm_crst);
598     avail = This->mmap_buflen_frames;
599     snd_pcm_drop(This->pcm);
600     snd_pcm_prepare(This->pcm);
601     avail = snd_pcm_avail_update(This->pcm);
602     snd_pcm_mmap_begin(This->pcm, &areas, &This->mmap_pos, &avail);
603     snd_pcm_hw_params_get_format(This->hw_params, &format);
604     snd_pcm_format_set_silence(format, areas->addr, This->mmap_buflen_frames);
605     snd_pcm_mmap_commit(This->pcm, This->mmap_pos, 0);
606
607     /* **** */
608     LeaveCriticalSection(&This->pcm_crst);
609     return DS_OK;
610 }
611
612 static const IDsDriverBufferVtbl dsdbvt =
613 {
614     IDsDriverBufferImpl_QueryInterface,
615     IDsDriverBufferImpl_AddRef,
616     IDsDriverBufferImpl_Release,
617     IDsDriverBufferImpl_Lock,
618     IDsDriverBufferImpl_Unlock,
619     IDsDriverBufferImpl_SetFormat,
620     IDsDriverBufferImpl_SetFrequency,
621     IDsDriverBufferImpl_SetVolumePan,
622     IDsDriverBufferImpl_SetPosition,
623     IDsDriverBufferImpl_GetPosition,
624     IDsDriverBufferImpl_Play,
625     IDsDriverBufferImpl_Stop
626 };
627
628 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
629 {
630     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
631     FIXME("(%p): stub!\n",iface);
632     return DSERR_UNSUPPORTED;
633 }
634
635 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
636 {
637     IDsDriverImpl *This = (IDsDriverImpl *)iface;
638     ULONG refCount = InterlockedIncrement(&This->ref);
639
640     TRACE("(%p)->(ref before=%u)\n",This, refCount - 1);
641
642     return refCount;
643 }
644
645 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
646 {
647     IDsDriverImpl *This = (IDsDriverImpl *)iface;
648     ULONG refCount = InterlockedDecrement(&This->ref);
649
650     TRACE("(%p)->(ref before=%u)\n",This, refCount + 1);
651
652     if (refCount)
653         return refCount;
654
655     HeapFree(GetProcessHeap(), 0, This);
656     return 0;
657 }
658
659 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
660 {
661     IDsDriverImpl *This = (IDsDriverImpl *)iface;
662     TRACE("(%p,%p)\n",iface,pDesc);
663     memcpy(pDesc, &(WOutDev[This->wDevID].ds_desc), sizeof(DSDRIVERDESC));
664     pDesc->dwFlags              = DSDDESC_DONTNEEDSECONDARYLOCK | DSDDESC_DONTNEEDWRITELEAD;
665     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
666     pDesc->wVxdId               = 0;
667     pDesc->wReserved            = 0;
668     pDesc->ulDeviceNum          = This->wDevID;
669     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
670     pDesc->pvDirectDrawHeap     = NULL;
671     pDesc->dwMemStartAddress    = 0xDEAD0000;
672     pDesc->dwMemEndAddress      = 0xDEAF0000;
673     pDesc->dwMemAllocExtra      = 0;
674     pDesc->pvReserved1          = NULL;
675     pDesc->pvReserved2          = NULL;
676     return DS_OK;
677 }
678
679 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
680 {
681     HRESULT hr = S_OK;
682     IDsDriverImpl *This = (IDsDriverImpl *)iface;
683     int err=0;
684     snd_pcm_t *pcm = NULL;
685     snd_pcm_hw_params_t *hw_params;
686
687     /* While this is not really needed, it is a good idea to do this,
688      * to see if sound can be initialized */
689
690     hw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof());
691
692     if (!hw_params)
693     {
694         hr = DSERR_OUTOFMEMORY;
695         goto unalloc;
696     }
697
698     err = snd_pcm_open(&pcm, WOutDev[This->wDevID].pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
699     if (err < 0) goto err;
700     err = snd_pcm_hw_params_any(pcm, hw_params);
701     if (err < 0) goto err;
702     err = snd_pcm_hw_params_set_access (pcm, hw_params, SND_PCM_ACCESS_MMAP_INTERLEAVED);
703     if (err < 0) goto err;
704
705     TRACE("Success\n");
706     snd_pcm_close(pcm);
707     goto unalloc;
708
709     err:
710     hr = DSERR_GENERIC;
711     FIXME("Failed to open device: %s\n", snd_strerror(err));
712     if (pcm)
713         snd_pcm_close(pcm);
714     unalloc:
715     HeapFree(GetProcessHeap(), 0, hw_params);
716     if (hr != S_OK)
717         WARN("--> %08x\n", hr);
718     return hr;
719 }
720
721 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
722 {
723     IDsDriverImpl *This = (IDsDriverImpl *)iface;
724     TRACE("(%p) stub, harmless\n",This);
725     return DS_OK;
726 }
727
728 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
729 {
730     IDsDriverImpl *This = (IDsDriverImpl *)iface;
731     TRACE("(%p,%p)\n",iface,pCaps);
732     memcpy(pCaps, &(WOutDev[This->wDevID].ds_caps), sizeof(DSDRIVERCAPS));
733     return DS_OK;
734 }
735
736 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
737                                                       LPWAVEFORMATEX pwfx,
738                                                       DWORD dwFlags, DWORD dwCardAddress,
739                                                       LPDWORD pdwcbBufferSize,
740                                                       LPBYTE *ppbBuffer,
741                                                       LPVOID *ppvObj)
742 {
743     IDsDriverImpl *This = (IDsDriverImpl *)iface;
744     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
745     HRESULT err;
746
747     TRACE("(%p,%p,%x,%x)\n",iface,pwfx,dwFlags,dwCardAddress);
748     /* we only support primary buffers... for now */
749     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
750         return DSERR_UNSUPPORTED;
751     if (This->primary)
752         return DSERR_ALLOCATED;
753
754     *ippdsdb = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDsDriverBufferImpl));
755     if (*ippdsdb == NULL)
756         return DSERR_OUTOFMEMORY;
757
758     (*ippdsdb)->hw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof());
759     (*ippdsdb)->sw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_sw_params_sizeof());
760     if (!(*ippdsdb)->hw_params || !(*ippdsdb)->sw_params)
761     {
762         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->sw_params);
763         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->hw_params);
764         return DSERR_OUTOFMEMORY;
765     }
766     (*ippdsdb)->lpVtbl  = &dsdbvt;
767     (*ippdsdb)->ref     = 1;
768     (*ippdsdb)->drv     = This;
769     InitializeCriticalSection(&(*ippdsdb)->pcm_crst);
770     (*ippdsdb)->pcm_crst.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ALSA_DSOUTPUT.pcm_crst");
771
772     /* SetFormat has to re-initialize pcm here anyway */
773     err = SetFormat(*ippdsdb, pwfx);
774     if (FAILED(err))
775     {
776         WARN("Error occurred: %08x\n", err);
777         goto err;
778     }
779
780     if (dwFlags & DSBCAPS_PRIMARYBUFFER)
781         This->primary = *ippdsdb;
782
783     *pdwcbBufferSize = (*ippdsdb)->mmap_buflen_bytes;
784     *ppbBuffer = (*ippdsdb)->mmap_buffer;
785
786     /* buffer is ready to go */
787     TRACE("buffer created at %p\n", *ippdsdb);
788     return err;
789
790     err:
791     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->sw_params);
792     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->hw_params);
793     HeapFree(GetProcessHeap(), 0, *ippdsdb);
794     *ippdsdb = NULL;
795     return err;
796 }
797
798 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
799                                                          PIDSDRIVERBUFFER pBuffer,
800                                                          LPVOID *ppvObj)
801 {
802     IDsDriverImpl *This = (IDsDriverImpl *)iface;
803     FIXME("(%p,%p): stub\n",This,pBuffer);
804     return DSERR_INVALIDCALL;
805 }
806
807 static const IDsDriverVtbl dsdvt =
808 {
809     IDsDriverImpl_QueryInterface,
810     IDsDriverImpl_AddRef,
811     IDsDriverImpl_Release,
812     IDsDriverImpl_GetDriverDesc,
813     IDsDriverImpl_Open,
814     IDsDriverImpl_Close,
815     IDsDriverImpl_GetCaps,
816     IDsDriverImpl_CreateSoundBuffer,
817     IDsDriverImpl_DuplicateSoundBuffer
818 };
819
820 DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
821 {
822     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
823
824     TRACE("driver created\n");
825
826     /* the HAL isn't much better than the HEL if we can't do mmap() */
827     if (!(WOutDev[wDevID].outcaps.dwSupport & WAVECAPS_DIRECTSOUND))
828     {
829         WARN("MMAP not supported for this device, falling back to waveout, should be harmless\n");
830         return MMSYSERR_NOTSUPPORTED;
831     }
832
833     *idrv = HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
834     if (!*idrv)
835         return MMSYSERR_NOMEM;
836     (*idrv)->lpVtbl     = &dsdvt;
837     (*idrv)->ref        = 1;
838
839     (*idrv)->wDevID     = wDevID;
840     (*idrv)->primary    = NULL;
841     return MMSYSERR_NOERROR;
842 }
843
844 DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
845 {
846     memcpy(desc, &(WOutDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
847     return MMSYSERR_NOERROR;
848 }
849
850 #endif /* HAVE_ALSA */