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