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