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