dmsynth: Mark internal symbols with hidden visibility.
[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 <assert.h>
34 #include <stdarg.h>
35 #include <stdio.h>
36 #include <string.h>
37 #ifdef HAVE_UNISTD_H
38 # include <unistd.h>
39 #endif
40 #include <errno.h>
41 #include <limits.h>
42 #include <fcntl.h>
43 #ifdef HAVE_SYS_IOCTL_H
44 # include <sys/ioctl.h>
45 #endif
46 #ifdef HAVE_SYS_MMAN_H
47 # include <sys/mman.h>
48 #endif
49 #include "windef.h"
50 #include "winbase.h"
51 #include "wingdi.h"
52 #include "winerror.h"
53 #include "winuser.h"
54 #include "mmddk.h"
55 #include "mmreg.h"
56 #include "dsound.h"
57 #include "dsdriver.h"
58
59 #include "alsa.h"
60 #include "wine/library.h"
61 #include "wine/unicode.h"
62 #include "wine/debug.h"
63
64 WINE_DEFAULT_DEBUG_CHANNEL(dsalsa);
65
66 typedef struct IDsDriverImpl IDsDriverImpl;
67 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
68
69 struct IDsDriverImpl
70 {
71     /* IUnknown fields */
72     IDsDriver IDsDriver_iface;
73     LONG ref;
74
75     /* IDsDriverImpl fields */
76     IDsDriverBufferImpl* primary;
77     UINT wDevID;
78 };
79
80 struct IDsDriverBufferImpl
81 {
82     IDsDriverBuffer IDsDriverBuffer_iface;
83     LONG ref;
84     IDsDriverImpl* drv;
85
86     CRITICAL_SECTION pcm_crst;
87     BYTE *mmap_buffer;
88     DWORD mmap_buflen_bytes;
89     BOOL mmap;
90
91     snd_pcm_t *pcm;
92     snd_pcm_hw_params_t *hw_params;
93     snd_pcm_sw_params_t *sw_params;
94     snd_pcm_uframes_t mmap_buflen_frames, mmap_pos, mmap_commitahead;
95 };
96
97 static inline IDsDriverImpl *impl_from_IDsDriver(IDsDriver *iface)
98 {
99     return CONTAINING_RECORD(iface, IDsDriverImpl, IDsDriver_iface);
100 }
101
102 static inline IDsDriverBufferImpl *impl_from_IDsDriverBuffer(IDsDriverBuffer *iface)
103 {
104     return CONTAINING_RECORD(iface, IDsDriverBufferImpl, IDsDriverBuffer_iface);
105 }
106
107 /** Fill buffers, for starting and stopping
108  * Alsa won't start playing until everything is filled up
109  * This also updates mmap_pos
110  *
111  * Returns: Amount of periods in use so snd_pcm_avail_update
112  * doesn't have to be called up to 4x in GetPosition()
113  */
114 static snd_pcm_uframes_t CommitAll(IDsDriverBufferImpl *This)
115 {
116     const snd_pcm_channel_area_t *areas;
117     snd_pcm_sframes_t used;
118     const snd_pcm_uframes_t commitahead = This->mmap_commitahead;
119
120     used = This->mmap_buflen_frames - snd_pcm_avail_update(This->pcm);
121     if (used < 0) used = 0;
122     TRACE("%p needs to commit to %lu, used: %ld\n", This, commitahead, used);
123     if (used < commitahead)
124     {
125         snd_pcm_sframes_t done;
126         snd_pcm_uframes_t putin = commitahead - used;
127         if (This->mmap)
128         {
129             snd_pcm_mmap_begin(This->pcm, &areas, &This->mmap_pos, &putin);
130             done = snd_pcm_mmap_commit(This->pcm, This->mmap_pos, putin);
131         }
132         else
133         {
134             if (putin + This->mmap_pos > This->mmap_buflen_frames)
135                 putin = This->mmap_buflen_frames - This->mmap_pos;
136             done = snd_pcm_writei(This->pcm, This->mmap_buffer + snd_pcm_frames_to_bytes(This->pcm, This->mmap_pos), putin);
137             if (done < putin) WARN("Short write %ld/%ld\n", putin, done);
138         }
139         if (done < 0) done = 0;
140         This->mmap_pos += done;
141         used += done;
142         putin = commitahead - used;
143
144         if (This->mmap_pos == This->mmap_buflen_frames && (snd_pcm_sframes_t)putin > 0)
145         {
146             if (This->mmap)
147             {
148                 snd_pcm_mmap_begin(This->pcm, &areas, &This->mmap_pos, &putin);
149                 done = snd_pcm_mmap_commit(This->pcm, This->mmap_pos, putin);
150                 This->mmap_pos += done;
151             }
152             else
153             {
154                 done = snd_pcm_writei(This->pcm, This->mmap_buffer, putin);
155                 if (done < putin) WARN("Short write %ld/%ld\n", putin, done);
156                 if (done < 0) done = 0;
157                 This->mmap_pos = done;
158             }
159             used += done;
160         }
161     }
162
163     if (This->mmap_pos == This->mmap_buflen_frames)
164         This->mmap_pos = 0;
165
166     return used;
167 }
168
169 static void CheckXRUN(IDsDriverBufferImpl* This)
170 {
171     snd_pcm_state_t state = snd_pcm_state(This->pcm);
172     int err;
173
174     if ( state == SND_PCM_STATE_XRUN )
175     {
176         err = snd_pcm_prepare(This->pcm);
177         CommitAll(This);
178         snd_pcm_start(This->pcm);
179         WARN("xrun occurred\n");
180         if ( err < 0 )
181             ERR("recovery from xrun failed, prepare failed: %s\n", snd_strerror(err));
182     }
183     else if ( state == SND_PCM_STATE_SUSPENDED )
184     {
185         int err = snd_pcm_resume(This->pcm);
186         TRACE("recovery from suspension occurred\n");
187         if (err < 0 && err != -EAGAIN){
188             err = snd_pcm_prepare(This->pcm);
189             if (err < 0)
190                 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
191         }
192     } else if ( state != SND_PCM_STATE_RUNNING ) {
193         FIXME("Unhandled state: %d\n", state);
194     }
195 }
196
197 /**
198  * Allocate the memory-mapped buffer for direct sound, and set up the
199  * callback.
200  */
201 static int DSDB_CreateMMAP(IDsDriverBufferImpl* pdbi)
202 {
203     snd_pcm_t *pcm = pdbi->pcm;
204     snd_pcm_format_t format;
205     snd_pcm_uframes_t frames, ofs, avail, psize, boundary;
206     unsigned int channels, bits_per_sample, bits_per_frame;
207     int err, mmap_mode;
208     const snd_pcm_channel_area_t *areas;
209     snd_pcm_hw_params_t *hw_params = pdbi->hw_params;
210     snd_pcm_sw_params_t *sw_params = pdbi->sw_params;
211     void *buf;
212
213     mmap_mode = snd_pcm_type(pcm);
214
215     if (mmap_mode == SND_PCM_TYPE_HW)
216         TRACE("mmap'd buffer is a direct hardware buffer.\n");
217     else if (mmap_mode == SND_PCM_TYPE_DMIX)
218         TRACE("mmap'd buffer is an ALSA dmix buffer\n");
219     else
220         TRACE("mmap'd buffer is an ALSA type %d buffer\n", mmap_mode);
221
222     err = snd_pcm_hw_params_get_period_size(hw_params, &psize, NULL);
223
224     err = snd_pcm_hw_params_get_format(hw_params, &format);
225     err = snd_pcm_hw_params_get_buffer_size(hw_params, &frames);
226     err = snd_pcm_hw_params_get_channels(hw_params, &channels);
227     bits_per_sample = snd_pcm_format_physical_width(format);
228     bits_per_frame = bits_per_sample * channels;
229
230     if (TRACE_ON(dsalsa))
231         ALSA_TraceParameters(hw_params, NULL, FALSE);
232
233     TRACE("format=%s  frames=%ld  channels=%d  bits_per_sample=%d  bits_per_frame=%d\n",
234           snd_pcm_format_name(format), frames, channels, bits_per_sample, bits_per_frame);
235
236     pdbi->mmap_buflen_frames = frames;
237     pdbi->mmap_buflen_bytes = snd_pcm_frames_to_bytes( pcm, frames );
238
239     snd_pcm_sw_params_current(pcm, sw_params);
240     snd_pcm_sw_params_set_start_threshold(pcm, sw_params, 0);
241     snd_pcm_sw_params_get_boundary(sw_params, &boundary);
242     snd_pcm_sw_params_set_stop_threshold(pcm, sw_params, boundary);
243     snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, boundary);
244     snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0);
245     snd_pcm_sw_params_set_avail_min(pcm, sw_params, 0);
246     err = snd_pcm_sw_params(pcm, sw_params);
247
248     avail = snd_pcm_avail_update(pcm);
249     if ((snd_pcm_sframes_t)avail < 0)
250     {
251         ERR("No buffer is available: %s.\n", snd_strerror(avail));
252         return DSERR_GENERIC;
253     }
254
255     if (!pdbi->mmap)
256     {
257         buf = pdbi->mmap_buffer = HeapAlloc(GetProcessHeap(), 0, pdbi->mmap_buflen_bytes);
258         if (!buf)
259             return DSERR_OUTOFMEMORY;
260
261         snd_pcm_format_set_silence(format, buf, pdbi->mmap_buflen_frames);
262         pdbi->mmap_pos = 0;
263     }
264     else
265     {
266         err = snd_pcm_mmap_begin(pcm, &areas, &ofs, &avail);
267         if ( err < 0 )
268         {
269             ERR("Can't map sound device for direct access: %s/%d\n", snd_strerror(err), err);
270             return DSERR_GENERIC;
271         }
272         snd_pcm_format_set_silence(format, areas->addr, pdbi->mmap_buflen_frames);
273         pdbi->mmap_pos = ofs + snd_pcm_mmap_commit(pcm, ofs, 0);
274         pdbi->mmap_buffer = areas->addr;
275     }
276
277     TRACE("created mmap buffer of %ld frames (%d bytes) at %p\n",
278         frames, pdbi->mmap_buflen_bytes, pdbi->mmap_buffer);
279
280     return DS_OK;
281 }
282
283 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
284 {
285     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
286     FIXME("(): stub!\n");
287     return DSERR_UNSUPPORTED;
288 }
289
290 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
291 {
292     IDsDriverBufferImpl *This = impl_from_IDsDriverBuffer(iface);
293     ULONG refCount = InterlockedIncrement(&This->ref);
294
295     TRACE("(%p)->(ref before=%u)\n",This, refCount - 1);
296
297     return refCount;
298 }
299
300 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
301 {
302     IDsDriverBufferImpl *This = impl_from_IDsDriverBuffer(iface);
303     ULONG refCount = InterlockedDecrement(&This->ref);
304
305     TRACE("(%p)->(ref before=%u)\n",This, refCount + 1);
306
307     if (refCount)
308         return refCount;
309
310     TRACE("mmap buffer %p destroyed\n", This->mmap_buffer);
311
312     if (This == This->drv->primary)
313         This->drv->primary = NULL;
314
315     This->pcm_crst.DebugInfo->Spare[0] = 0;
316     DeleteCriticalSection(&This->pcm_crst);
317
318     snd_pcm_drop(This->pcm);
319     snd_pcm_close(This->pcm);
320     This->pcm = NULL;
321     HeapFree(GetProcessHeap(), 0, This->sw_params);
322     HeapFree(GetProcessHeap(), 0, This->hw_params);
323     if (!This->mmap)
324         HeapFree(GetProcessHeap(), 0, This->mmap_buffer);
325     HeapFree(GetProcessHeap(), 0, This);
326     return 0;
327 }
328
329 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
330                                                LPVOID*ppvAudio1,LPDWORD pdwLen1,
331                                                LPVOID*ppvAudio2,LPDWORD pdwLen2,
332                                                DWORD dwWritePosition,DWORD dwWriteLen,
333                                                DWORD dwFlags)
334 {
335     IDsDriverBufferImpl *This = impl_from_IDsDriverBuffer(iface);
336     snd_pcm_uframes_t writepos;
337
338     TRACE("%d bytes from %d\n", dwWriteLen, dwWritePosition);
339
340     /* **** */
341     EnterCriticalSection(&This->pcm_crst);
342
343     if (dwFlags & DSBLOCK_ENTIREBUFFER)
344         dwWriteLen = This->mmap_buflen_bytes;
345
346     if (dwWriteLen > This->mmap_buflen_bytes || dwWritePosition >= This->mmap_buflen_bytes)
347     {
348         /* **** */
349         LeaveCriticalSection(&This->pcm_crst);
350         return DSERR_INVALIDPARAM;
351     }
352
353     if (ppvAudio2) *ppvAudio2 = NULL;
354     if (pdwLen2) *pdwLen2 = 0;
355
356     *ppvAudio1 = This->mmap_buffer + dwWritePosition;
357     *pdwLen1 = dwWriteLen;
358
359     if (dwWritePosition+dwWriteLen > This->mmap_buflen_bytes)
360     {
361         DWORD remainder = This->mmap_buflen_bytes - dwWritePosition;
362         *pdwLen1 = remainder;
363
364         if (ppvAudio2 && pdwLen2)
365         {
366             *ppvAudio2 = This->mmap_buffer;
367             *pdwLen2 = dwWriteLen - remainder;
368         }
369         else dwWriteLen = remainder;
370     }
371
372     writepos = snd_pcm_bytes_to_frames(This->pcm, dwWritePosition);
373     if (writepos == This->mmap_pos)
374     {
375         const snd_pcm_channel_area_t *areas;
376         snd_pcm_uframes_t writelen = snd_pcm_bytes_to_frames(This->pcm, dwWriteLen), putin = writelen;
377         TRACE("Hit mmap_pos, locking data!\n");
378         if (This->mmap)
379             snd_pcm_mmap_begin(This->pcm, &areas, &This->mmap_pos, &putin);
380     }
381     else
382         WARN("mmap_pos (%lu) != writepos (%lu) not locking data!\n", This->mmap_pos, writepos);
383
384     LeaveCriticalSection(&This->pcm_crst);
385     /* **** */
386     return DS_OK;
387 }
388
389 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
390                                                  LPVOID pvAudio1,DWORD dwLen1,
391                                                  LPVOID pvAudio2,DWORD dwLen2)
392 {
393     IDsDriverBufferImpl *This = impl_from_IDsDriverBuffer(iface);
394     snd_pcm_uframes_t writepos;
395
396     if (!dwLen1)
397         return DS_OK;
398
399     /* **** */
400     EnterCriticalSection(&This->pcm_crst);
401
402     writepos = snd_pcm_bytes_to_frames(This->pcm, (DWORD_PTR)pvAudio1 - (DWORD_PTR)This->mmap_buffer);
403     if (writepos == This->mmap_pos)
404     {
405         const snd_pcm_channel_area_t *areas;
406         snd_pcm_uframes_t writelen = snd_pcm_bytes_to_frames(This->pcm, dwLen1);
407         TRACE("Committing data\n");
408         if (This->mmap)
409             This->mmap_pos += snd_pcm_mmap_commit(This->pcm, This->mmap_pos, writelen);
410         else
411         {
412             int ret;
413             ret = snd_pcm_writei(This->pcm, pvAudio1, writelen);
414             if (ret == -EPIPE)
415             {
416                 WARN("Underrun occurred\n");
417                 wine_snd_pcm_recover(This->pcm, -EPIPE, 1);
418                 ret = snd_pcm_writei(This->pcm, pvAudio1, writelen);
419
420                 /* Advance mmap pointer a little to make dsound notice the underrun and respond to it */
421                 if (ret < writelen) WARN("Short write %ld/%d\n", writelen, ret);
422                 This->mmap_pos += This->mmap_commitahead + ret;
423                 This->mmap_pos %= This->mmap_buflen_frames;
424             }
425             else if (ret > 0)
426                 This->mmap_pos += ret;
427             if (ret < 0)
428                 WARN("Committing data: %d / %s (%p %ld)\n", ret, snd_strerror(ret), pvAudio1, writelen);
429         }
430
431         if (This->mmap_pos == This->mmap_buflen_frames)
432             This->mmap_pos = 0;
433         if (dwLen2)
434         {
435             writelen = snd_pcm_bytes_to_frames(This->pcm, dwLen2);
436             if (This->mmap)
437             {
438                 snd_pcm_mmap_begin(This->pcm, &areas, &This->mmap_pos, &writelen);
439                 This->mmap_pos += snd_pcm_mmap_commit(This->pcm, This->mmap_pos, writelen);
440             }
441             else
442             {
443                 int ret;
444                 ret = snd_pcm_writei(This->pcm, pvAudio2, writelen);
445                 if (ret < writelen) WARN("Short write %ld/%d\n", writelen, ret);
446                 This->mmap_pos = ret > 0 ? ret : 0;
447             }
448             assert(This->mmap_pos < This->mmap_buflen_frames);
449         }
450     }
451     LeaveCriticalSection(&This->pcm_crst);
452     /* **** */
453
454     return DS_OK;
455 }
456
457 static HRESULT SetFormat(IDsDriverBufferImpl *This, LPWAVEFORMATEX pwfx)
458 {
459     snd_pcm_t *pcm = NULL;
460     snd_pcm_hw_params_t *hw_params = This->hw_params;
461     unsigned int buffer_time = 500000;
462     snd_pcm_format_t format = -1;
463     snd_pcm_uframes_t psize;
464     DWORD rate = pwfx->nSamplesPerSec;
465     int err=0;
466
467     switch (pwfx->wBitsPerSample)
468     {
469         case  8: format = SND_PCM_FORMAT_U8; break;
470         case 16: format = SND_PCM_FORMAT_S16_LE; break;
471         case 24: format = SND_PCM_FORMAT_S24_3LE; break;
472         case 32: format = SND_PCM_FORMAT_S32_LE; break;
473         default: FIXME("Unsupported bpp: %d\n", pwfx->wBitsPerSample); return DSERR_GENERIC;
474     }
475
476     err = snd_pcm_open(&pcm, WOutDev[This->drv->wDevID].pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
477     if (err < 0)
478     {
479         if (errno != EBUSY || !This->pcm)
480         {
481             WARN("Cannot open sound device: %s\n", snd_strerror(err));
482             return DSERR_GENERIC;
483         }
484         snd_pcm_drop(This->pcm);
485         snd_pcm_close(This->pcm);
486         This->pcm = NULL;
487         err = snd_pcm_open(&pcm, WOutDev[This->drv->wDevID].pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
488         if (err < 0)
489         {
490             WARN("Cannot open sound device: %s\n", snd_strerror(err));
491             return DSERR_BUFFERLOST;
492         }
493     }
494
495     /* Set some defaults */
496     snd_pcm_hw_params_any(pcm, hw_params);
497     err = snd_pcm_hw_params_set_channels(pcm, hw_params, pwfx->nChannels);
498     if (err < 0) { WARN("Could not set channels to %d\n", pwfx->nChannels); goto err; }
499
500     err = snd_pcm_hw_params_set_format(pcm, hw_params, format);
501     if (err < 0) { WARN("Could not set format to %d bpp\n", pwfx->wBitsPerSample); goto err; }
502
503     /* Alsa's rate resampling is only used if the application specifically requests
504      * a buffer at a certain frequency, else it is better to disable it due to unwanted
505      * side effects, which may include: Less granular pointer, changing buffer sizes, etc
506      */
507 #if SND_LIB_VERSION >= 0x010009
508     snd_pcm_hw_params_set_rate_resample(pcm, hw_params, 0);
509 #endif
510
511     err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, NULL);
512     if (err < 0) { rate = pwfx->nSamplesPerSec; WARN("Could not set rate\n"); goto err; }
513
514     if (!ALSA_NearMatch(rate, pwfx->nSamplesPerSec))
515     {
516         WARN("Could not set sound rate to %d, but instead to %d\n", pwfx->nSamplesPerSec, rate);
517         pwfx->nSamplesPerSec = rate;
518         pwfx->nAvgBytesPerSec = rate * pwfx->nBlockAlign;
519         /* Let DirectSound detect this */
520     }
521
522     snd_pcm_hw_params_set_periods_integer(pcm, hw_params);
523     snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, NULL);
524     buffer_time = 10000;
525     snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &buffer_time, NULL);
526
527     err = snd_pcm_hw_params_get_period_size(hw_params, &psize, NULL);
528     buffer_time = 16;
529     snd_pcm_hw_params_set_periods_near(pcm, hw_params, &buffer_time, NULL);
530
531     if (!This->mmap)
532     {
533         HeapFree(GetProcessHeap(), 0, This->mmap_buffer);
534         This->mmap_buffer = NULL;
535     }
536
537     err = snd_pcm_hw_params_set_access (pcm, hw_params, SND_PCM_ACCESS_MMAP_INTERLEAVED);
538     if (err >= 0)
539         This->mmap = 1;
540     else
541     {
542         This->mmap = 0;
543         err = snd_pcm_hw_params_set_access (pcm, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
544     }
545
546     err = snd_pcm_hw_params(pcm, hw_params);
547
548     /* ALSA needs at least 3 buffers to work successfully */
549     This->mmap_commitahead = 3 * psize;
550     while (This->mmap_commitahead <= 512)
551         This->mmap_commitahead += psize;
552
553     if (This->pcm)
554     {
555         snd_pcm_drop(This->pcm);
556         snd_pcm_close(This->pcm);
557     }
558     This->pcm = pcm;
559     snd_pcm_prepare(This->pcm);
560     DSDB_CreateMMAP(This);
561     return S_OK;
562
563     err:
564     if (err < 0)
565         WARN("Failed to apply changes: %s\n", snd_strerror(err));
566
567     if (!This->pcm)
568         This->pcm = pcm;
569     else
570         snd_pcm_close(pcm);
571
572     if (This->pcm)
573         snd_pcm_hw_params_current(This->pcm, This->hw_params);
574
575     return DSERR_BADFORMAT;
576 }
577
578 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface, LPWAVEFORMATEX pwfx)
579 {
580     IDsDriverBufferImpl *This = impl_from_IDsDriverBuffer(iface);
581     HRESULT hr = S_OK;
582
583     TRACE("(%p, %p)\n", iface, pwfx);
584
585     /* **** */
586     EnterCriticalSection(&This->pcm_crst);
587     hr = SetFormat(This, pwfx);
588     /* **** */
589     LeaveCriticalSection(&This->pcm_crst);
590
591     if (hr == DS_OK)
592         return S_FALSE;
593     return hr;
594 }
595
596 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
597 {
598     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
599     FIXME("(%p,%d): stub\n",iface,dwFreq);
600     return S_OK;
601 }
602
603 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
604 {
605     IDsDriverBufferImpl *This = impl_from_IDsDriverBuffer(iface);
606     FIXME("(%p,%p): stub\n",This,pVolPan);
607     /* TODO: Bring volume control back */
608     return DS_OK;
609 }
610
611 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
612 {
613     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
614     /* I don't even think alsa allows this */
615     FIXME("(%p,%d): stub\n",iface,dwNewPos);
616     return DSERR_UNSUPPORTED;
617 }
618
619 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
620                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
621 {
622     IDsDriverBufferImpl *This = impl_from_IDsDriverBuffer(iface);
623     snd_pcm_uframes_t hw_pptr, hw_wptr;
624     snd_pcm_state_t state;
625
626     /* **** */
627     EnterCriticalSection(&This->pcm_crst);
628
629     if (!This->pcm)
630     {
631         FIXME("Bad pointer for pcm: %p\n", This->pcm);
632         LeaveCriticalSection(&This->pcm_crst);
633         return DSERR_GENERIC;
634     }
635
636     if (!lpdwPlay && !lpdwWrite)
637         CommitAll(This);
638
639     state = snd_pcm_state(This->pcm);
640
641     if (state != SND_PCM_STATE_PREPARED && state != SND_PCM_STATE_RUNNING)
642     {
643         CheckXRUN(This);
644         state = snd_pcm_state(This->pcm);
645     }
646     if (state == SND_PCM_STATE_RUNNING)
647     {
648         snd_pcm_sframes_t used = This->mmap_buflen_frames - snd_pcm_avail_update(This->pcm);
649
650         if (used < 0)
651         {
652             WARN("Underrun: %ld / %ld\n", used, snd_pcm_avail_update(This->pcm));
653             if (This->mmap)
654             {
655                 snd_pcm_forward(This->pcm, -used);
656                 This->mmap_pos += -used;
657                 This->mmap_pos %= This->mmap_buflen_frames;
658             }
659             used = 0;
660         }
661
662         if (This->mmap_pos > used)
663             hw_pptr = This->mmap_pos - used;
664         else
665             hw_pptr = This->mmap_buflen_frames + This->mmap_pos - used;
666         hw_pptr %= This->mmap_buflen_frames;
667
668         TRACE("At position: %ld (%ld) - Used %ld\n", hw_pptr, This->mmap_pos, used);
669     }
670     else hw_pptr = This->mmap_pos;
671     hw_wptr = This->mmap_pos;
672
673     LeaveCriticalSection(&This->pcm_crst);
674     /* **** */
675
676     if (lpdwPlay)
677         *lpdwPlay = snd_pcm_frames_to_bytes(This->pcm, hw_pptr);
678     if (lpdwWrite)
679         *lpdwWrite = snd_pcm_frames_to_bytes(This->pcm, hw_wptr);
680
681     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);
682     return DS_OK;
683 }
684
685 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
686 {
687     IDsDriverBufferImpl *This = impl_from_IDsDriverBuffer(iface);
688     TRACE("(%p,%x,%x,%x)\n",iface,dwRes1,dwRes2,dwFlags);
689
690     /* **** */
691     EnterCriticalSection(&This->pcm_crst);
692     snd_pcm_start(This->pcm);
693     /* **** */
694     LeaveCriticalSection(&This->pcm_crst);
695     return DS_OK;
696 }
697
698 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
699 {
700     const snd_pcm_channel_area_t *areas;
701     snd_pcm_uframes_t avail;
702     snd_pcm_format_t format;
703     IDsDriverBufferImpl *This = impl_from_IDsDriverBuffer(iface);
704     TRACE("(%p)\n",iface);
705
706     /* **** */
707     EnterCriticalSection(&This->pcm_crst);
708     avail = This->mmap_buflen_frames;
709     snd_pcm_drop(This->pcm);
710     snd_pcm_prepare(This->pcm);
711     avail = snd_pcm_avail_update(This->pcm);
712     snd_pcm_hw_params_get_format(This->hw_params, &format);
713     if (This->mmap)
714     {
715         snd_pcm_mmap_begin(This->pcm, &areas, &This->mmap_pos, &avail);
716         snd_pcm_format_set_silence(format, areas->addr, This->mmap_buflen_frames);
717         snd_pcm_mmap_commit(This->pcm, This->mmap_pos, 0);
718     }
719     else
720     {
721         snd_pcm_format_set_silence(format, This->mmap_buffer, This->mmap_buflen_frames);
722         snd_pcm_writei(This->pcm, This->mmap_buffer, This->mmap_buflen_frames);
723         This->mmap_pos = 0;
724     }
725
726     /* **** */
727     LeaveCriticalSection(&This->pcm_crst);
728     return DS_OK;
729 }
730
731 static const IDsDriverBufferVtbl dsdbvt =
732 {
733     IDsDriverBufferImpl_QueryInterface,
734     IDsDriverBufferImpl_AddRef,
735     IDsDriverBufferImpl_Release,
736     IDsDriverBufferImpl_Lock,
737     IDsDriverBufferImpl_Unlock,
738     IDsDriverBufferImpl_SetFormat,
739     IDsDriverBufferImpl_SetFrequency,
740     IDsDriverBufferImpl_SetVolumePan,
741     IDsDriverBufferImpl_SetPosition,
742     IDsDriverBufferImpl_GetPosition,
743     IDsDriverBufferImpl_Play,
744     IDsDriverBufferImpl_Stop
745 };
746
747 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
748 {
749     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
750     FIXME("(%p): stub!\n",iface);
751     return DSERR_UNSUPPORTED;
752 }
753
754 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
755 {
756     IDsDriverImpl *This = impl_from_IDsDriver(iface);
757     ULONG refCount = InterlockedIncrement(&This->ref);
758
759     TRACE("(%p)->(ref before=%u)\n",This, refCount - 1);
760
761     return refCount;
762 }
763
764 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
765 {
766     IDsDriverImpl *This = impl_from_IDsDriver(iface);
767     ULONG refCount = InterlockedDecrement(&This->ref);
768
769     TRACE("(%p)->(ref before=%u)\n",This, refCount + 1);
770
771     if (refCount)
772         return refCount;
773
774     HeapFree(GetProcessHeap(), 0, This);
775     return 0;
776 }
777
778 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
779 {
780     IDsDriverImpl *This = impl_from_IDsDriver(iface);
781     TRACE("(%p,%p)\n",iface,pDesc);
782     *pDesc                      = WOutDev[This->wDevID].ds_desc;
783     pDesc->dwFlags              = DSDDESC_DONTNEEDSECONDARYLOCK | DSDDESC_DONTNEEDWRITELEAD;
784     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
785     pDesc->wVxdId               = 0;
786     pDesc->wReserved            = 0;
787     pDesc->ulDeviceNum          = This->wDevID;
788     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
789     pDesc->pvDirectDrawHeap     = NULL;
790     pDesc->dwMemStartAddress    = 0xDEAD0000;
791     pDesc->dwMemEndAddress      = 0xDEAF0000;
792     pDesc->dwMemAllocExtra      = 0;
793     pDesc->pvReserved1          = NULL;
794     pDesc->pvReserved2          = NULL;
795     return DS_OK;
796 }
797
798 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
799 {
800     HRESULT hr = S_OK;
801     IDsDriverImpl *This = impl_from_IDsDriver(iface);
802     int err=0;
803     snd_pcm_t *pcm = NULL;
804     snd_pcm_hw_params_t *hw_params;
805
806     /* While this is not really needed, it is a good idea to do this,
807      * to see if sound can be initialized */
808
809     hw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof());
810
811     if (!hw_params)
812     {
813         hr = DSERR_OUTOFMEMORY;
814         goto unalloc;
815     }
816
817     err = snd_pcm_open(&pcm, WOutDev[This->wDevID].pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
818     if (err < 0) goto err;
819     err = snd_pcm_hw_params_any(pcm, hw_params);
820     if (err < 0) goto err;
821     err = snd_pcm_hw_params_set_access (pcm, hw_params, SND_PCM_ACCESS_MMAP_INTERLEAVED);
822     if (err < 0)
823         err = snd_pcm_hw_params_set_access (pcm, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
824     if (err < 0) goto err;
825
826     TRACE("Success\n");
827     snd_pcm_close(pcm);
828     goto unalloc;
829
830     err:
831     hr = DSERR_GENERIC;
832     FIXME("Failed to open device: %s\n", snd_strerror(err));
833     if (pcm)
834         snd_pcm_close(pcm);
835     unalloc:
836     HeapFree(GetProcessHeap(), 0, hw_params);
837     if (hr != S_OK)
838         WARN("--> %08x\n", hr);
839     return hr;
840 }
841
842 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
843 {
844     IDsDriverImpl *This = impl_from_IDsDriver(iface);
845     TRACE("(%p) stub, harmless\n",This);
846     return DS_OK;
847 }
848
849 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
850 {
851     IDsDriverImpl *This = impl_from_IDsDriver(iface);
852     TRACE("(%p,%p)\n",iface,pCaps);
853     *pCaps = WOutDev[This->wDevID].ds_caps;
854     return DS_OK;
855 }
856
857 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
858                                                       LPWAVEFORMATEX pwfx,
859                                                       DWORD dwFlags, DWORD dwCardAddress,
860                                                       LPDWORD pdwcbBufferSize,
861                                                       LPBYTE *ppbBuffer,
862                                                       LPVOID *ppvObj)
863 {
864     IDsDriverImpl *This = impl_from_IDsDriver(iface);
865     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
866     HRESULT err;
867
868     TRACE("(%p,%p,%x,%x)\n",iface,pwfx,dwFlags,dwCardAddress);
869     /* we only support primary buffers... for now */
870     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
871         return DSERR_UNSUPPORTED;
872     if (This->primary)
873         return DSERR_ALLOCATED;
874
875     *ippdsdb = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDsDriverBufferImpl));
876     if (*ippdsdb == NULL)
877         return DSERR_OUTOFMEMORY;
878
879     (*ippdsdb)->hw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof());
880     (*ippdsdb)->sw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_sw_params_sizeof());
881     if (!(*ippdsdb)->hw_params || !(*ippdsdb)->sw_params)
882     {
883         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->sw_params);
884         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->hw_params);
885         return DSERR_OUTOFMEMORY;
886     }
887     (*ippdsdb)->IDsDriverBuffer_iface.lpVtbl = &dsdbvt;
888     (*ippdsdb)->ref     = 1;
889     (*ippdsdb)->drv     = This;
890     InitializeCriticalSection(&(*ippdsdb)->pcm_crst);
891     (*ippdsdb)->pcm_crst.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ALSA_DSOUTPUT.pcm_crst");
892
893     /* SetFormat has to re-initialize pcm here anyway */
894     err = SetFormat(*ippdsdb, pwfx);
895     if (FAILED(err))
896     {
897         WARN("Error occurred: %08x\n", err);
898         goto err;
899     }
900
901     if (dwFlags & DSBCAPS_PRIMARYBUFFER)
902         This->primary = *ippdsdb;
903
904     *pdwcbBufferSize = (*ippdsdb)->mmap_buflen_bytes;
905     *ppbBuffer = (*ippdsdb)->mmap_buffer;
906
907     /* buffer is ready to go */
908     TRACE("buffer created at %p\n", *ippdsdb);
909     return err;
910
911     err:
912     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->sw_params);
913     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->hw_params);
914     HeapFree(GetProcessHeap(), 0, *ippdsdb);
915     *ippdsdb = NULL;
916     return err;
917 }
918
919 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
920                                                          PIDSDRIVERBUFFER pBuffer,
921                                                          LPVOID *ppvObj)
922 {
923     IDsDriverImpl *This = impl_from_IDsDriver(iface);
924     FIXME("(%p,%p): stub\n",This,pBuffer);
925     return DSERR_INVALIDCALL;
926 }
927
928 static const IDsDriverVtbl dsdvt =
929 {
930     IDsDriverImpl_QueryInterface,
931     IDsDriverImpl_AddRef,
932     IDsDriverImpl_Release,
933     IDsDriverImpl_GetDriverDesc,
934     IDsDriverImpl_Open,
935     IDsDriverImpl_Close,
936     IDsDriverImpl_GetCaps,
937     IDsDriverImpl_CreateSoundBuffer,
938     IDsDriverImpl_DuplicateSoundBuffer
939 };
940
941 DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
942 {
943     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
944
945     TRACE("driver created\n");
946
947     *idrv = HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
948     if (!*idrv)
949         return MMSYSERR_NOMEM;
950     (*idrv)->IDsDriver_iface.lpVtbl = &dsdvt;
951     (*idrv)->ref        = 1;
952
953     (*idrv)->wDevID     = wDevID;
954     (*idrv)->primary    = NULL;
955     return MMSYSERR_NOERROR;
956 }
957
958 DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
959 {
960     *desc = WOutDev[wDevID].ds_desc;
961     return MMSYSERR_NOERROR;
962 }