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