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