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