hlink: Use HLINKSETF flags in Hlink::fnSetMonikerReference.
[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                 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     err = snd_pcm_sw_params(pcm, This->sw_params);
540     snd_pcm_prepare(pcm);
541
542     /* ALSA needs at least 3 buffers to work successfully */
543     This->mmap_commitahead = 3 * psize;
544     while (This->mmap_commitahead <= 512)
545         This->mmap_commitahead += psize;
546
547     if (This->pcm)
548     {
549         snd_pcm_drop(This->pcm);
550         snd_pcm_close(This->pcm);
551     }
552     This->pcm = pcm;
553     snd_pcm_prepare(This->pcm);
554     DSDB_CreateMMAP(This);
555     return S_OK;
556
557     err:
558     if (err < 0)
559         WARN("Failed to apply changes: %s\n", snd_strerror(err));
560
561     if (!This->pcm)
562         This->pcm = pcm;
563     else
564         snd_pcm_close(pcm);
565
566     if (This->pcm)
567         snd_pcm_hw_params_current(This->pcm, This->hw_params);
568
569     return DSERR_BADFORMAT;
570 }
571
572 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface, LPWAVEFORMATEX pwfx)
573 {
574     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
575     HRESULT hr = S_OK;
576
577     TRACE("(%p, %p)\n", iface, pwfx);
578
579     /* **** */
580     EnterCriticalSection(&This->pcm_crst);
581     hr = SetFormat(This, pwfx);
582     /* **** */
583     LeaveCriticalSection(&This->pcm_crst);
584
585     if (hr == DS_OK)
586         return S_FALSE;
587     return hr;
588 }
589
590 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
591 {
592     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
593     FIXME("(%p,%d): stub\n",iface,dwFreq);
594     return S_OK;
595 }
596
597 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
598 {
599     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
600     FIXME("(%p,%p): stub\n",This,pVolPan);
601     /* TODO: Bring volume control back */
602     return DS_OK;
603 }
604
605 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
606 {
607     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
608     /* I don't even think alsa allows this */
609     FIXME("(%p,%d): stub\n",iface,dwNewPos);
610     return DSERR_UNSUPPORTED;
611 }
612
613 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
614                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
615 {
616     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
617     snd_pcm_uframes_t hw_pptr, hw_wptr;
618     snd_pcm_state_t state;
619
620     /* **** */
621     EnterCriticalSection(&This->pcm_crst);
622
623     if (!This->pcm)
624     {
625         FIXME("Bad pointer for pcm: %p\n", This->pcm);
626         LeaveCriticalSection(&This->pcm_crst);
627         return DSERR_GENERIC;
628     }
629
630     if (!lpdwPlay && !lpdwWrite)
631         CommitAll(This);
632
633     state = snd_pcm_state(This->pcm);
634
635     if (state != SND_PCM_STATE_PREPARED && state != SND_PCM_STATE_RUNNING)
636     {
637         CheckXRUN(This);
638         state = snd_pcm_state(This->pcm);
639     }
640     if (state == SND_PCM_STATE_RUNNING)
641     {
642         snd_pcm_sframes_t used = This->mmap_buflen_frames - snd_pcm_avail_update(This->pcm);
643
644         if (used < 0)
645         {
646             WARN("Underrun: %ld / %ld\n", used, snd_pcm_avail_update(This->pcm));
647             if (This->mmap)
648             {
649                 snd_pcm_forward(This->pcm, -used);
650                 This->mmap_pos += -used;
651                 This->mmap_pos %= This->mmap_buflen_frames;
652             }
653             used = 0;
654         }
655
656         if (This->mmap_pos > used)
657             hw_pptr = This->mmap_pos - used;
658         else
659             hw_pptr = This->mmap_buflen_frames + This->mmap_pos - used;
660         hw_pptr %= This->mmap_buflen_frames;
661
662         TRACE("At position: %ld (%ld) - Used %ld\n", hw_pptr, This->mmap_pos, used);
663     }
664     else hw_pptr = This->mmap_pos;
665     hw_wptr = This->mmap_pos;
666
667     LeaveCriticalSection(&This->pcm_crst);
668     /* **** */
669
670     if (lpdwPlay)
671         *lpdwPlay = snd_pcm_frames_to_bytes(This->pcm, hw_pptr);
672     if (lpdwWrite)
673         *lpdwWrite = snd_pcm_frames_to_bytes(This->pcm, hw_wptr);
674
675     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);
676     return DS_OK;
677 }
678
679 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
680 {
681     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
682     TRACE("(%p,%x,%x,%x)\n",iface,dwRes1,dwRes2,dwFlags);
683
684     /* **** */
685     EnterCriticalSection(&This->pcm_crst);
686     snd_pcm_start(This->pcm);
687     /* **** */
688     LeaveCriticalSection(&This->pcm_crst);
689     return DS_OK;
690 }
691
692 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
693 {
694     const snd_pcm_channel_area_t *areas;
695     snd_pcm_uframes_t avail;
696     snd_pcm_format_t format;
697     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
698     TRACE("(%p)\n",iface);
699
700     /* **** */
701     EnterCriticalSection(&This->pcm_crst);
702     avail = This->mmap_buflen_frames;
703     snd_pcm_drop(This->pcm);
704     snd_pcm_prepare(This->pcm);
705     avail = snd_pcm_avail_update(This->pcm);
706     snd_pcm_hw_params_get_format(This->hw_params, &format);
707     if (This->mmap)
708     {
709         snd_pcm_mmap_begin(This->pcm, &areas, &This->mmap_pos, &avail);
710         snd_pcm_format_set_silence(format, areas->addr, This->mmap_buflen_frames);
711         snd_pcm_mmap_commit(This->pcm, This->mmap_pos, 0);
712     }
713     else
714     {
715         snd_pcm_format_set_silence(format, This->mmap_buffer, This->mmap_buflen_frames);
716         snd_pcm_writei(This->pcm, This->mmap_buffer, This->mmap_buflen_frames);
717         This->mmap_pos = 0;
718     }
719
720     /* **** */
721     LeaveCriticalSection(&This->pcm_crst);
722     return DS_OK;
723 }
724
725 static const IDsDriverBufferVtbl dsdbvt =
726 {
727     IDsDriverBufferImpl_QueryInterface,
728     IDsDriverBufferImpl_AddRef,
729     IDsDriverBufferImpl_Release,
730     IDsDriverBufferImpl_Lock,
731     IDsDriverBufferImpl_Unlock,
732     IDsDriverBufferImpl_SetFormat,
733     IDsDriverBufferImpl_SetFrequency,
734     IDsDriverBufferImpl_SetVolumePan,
735     IDsDriverBufferImpl_SetPosition,
736     IDsDriverBufferImpl_GetPosition,
737     IDsDriverBufferImpl_Play,
738     IDsDriverBufferImpl_Stop
739 };
740
741 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
742 {
743     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
744     FIXME("(%p): stub!\n",iface);
745     return DSERR_UNSUPPORTED;
746 }
747
748 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
749 {
750     IDsDriverImpl *This = (IDsDriverImpl *)iface;
751     ULONG refCount = InterlockedIncrement(&This->ref);
752
753     TRACE("(%p)->(ref before=%u)\n",This, refCount - 1);
754
755     return refCount;
756 }
757
758 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
759 {
760     IDsDriverImpl *This = (IDsDriverImpl *)iface;
761     ULONG refCount = InterlockedDecrement(&This->ref);
762
763     TRACE("(%p)->(ref before=%u)\n",This, refCount + 1);
764
765     if (refCount)
766         return refCount;
767
768     HeapFree(GetProcessHeap(), 0, This);
769     return 0;
770 }
771
772 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
773 {
774     IDsDriverImpl *This = (IDsDriverImpl *)iface;
775     TRACE("(%p,%p)\n",iface,pDesc);
776     *pDesc                      = WOutDev[This->wDevID].ds_desc;
777     pDesc->dwFlags              = DSDDESC_DONTNEEDSECONDARYLOCK | DSDDESC_DONTNEEDWRITELEAD;
778     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
779     pDesc->wVxdId               = 0;
780     pDesc->wReserved            = 0;
781     pDesc->ulDeviceNum          = This->wDevID;
782     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
783     pDesc->pvDirectDrawHeap     = NULL;
784     pDesc->dwMemStartAddress    = 0xDEAD0000;
785     pDesc->dwMemEndAddress      = 0xDEAF0000;
786     pDesc->dwMemAllocExtra      = 0;
787     pDesc->pvReserved1          = NULL;
788     pDesc->pvReserved2          = NULL;
789     return DS_OK;
790 }
791
792 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
793 {
794     HRESULT hr = S_OK;
795     IDsDriverImpl *This = (IDsDriverImpl *)iface;
796     int err=0;
797     snd_pcm_t *pcm = NULL;
798     snd_pcm_hw_params_t *hw_params;
799
800     /* While this is not really needed, it is a good idea to do this,
801      * to see if sound can be initialized */
802
803     hw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof());
804
805     if (!hw_params)
806     {
807         hr = DSERR_OUTOFMEMORY;
808         goto unalloc;
809     }
810
811     err = snd_pcm_open(&pcm, WOutDev[This->wDevID].pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
812     if (err < 0) goto err;
813     err = snd_pcm_hw_params_any(pcm, hw_params);
814     if (err < 0) goto err;
815     err = snd_pcm_hw_params_set_access (pcm, hw_params, SND_PCM_ACCESS_MMAP_INTERLEAVED);
816     if (err < 0)
817         err = snd_pcm_hw_params_set_access (pcm, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
818     if (err < 0) goto err;
819
820     TRACE("Success\n");
821     snd_pcm_close(pcm);
822     goto unalloc;
823
824     err:
825     hr = DSERR_GENERIC;
826     FIXME("Failed to open device: %s\n", snd_strerror(err));
827     if (pcm)
828         snd_pcm_close(pcm);
829     unalloc:
830     HeapFree(GetProcessHeap(), 0, hw_params);
831     if (hr != S_OK)
832         WARN("--> %08x\n", hr);
833     return hr;
834 }
835
836 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
837 {
838     IDsDriverImpl *This = (IDsDriverImpl *)iface;
839     TRACE("(%p) stub, harmless\n",This);
840     return DS_OK;
841 }
842
843 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
844 {
845     IDsDriverImpl *This = (IDsDriverImpl *)iface;
846     TRACE("(%p,%p)\n",iface,pCaps);
847     *pCaps = WOutDev[This->wDevID].ds_caps;
848     return DS_OK;
849 }
850
851 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
852                                                       LPWAVEFORMATEX pwfx,
853                                                       DWORD dwFlags, DWORD dwCardAddress,
854                                                       LPDWORD pdwcbBufferSize,
855                                                       LPBYTE *ppbBuffer,
856                                                       LPVOID *ppvObj)
857 {
858     IDsDriverImpl *This = (IDsDriverImpl *)iface;
859     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
860     HRESULT err;
861
862     TRACE("(%p,%p,%x,%x)\n",iface,pwfx,dwFlags,dwCardAddress);
863     /* we only support primary buffers... for now */
864     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
865         return DSERR_UNSUPPORTED;
866     if (This->primary)
867         return DSERR_ALLOCATED;
868
869     *ippdsdb = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDsDriverBufferImpl));
870     if (*ippdsdb == NULL)
871         return DSERR_OUTOFMEMORY;
872
873     (*ippdsdb)->hw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof());
874     (*ippdsdb)->sw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_sw_params_sizeof());
875     if (!(*ippdsdb)->hw_params || !(*ippdsdb)->sw_params)
876     {
877         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->sw_params);
878         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->hw_params);
879         return DSERR_OUTOFMEMORY;
880     }
881     (*ippdsdb)->lpVtbl  = &dsdbvt;
882     (*ippdsdb)->ref     = 1;
883     (*ippdsdb)->drv     = This;
884     InitializeCriticalSection(&(*ippdsdb)->pcm_crst);
885     (*ippdsdb)->pcm_crst.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ALSA_DSOUTPUT.pcm_crst");
886
887     /* SetFormat has to re-initialize pcm here anyway */
888     err = SetFormat(*ippdsdb, pwfx);
889     if (FAILED(err))
890     {
891         WARN("Error occurred: %08x\n", err);
892         goto err;
893     }
894
895     if (dwFlags & DSBCAPS_PRIMARYBUFFER)
896         This->primary = *ippdsdb;
897
898     *pdwcbBufferSize = (*ippdsdb)->mmap_buflen_bytes;
899     *ppbBuffer = (*ippdsdb)->mmap_buffer;
900
901     /* buffer is ready to go */
902     TRACE("buffer created at %p\n", *ippdsdb);
903     return err;
904
905     err:
906     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->sw_params);
907     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->hw_params);
908     HeapFree(GetProcessHeap(), 0, *ippdsdb);
909     *ippdsdb = NULL;
910     return err;
911 }
912
913 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
914                                                          PIDSDRIVERBUFFER pBuffer,
915                                                          LPVOID *ppvObj)
916 {
917     IDsDriverImpl *This = (IDsDriverImpl *)iface;
918     FIXME("(%p,%p): stub\n",This,pBuffer);
919     return DSERR_INVALIDCALL;
920 }
921
922 static const IDsDriverVtbl dsdvt =
923 {
924     IDsDriverImpl_QueryInterface,
925     IDsDriverImpl_AddRef,
926     IDsDriverImpl_Release,
927     IDsDriverImpl_GetDriverDesc,
928     IDsDriverImpl_Open,
929     IDsDriverImpl_Close,
930     IDsDriverImpl_GetCaps,
931     IDsDriverImpl_CreateSoundBuffer,
932     IDsDriverImpl_DuplicateSoundBuffer
933 };
934
935 DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
936 {
937     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
938
939     TRACE("driver created\n");
940
941     *idrv = HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
942     if (!*idrv)
943         return MMSYSERR_NOMEM;
944     (*idrv)->lpVtbl     = &dsdvt;
945     (*idrv)->ref        = 1;
946
947     (*idrv)->wDevID     = wDevID;
948     (*idrv)->primary    = NULL;
949     return MMSYSERR_NOERROR;
950 }
951
952 DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
953 {
954     *desc = WOutDev[wDevID].ds_desc;
955     return MMSYSERR_NOERROR;
956 }
957
958 #endif /* HAVE_ALSA */