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