winalsa.drv: Explicitly include assert.h.
[wine] / dlls / winealsa.drv / dscapture.c
1 /*
2  * Sample Wine Driver for Advanced Linux Sound System (ALSA)
3  *      Based on version <final> of the ALSA API
4  *
5  * Copyright 2007 - Maarten Lankhorst
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 /*======================================================================*
23  *              Low level dsound input implementation                   *
24  *======================================================================*/
25
26 #include "config.h"
27 #include "wine/port.h"
28
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <string.h>
33 #ifdef HAVE_UNISTD_H
34 # include <unistd.h>
35 #endif
36 #include <errno.h>
37 #include <limits.h>
38 #include <fcntl.h>
39 #ifdef HAVE_SYS_IOCTL_H
40 # include <sys/ioctl.h>
41 #endif
42 #ifdef HAVE_SYS_MMAN_H
43 # include <sys/mman.h>
44 #endif
45 #include "windef.h"
46 #include "winbase.h"
47 #include "wingdi.h"
48 #include "winerror.h"
49 #include "winuser.h"
50 #include "mmddk.h"
51
52 #include "alsa.h"
53 #include "wine/library.h"
54 #include "wine/unicode.h"
55 #include "wine/debug.h"
56
57 #ifdef HAVE_ALSA
58
59 /* Notify timer checks every 10 ms with a resolution of 2 ms */
60 #define DS_TIME_DEL 10
61 #define DS_TIME_RES 2
62
63 WINE_DEFAULT_DEBUG_CHANNEL(dsalsa);
64
65 typedef struct IDsCaptureDriverBufferImpl IDsCaptureDriverBufferImpl;
66
67 typedef struct IDsCaptureDriverImpl
68 {
69     const IDsCaptureDriverVtbl *lpVtbl;
70     LONG ref;
71     IDsCaptureDriverBufferImpl* capture_buffer;
72     UINT wDevID;
73 } IDsCaptureDriverImpl;
74
75 typedef struct IDsCaptureDriverNotifyImpl
76 {
77     const IDsDriverNotifyVtbl *lpVtbl;
78     LONG ref;
79     IDsCaptureDriverBufferImpl *buffer;
80     DSBPOSITIONNOTIFY *notifies;
81     DWORD nrofnotifies, playpos;
82     UINT timerID;
83 } IDsCaptureDriverNotifyImpl;
84
85 struct IDsCaptureDriverBufferImpl
86 {
87     const IDsCaptureDriverBufferVtbl *lpVtbl;
88     LONG ref;
89     IDsCaptureDriverImpl *drv;
90     IDsCaptureDriverNotifyImpl *notify;
91
92     CRITICAL_SECTION pcm_crst;
93     LPBYTE mmap_buffer, presented_buffer;
94     DWORD mmap_buflen_bytes, play_looping, mmap_ofs_bytes;
95
96     /* Note: snd_pcm_frames_to_bytes(This->pcm, mmap_buflen_frames) != mmap_buflen_bytes */
97     /* The actual buffer may differ in size from the wanted buffer size */
98
99     snd_pcm_t *pcm;
100     snd_pcm_hw_params_t *hw_params;
101     snd_pcm_sw_params_t *sw_params;
102     snd_pcm_uframes_t mmap_buflen_frames, mmap_pos;
103 };
104
105 static void Capture_CheckNotify(IDsCaptureDriverNotifyImpl *This, DWORD from, DWORD len)
106 {
107     unsigned i;
108     for (i = 0; i < This->nrofnotifies; ++i) {
109         LPDSBPOSITIONNOTIFY event = This->notifies + i;
110         DWORD offset = event->dwOffset;
111         TRACE("checking %d, position %d, event = %p\n", i, offset, event->hEventNotify);
112
113         if (offset == DSBPN_OFFSETSTOP) {
114             if (!from && !len) {
115                 SetEvent(event->hEventNotify);
116                 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
117                 return;
118             }
119             else return;
120         }
121
122         if (offset >= from && offset < (from + len))
123         {
124             TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
125             SetEvent(event->hEventNotify);
126         }
127     }
128 }
129
130 static void CALLBACK Capture_Notify(UINT timerID, UINT msg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
131 {
132     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)dwUser;
133     DWORD last_playpos, playpos;
134     PIDSCDRIVERBUFFER iface = (PIDSCDRIVERBUFFER)This;
135
136     /* **** */
137     EnterCriticalSection(&This->pcm_crst);
138
139     IDsDriverBuffer_GetPosition(iface, &playpos, NULL);
140     last_playpos = This->notify->playpos;
141     This->notify->playpos = playpos;
142
143     if (snd_pcm_state(This->pcm) != SND_PCM_STATE_RUNNING || last_playpos == playpos || !This->notify->nrofnotifies || !This->notify->notifies)
144         goto done;
145
146     if (playpos < last_playpos)
147     {
148         Capture_CheckNotify(This->notify, last_playpos, This->mmap_buflen_bytes);
149         if (playpos)
150             Capture_CheckNotify(This->notify, 0, playpos);
151     }
152     else Capture_CheckNotify(This->notify, last_playpos, playpos - last_playpos);
153
154 done:
155     LeaveCriticalSection(&This->pcm_crst);
156     /* **** */
157 }
158
159 static HRESULT WINAPI IDsCaptureDriverNotifyImpl_QueryInterface(PIDSDRIVERNOTIFY iface, REFIID riid, LPVOID *ppobj)
160 {
161     IDsCaptureDriverNotifyImpl *This = (IDsCaptureDriverNotifyImpl *)iface;
162     TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
163
164     if ( IsEqualGUID(riid, &IID_IUnknown) ||
165          IsEqualGUID(riid, &IID_IDsDriverNotify) ) {
166         IDsDriverNotify_AddRef(iface);
167         *ppobj = This;
168         return DS_OK;
169     }
170
171     FIXME( "Unknown IID %s\n", debugstr_guid(riid));
172
173     *ppobj = 0;
174     return E_NOINTERFACE;
175 }
176
177 static ULONG WINAPI IDsCaptureDriverNotifyImpl_AddRef(PIDSDRIVERNOTIFY iface)
178 {
179     IDsCaptureDriverNotifyImpl *This = (IDsCaptureDriverNotifyImpl *)iface;
180     ULONG refCount = InterlockedIncrement(&This->ref);
181
182     TRACE("(%p) ref was %d\n", This, refCount - 1);
183
184     return refCount;
185 }
186
187 static ULONG WINAPI IDsCaptureDriverNotifyImpl_Release(PIDSDRIVERNOTIFY iface)
188 {
189     IDsCaptureDriverNotifyImpl *This = (IDsCaptureDriverNotifyImpl *)iface;
190     ULONG refCount = InterlockedDecrement(&This->ref);
191
192     TRACE("(%p) ref was %d\n", This, refCount + 1);
193
194     if (!refCount) {
195         This->buffer->notify = NULL;
196         if (This->timerID)
197         {
198             timeKillEvent(This->timerID);
199             timeEndPeriod(DS_TIME_RES);
200         }
201         HeapFree(GetProcessHeap(), 0, This->notifies);
202         HeapFree(GetProcessHeap(), 0, This);
203         TRACE("(%p) released\n", This);
204     }
205     return refCount;
206 }
207
208 static HRESULT WINAPI IDsCaptureDriverNotifyImpl_SetNotificationPositions(PIDSDRIVERNOTIFY iface, DWORD howmuch, LPCDSBPOSITIONNOTIFY notify)
209 {
210     DWORD len = howmuch * sizeof(DSBPOSITIONNOTIFY);
211     unsigned i;
212     LPVOID notifies;
213     IDsCaptureDriverNotifyImpl *This = (IDsCaptureDriverNotifyImpl *)iface;
214     TRACE("(%p,0x%08x,%p)\n",This,howmuch,notify);
215
216     if (!notify) {
217         WARN("invalid parameter\n");
218         return DSERR_INVALIDPARAM;
219     }
220
221     if (TRACE_ON(dsalsa))
222         for (i=0;i<howmuch; ++i)
223             TRACE("notify at %d to %p\n", notify[i].dwOffset, notify[i].hEventNotify);
224
225     /* **** */
226     EnterCriticalSection(&This->buffer->pcm_crst);
227
228     /* Make an internal copy of the caller-supplied array.
229      * Replace the existing copy if one is already present. */
230     if (This->notifies)
231         notifies = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, This->notifies, len);
232     else
233         notifies = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len);
234
235     if (!notifies)
236     {
237         LeaveCriticalSection(&This->buffer->pcm_crst);
238         /* **** */
239         return DSERR_OUTOFMEMORY;
240     }
241     This->notifies = notifies;
242     memcpy(This->notifies, notify, len);
243     This->nrofnotifies = howmuch;
244     IDsDriverBuffer_GetPosition((PIDSCDRIVERBUFFER)This->buffer, &This->playpos, NULL);
245
246     if (!This->timerID)
247     {
248         timeBeginPeriod(DS_TIME_RES);
249         This->timerID = timeSetEvent(DS_TIME_DEL, DS_TIME_RES, Capture_Notify, (DWORD_PTR)This->buffer, TIME_PERIODIC | TIME_KILL_SYNCHRONOUS);
250     }
251
252     LeaveCriticalSection(&This->buffer->pcm_crst);
253     /* **** */
254
255     return S_OK;
256 }
257
258 static const IDsDriverNotifyVtbl dscdnvt =
259 {
260     IDsCaptureDriverNotifyImpl_QueryInterface,
261     IDsCaptureDriverNotifyImpl_AddRef,
262     IDsCaptureDriverNotifyImpl_Release,
263     IDsCaptureDriverNotifyImpl_SetNotificationPositions,
264 };
265
266 #if 0
267 /** Convert the position an application sees into a position ALSA sees */
268 static snd_pcm_uframes_t fakepos_to_realpos(const IDsCaptureDriverBufferImpl* This, DWORD fakepos)
269 {
270     snd_pcm_uframes_t realpos;
271     if (fakepos < This->mmap_ofs_bytes)
272         realpos = This->mmap_buflen_bytes + fakepos - This->mmap_ofs_bytes;
273     else realpos = fakepos - This->mmap_ofs_bytes;
274     return snd_pcm_bytes_to_frames(This->pcm, realpos) % This->mmap_buflen_frames;
275 }
276 #endif
277
278 /** Convert the position ALSA sees into a position an application sees */
279 static DWORD realpos_to_fakepos(const IDsCaptureDriverBufferImpl* This, snd_pcm_uframes_t realpos)
280 {
281     DWORD realposb = snd_pcm_frames_to_bytes(This->pcm, realpos);
282     return (realposb + This->mmap_ofs_bytes) % This->mmap_buflen_bytes;
283 }
284
285 /** Raw copy data, with buffer wrap around */
286 static void CopyDataWrap(const IDsCaptureDriverBufferImpl* This, LPBYTE dest, DWORD fromwhere, DWORD copylen, DWORD buflen)
287 {
288     DWORD remainder = buflen - fromwhere;
289     if (remainder >= copylen)
290     {
291         CopyMemory(dest, This->mmap_buffer + fromwhere, copylen);
292     }
293     else
294     {
295         CopyMemory(dest, This->mmap_buffer + fromwhere, remainder);
296         copylen -= remainder;
297         CopyMemory(dest, This->mmap_buffer, copylen);
298     }
299 }
300
301 /** Copy data from the mmap buffer to backbuffer, taking into account all wraparounds that may occur */
302 static void CopyData(const IDsCaptureDriverBufferImpl* This, snd_pcm_uframes_t fromwhere, snd_pcm_uframes_t len)
303 {
304     DWORD dlen = snd_pcm_frames_to_bytes(This->pcm, len) % This->mmap_buflen_bytes;
305
306     /* Backbuffer */
307     DWORD ofs = realpos_to_fakepos(This, fromwhere);
308     DWORD remainder = This->mmap_buflen_bytes - ofs;
309
310     /* MMAP buffer */
311     DWORD realbuflen = snd_pcm_frames_to_bytes(This->pcm, This->mmap_buflen_frames);
312     DWORD realofs = snd_pcm_frames_to_bytes(This->pcm, fromwhere);
313
314     if (remainder >= dlen)
315     {
316        CopyDataWrap(This, This->presented_buffer + ofs, realofs, dlen, realbuflen);
317     }
318     else
319     {
320        CopyDataWrap(This, This->presented_buffer + ofs, realofs, remainder, realbuflen);
321        dlen -= remainder;
322        CopyDataWrap(This, This->presented_buffer, (realofs+remainder)%realbuflen, dlen, realbuflen);
323     }
324 }
325
326 /** Fill buffers, for starting and stopping
327  * Alsa won't start playing until everything is filled up
328  * This also updates mmap_pos
329  *
330  * Returns: Amount of periods in use so snd_pcm_avail_update
331  * doesn't have to be called up to 4x in GetPosition()
332  */
333 static snd_pcm_uframes_t CommitAll(IDsCaptureDriverBufferImpl *This, DWORD forced)
334 {
335     const snd_pcm_channel_area_t *areas;
336     snd_pcm_uframes_t used;
337     const snd_pcm_uframes_t commitahead = This->mmap_buflen_frames;
338
339     used = This->mmap_buflen_frames - snd_pcm_avail_update(This->pcm);
340     TRACE("%p needs to commit to %lu, used: %lu\n", This, commitahead, used);
341     if (used < commitahead && (forced || This->play_looping))
342     {
343         snd_pcm_uframes_t done, putin = commitahead - used;
344         snd_pcm_mmap_begin(This->pcm, &areas, &This->mmap_pos, &putin);
345         CopyData(This, This->mmap_pos, putin);
346         done = snd_pcm_mmap_commit(This->pcm, This->mmap_pos, putin);
347         This->mmap_pos += done;
348         used += done;
349         putin = commitahead - used;
350
351         if (This->mmap_pos == This->mmap_buflen_frames && (snd_pcm_sframes_t)putin > 0 && This->play_looping)
352         {
353             snd_pcm_mmap_begin(This->pcm, &areas, &This->mmap_pos, &putin);
354             This->mmap_ofs_bytes += snd_pcm_frames_to_bytes(This->pcm, This->mmap_buflen_frames);
355             This->mmap_ofs_bytes %= This->mmap_buflen_bytes;
356             CopyData(This, This->mmap_pos, putin);
357             done = snd_pcm_mmap_commit(This->pcm, This->mmap_pos, putin);
358             This->mmap_pos += done;
359             used += done;
360         }
361     }
362
363     if (This->mmap_pos == This->mmap_buflen_frames)
364     {
365         This->mmap_ofs_bytes += snd_pcm_frames_to_bytes(This->pcm, This->mmap_buflen_frames);
366         This->mmap_ofs_bytes %= This->mmap_buflen_bytes;
367         This->mmap_pos = 0;
368     }
369
370     return used;
371 }
372
373 static void CheckXRUN(IDsCaptureDriverBufferImpl* This)
374 {
375     snd_pcm_state_t state = snd_pcm_state(This->pcm);
376     snd_pcm_sframes_t delay;
377     int err;
378
379     snd_pcm_hwsync(This->pcm);
380     snd_pcm_delay(This->pcm, &delay);
381     if ( state == SND_PCM_STATE_XRUN )
382     {
383         err = snd_pcm_prepare(This->pcm);
384         CommitAll(This, FALSE);
385         snd_pcm_start(This->pcm);
386         WARN("xrun occurred\n");
387         if ( err < 0 )
388             ERR("recovery from xrun failed, prepare failed: %s\n", snd_strerror(err));
389     }
390     else if ( state == SND_PCM_STATE_SUSPENDED )
391     {
392         int err = snd_pcm_resume(This->pcm);
393         TRACE("recovery from suspension occurred\n");
394         if (err < 0 && err != -EAGAIN){
395             err = snd_pcm_prepare(This->pcm);
396             if (err < 0)
397                 ERR("recovery from suspend failed, prepare failed: %s\n", snd_strerror(err));
398         }
399     }
400     else if ( state != SND_PCM_STATE_RUNNING)
401     {
402         WARN("Unhandled state: %d\n", state);
403     }
404 }
405
406 /**
407  * Allocate the memory-mapped buffer for direct sound, and set up the
408  * callback.
409  */
410 static int CreateMMAP(IDsCaptureDriverBufferImpl* pdbi)
411 {
412     snd_pcm_t *pcm = pdbi->pcm;
413     snd_pcm_format_t format;
414     snd_pcm_uframes_t frames, ofs, avail, psize, boundary;
415     unsigned int channels, bits_per_sample, bits_per_frame;
416     int err, mmap_mode;
417     const snd_pcm_channel_area_t *areas;
418     snd_pcm_hw_params_t *hw_params = pdbi->hw_params;
419     snd_pcm_sw_params_t *sw_params = pdbi->sw_params;
420
421     mmap_mode = snd_pcm_type(pcm);
422
423     if (mmap_mode == SND_PCM_TYPE_HW)
424         TRACE("mmap'd buffer is a direct hardware buffer.\n");
425     else if (mmap_mode == SND_PCM_TYPE_DMIX)
426         TRACE("mmap'd buffer is an ALSA dmix buffer\n");
427     else
428         TRACE("mmap'd buffer is an ALSA type %d buffer\n", mmap_mode);
429
430     err = snd_pcm_hw_params_get_period_size(hw_params, &psize, NULL);
431     err = snd_pcm_hw_params_get_format(hw_params, &format);
432     err = snd_pcm_hw_params_get_buffer_size(hw_params, &frames);
433     err = snd_pcm_hw_params_get_channels(hw_params, &channels);
434     bits_per_sample = snd_pcm_format_physical_width(format);
435     bits_per_frame = bits_per_sample * channels;
436
437     if (TRACE_ON(dsalsa))
438         ALSA_TraceParameters(hw_params, NULL, FALSE);
439
440     TRACE("format=%s  frames=%ld  channels=%d  bits_per_sample=%d  bits_per_frame=%d\n",
441           snd_pcm_format_name(format), frames, channels, bits_per_sample, bits_per_frame);
442
443     pdbi->mmap_buflen_frames = frames;
444     snd_pcm_sw_params_current(pcm, sw_params);
445     snd_pcm_sw_params_set_start_threshold(pcm, sw_params, 0);
446     snd_pcm_sw_params_get_boundary(sw_params, &boundary);
447     snd_pcm_sw_params_set_stop_threshold(pcm, sw_params, boundary);
448     snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, INT_MAX);
449     snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0);
450     snd_pcm_sw_params_set_avail_min(pcm, sw_params, 0);
451     snd_pcm_sw_params_set_xrun_mode(pcm, sw_params, SND_PCM_XRUN_NONE);
452     err = snd_pcm_sw_params(pcm, sw_params);
453
454     avail = snd_pcm_avail_update(pcm);
455     if (avail < 0)
456     {
457         ERR("No buffer is available: %s.\n", snd_strerror(avail));
458         return DSERR_GENERIC;
459     }
460     err = snd_pcm_mmap_begin(pcm, &areas, &ofs, &avail);
461     if ( err < 0 )
462     {
463         ERR("Can't map sound device for direct access: %s\n", snd_strerror(err));
464         return DSERR_GENERIC;
465     }
466     err = snd_pcm_mmap_commit(pcm, ofs, 0);
467     pdbi->mmap_buffer = areas->addr;
468
469     TRACE("created mmap buffer of %ld frames (%d bytes) at %p\n",
470         frames, pdbi->mmap_buflen_bytes, pdbi->mmap_buffer);
471
472     return DS_OK;
473 }
474
475 static HRESULT WINAPI IDsCaptureDriverBufferImpl_QueryInterface(PIDSCDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
476 {
477     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
478     if ( IsEqualGUID(riid, &IID_IUnknown) ||
479          IsEqualGUID(riid, &IID_IDsCaptureDriverBuffer) ) {
480         IDsCaptureDriverBuffer_AddRef(iface);
481         *ppobj = (LPVOID)iface;
482         return DS_OK;
483     }
484
485     if ( IsEqualGUID( &IID_IDsDriverNotify, riid ) ) {
486         if (!This->notify)
487         {
488             This->notify = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDsCaptureDriverNotifyImpl));
489             if (!This->notify)
490                 return DSERR_OUTOFMEMORY;
491             This->notify->lpVtbl = &dscdnvt;
492             This->notify->buffer = This;
493
494             /* Keep a lock on IDsDriverNotify for ourself, so it is destroyed when the buffer is */
495             IDsDriverNotify_AddRef((PIDSDRIVERNOTIFY)This->notify);
496         }
497         IDsDriverNotify_AddRef((PIDSDRIVERNOTIFY)This->notify);
498         *ppobj = (LPVOID)This->notify;
499         return DS_OK;
500     }
501
502     if ( IsEqualGUID( &IID_IDsDriverPropertySet, riid ) ) {
503         FIXME("Unsupported interface IID_IDsDriverPropertySet\n");
504         return E_FAIL;
505     }
506
507     FIXME("(): Unknown interface %s\n", debugstr_guid(riid));
508     return DSERR_UNSUPPORTED;
509 }
510
511 static ULONG WINAPI IDsCaptureDriverBufferImpl_AddRef(PIDSCDRIVERBUFFER iface)
512 {
513     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
514     ULONG refCount = InterlockedIncrement(&This->ref);
515
516     TRACE("(%p)->(ref before=%u)\n",This, refCount - 1);
517
518     return refCount;
519 }
520
521 static ULONG WINAPI IDsCaptureDriverBufferImpl_Release(PIDSCDRIVERBUFFER iface)
522 {
523     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
524     ULONG refCount = InterlockedDecrement(&This->ref);
525
526     TRACE("(%p)->(ref before=%u)\n",This, refCount + 1);
527
528     if (refCount)
529         return refCount;
530
531     EnterCriticalSection(&This->pcm_crst);
532     if (This->notify)
533         IDsDriverNotify_Release((PIDSDRIVERNOTIFY)This->notify);
534     TRACE("mmap buffer %p destroyed\n", This->mmap_buffer);
535
536     This->drv->capture_buffer = NULL;
537     LeaveCriticalSection(&This->pcm_crst);
538     This->pcm_crst.DebugInfo->Spare[0] = 0;
539     DeleteCriticalSection(&This->pcm_crst);
540
541     snd_pcm_drop(This->pcm);
542     snd_pcm_close(This->pcm);
543     This->pcm = NULL;
544     HeapFree(GetProcessHeap(), 0, This->presented_buffer);
545     HeapFree(GetProcessHeap(), 0, This->sw_params);
546     HeapFree(GetProcessHeap(), 0, This->hw_params);
547     HeapFree(GetProcessHeap(), 0, This);
548     return 0;
549 }
550
551 static HRESULT WINAPI IDsCaptureDriverBufferImpl_Lock(PIDSCDRIVERBUFFER iface, LPVOID*ppvAudio1,LPDWORD pdwLen1,LPVOID*ppvAudio2,LPDWORD pdwLen2, DWORD dwWritePosition,DWORD dwWriteLen, DWORD dwFlags)
552 {
553     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
554     TRACE("(%p,%p,%p,%p,%p,%d,%d,0x%08x)\n", This, ppvAudio1, pdwLen1, ppvAudio2, pdwLen2, dwWritePosition, dwWriteLen, dwFlags);
555
556     if (ppvAudio1)
557         *ppvAudio1 = (LPBYTE)This->presented_buffer + dwWritePosition;
558
559     if (dwWritePosition + dwWriteLen < This->mmap_buflen_bytes) {
560         if (pdwLen1)
561             *pdwLen1 = dwWriteLen;
562         if (ppvAudio2)
563             *ppvAudio2 = 0;
564         if (pdwLen2)
565             *pdwLen2 = 0;
566     } else {
567         if (pdwLen1)
568             *pdwLen1 = This->mmap_buflen_bytes - dwWritePosition;
569         if (ppvAudio2)
570             *ppvAudio2 = This->presented_buffer;
571         if (pdwLen2)
572             *pdwLen2 = dwWriteLen - (This->mmap_buflen_bytes - dwWritePosition);
573     }
574     return DS_OK;
575 }
576
577 static HRESULT WINAPI IDsCaptureDriverBufferImpl_Unlock(PIDSCDRIVERBUFFER iface, LPVOID pvAudio1,DWORD dwLen1, LPVOID pvAudio2,DWORD dwLen2)
578 {
579     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
580     TRACE("(%p,%p,%d,%p,%d)\n",This,pvAudio1,dwLen1,pvAudio2,dwLen2);
581     return DS_OK;
582 }
583
584 static HRESULT WINAPI IDsCaptureDriverBufferImpl_SetFormat(PIDSCDRIVERBUFFER iface, LPWAVEFORMATEX pwfx)
585 {
586     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
587     WINE_WAVEDEV *wwi = &WInDev[This->drv->wDevID];
588     snd_pcm_t *pcm = NULL;
589     snd_pcm_hw_params_t *hw_params = This->hw_params;
590     snd_pcm_format_t format = -1;
591     snd_pcm_uframes_t buffer_size;
592     DWORD rate = pwfx->nSamplesPerSec;
593     int err=0;
594
595     TRACE("(%p, %p)\n", iface, pwfx);
596
597     switch (pwfx->wBitsPerSample)
598     {
599         case  8: format = SND_PCM_FORMAT_U8; break;
600         case 16: format = SND_PCM_FORMAT_S16_LE; break;
601         case 24: format = SND_PCM_FORMAT_S24_3LE; break;
602         case 32: format = SND_PCM_FORMAT_S32_LE; break;
603         default: FIXME("Unsupported bpp: %d\n", pwfx->wBitsPerSample); return DSERR_GENERIC;
604     }
605
606     /* **** */
607     EnterCriticalSection(&This->pcm_crst);
608
609     err = snd_pcm_open(&pcm, wwi->pcmname, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
610
611     if (err < 0)
612     {
613         if (errno != EBUSY || !This->pcm)
614         {
615             /* **** */
616             LeaveCriticalSection(&This->pcm_crst);
617             WARN("Cannot open sound device: %s\n", snd_strerror(err));
618             return DSERR_GENERIC;
619         }
620         snd_pcm_drop(This->pcm);
621         snd_pcm_close(This->pcm);
622         This->pcm = NULL;
623         err = snd_pcm_open(&pcm, wwi->pcmname, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
624         if (err < 0)
625         {
626             /* **** */
627             LeaveCriticalSection(&This->pcm_crst);
628             WARN("Cannot open sound device: %s\n", snd_strerror(err));
629             return DSERR_BUFFERLOST;
630         }
631     }
632
633     /* Set some defaults */
634     snd_pcm_hw_params_any(pcm, hw_params);
635     err = snd_pcm_hw_params_set_channels(pcm, hw_params, pwfx->nChannels);
636     if (err < 0) { WARN("Could not set channels to %d\n", pwfx->nChannels); goto err; }
637
638     err = snd_pcm_hw_params_set_format(pcm, hw_params, format);
639     if (err < 0) { WARN("Could not set format to %d bpp\n", pwfx->wBitsPerSample); goto err; }
640
641     err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, NULL);
642     if (err < 0) { rate = pwfx->nSamplesPerSec; WARN("Could not set rate\n"); goto err; }
643
644     if (!ALSA_NearMatch(rate, pwfx->nSamplesPerSec))
645     {
646         WARN("Could not set sound rate to %d, but instead to %d\n", pwfx->nSamplesPerSec, rate);
647         pwfx->nSamplesPerSec = rate;
648         pwfx->nAvgBytesPerSec = rate * pwfx->nBlockAlign;
649         /* Let DirectSound detect this */
650     }
651
652     snd_pcm_hw_params_set_periods_integer(pcm, hw_params);
653     buffer_size = This->mmap_buflen_bytes / pwfx->nBlockAlign;
654     snd_pcm_hw_params_set_buffer_size_near(pcm, hw_params, &buffer_size);
655     buffer_size = 5000;
656     snd_pcm_hw_params_set_period_time_near(pcm, hw_params, (unsigned int*)&buffer_size, NULL);
657     err = snd_pcm_hw_params(pcm, hw_params);
658     err = snd_pcm_sw_params(pcm, This->sw_params);
659     snd_pcm_prepare(pcm);
660
661     if (This->pcm)
662     {
663         snd_pcm_drop(This->pcm);
664         snd_pcm_close(This->pcm);
665     }
666     This->pcm = pcm;
667
668     snd_pcm_prepare(This->pcm);
669     CreateMMAP(This);
670
671     /* **** */
672     LeaveCriticalSection(&This->pcm_crst);
673     return S_OK;
674
675     err:
676     if (err < 0)
677         WARN("Failed to apply changes: %s\n", snd_strerror(err));
678
679     if (!This->pcm)
680         This->pcm = pcm;
681     else
682         snd_pcm_close(pcm);
683
684     if (This->pcm)
685         snd_pcm_hw_params_current(This->pcm, This->hw_params);
686
687     /* **** */
688     LeaveCriticalSection(&This->pcm_crst);
689     return DSERR_BADFORMAT;
690 }
691
692 static HRESULT WINAPI IDsCaptureDriverBufferImpl_GetPosition(PIDSCDRIVERBUFFER iface, LPDWORD lpdwCappos, LPDWORD lpdwReadpos)
693 {
694     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
695     snd_pcm_uframes_t hw_pptr, hw_wptr;
696
697     EnterCriticalSection(&This->pcm_crst);
698
699     if (!This->pcm)
700     {
701         FIXME("Bad pointer for pcm: %p\n", This->pcm);
702         LeaveCriticalSection(&This->pcm_crst);
703         return DSERR_GENERIC;
704     }
705
706     if (snd_pcm_state(This->pcm) != SND_PCM_STATE_RUNNING)
707     {
708         hw_pptr = This->mmap_pos;
709         CheckXRUN(This);
710     }
711     else
712     {
713         /* FIXME: Unused at the moment */
714         snd_pcm_uframes_t used = CommitAll(This, FALSE);
715
716         if (This->mmap_pos > used)
717             hw_pptr = This->mmap_pos - used;
718         else
719             hw_pptr = This->mmap_buflen_frames - used + This->mmap_pos;
720     }
721     hw_wptr = This->mmap_pos;
722
723     if (lpdwCappos)
724         *lpdwCappos = realpos_to_fakepos(This, hw_pptr);
725     if (lpdwReadpos)
726         *lpdwReadpos = realpos_to_fakepos(This, hw_wptr);
727
728     LeaveCriticalSection(&This->pcm_crst);
729
730     TRACE("hw_pptr=0x%08x, hw_wptr=0x%08x playpos=%d, writepos=%d\n", (unsigned int)hw_pptr, (unsigned int)hw_wptr, lpdwCappos?*lpdwCappos:-1, lpdwReadpos?*lpdwReadpos:-1);
731     return DS_OK;
732 }
733
734 static HRESULT WINAPI IDsCaptureDriverBufferImpl_GetStatus(PIDSCDRIVERBUFFER iface, LPDWORD lpdwStatus)
735 {
736     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
737     snd_pcm_state_t state;
738     TRACE("(%p,%p)\n",iface,lpdwStatus);
739
740     state = snd_pcm_state(This->pcm);
741     switch (state)
742     {
743     case SND_PCM_STATE_XRUN:
744     case SND_PCM_STATE_SUSPENDED:
745     case SND_PCM_STATE_RUNNING:
746         *lpdwStatus = DSCBSTATUS_CAPTURING | (This->play_looping ? DSCBSTATUS_LOOPING : 0);
747         break;
748     default:
749         *lpdwStatus = 0;
750         break;
751     }
752
753     TRACE("State: %d, flags: 0x%08x\n", state, *lpdwStatus);
754     return DS_OK;
755 }
756
757 static HRESULT WINAPI IDsCaptureDriverBufferImpl_Start(PIDSCDRIVERBUFFER iface, DWORD dwFlags)
758 {
759     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
760     TRACE("(%p,%x)\n",iface,dwFlags);
761
762     /* **** */
763     EnterCriticalSection(&This->pcm_crst);
764     snd_pcm_start(This->pcm);
765     This->play_looping = !!(dwFlags & DSCBSTART_LOOPING);
766     if (!This->play_looping)
767         /* Not well supported because of the difference in ALSA size and DSOUND's notion of size
768          * what it does right now is fill the buffer once.. ALSA size */
769         FIXME("Non-looping buffers are not properly supported!\n");
770     CommitAll(This, TRUE);
771
772     if (This->notify && This->notify->nrofnotifies && This->notify->notifies)
773     {
774         DWORD playpos = realpos_to_fakepos(This, This->mmap_pos);
775         if (playpos)
776             Capture_CheckNotify(This->notify, 0, playpos);
777         This->notify->playpos = playpos;
778     }
779
780     /* **** */
781     LeaveCriticalSection(&This->pcm_crst);
782     return DS_OK;
783 }
784
785 static HRESULT WINAPI IDsCaptureDriverBufferImpl_Stop(PIDSCDRIVERBUFFER iface)
786 {
787     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
788     TRACE("(%p)\n",iface);
789
790     /* **** */
791     EnterCriticalSection(&This->pcm_crst);
792     This->play_looping = FALSE;
793     snd_pcm_drop(This->pcm);
794     snd_pcm_prepare(This->pcm);
795
796     if (This->notify && This->notify->notifies && This->notify->nrofnotifies)
797         Capture_CheckNotify(This->notify, 0, 0);
798
799     /* **** */
800     LeaveCriticalSection(&This->pcm_crst);
801     return DS_OK;
802 }
803
804 static const IDsCaptureDriverBufferVtbl dsdbvt =
805 {
806     IDsCaptureDriverBufferImpl_QueryInterface,
807     IDsCaptureDriverBufferImpl_AddRef,
808     IDsCaptureDriverBufferImpl_Release,
809     IDsCaptureDriverBufferImpl_Lock,
810     IDsCaptureDriverBufferImpl_Unlock,
811     IDsCaptureDriverBufferImpl_SetFormat,
812     IDsCaptureDriverBufferImpl_GetPosition,
813     IDsCaptureDriverBufferImpl_GetStatus,
814     IDsCaptureDriverBufferImpl_Start,
815     IDsCaptureDriverBufferImpl_Stop
816 };
817
818 static HRESULT WINAPI IDsCaptureDriverImpl_QueryInterface(PIDSCDRIVER iface, REFIID riid, LPVOID *ppobj)
819 {
820     /* IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface; */
821     FIXME("(%p): stub!\n",iface);
822     return DSERR_UNSUPPORTED;
823 }
824
825 static ULONG WINAPI IDsCaptureDriverImpl_AddRef(PIDSCDRIVER iface)
826 {
827     IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface;
828     ULONG refCount = InterlockedIncrement(&This->ref);
829
830     TRACE("(%p)->(ref before=%u)\n",This, refCount - 1);
831
832     return refCount;
833 }
834
835 static ULONG WINAPI IDsCaptureDriverImpl_Release(PIDSCDRIVER iface)
836 {
837     IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface;
838     ULONG refCount = InterlockedDecrement(&This->ref);
839
840     TRACE("(%p)->(ref before=%u)\n",This, refCount + 1);
841
842     if (refCount)
843         return refCount;
844
845     HeapFree(GetProcessHeap(), 0, This);
846     return 0;
847 }
848
849 static HRESULT WINAPI IDsCaptureDriverImpl_GetDriverDesc(PIDSCDRIVER iface, PDSDRIVERDESC pDesc)
850 {
851     IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface;
852     TRACE("(%p,%p)\n",iface,pDesc);
853     memcpy(pDesc, &(WInDev[This->wDevID].ds_desc), sizeof(DSDRIVERDESC));
854     pDesc->dwFlags              = 0;
855     pDesc->dnDevNode            = WInDev[This->wDevID].waveDesc.dnDevNode;
856     pDesc->wVxdId               = 0;
857     pDesc->wReserved            = 0;
858     pDesc->ulDeviceNum          = This->wDevID;
859     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
860     pDesc->pvDirectDrawHeap     = NULL;
861     pDesc->dwMemStartAddress    = 0xDEAD0000;
862     pDesc->dwMemEndAddress      = 0xDEAF0000;
863     pDesc->dwMemAllocExtra      = 0;
864     pDesc->pvReserved1          = NULL;
865     pDesc->pvReserved2          = NULL;
866     return DS_OK;
867 }
868
869 static HRESULT WINAPI IDsCaptureDriverImpl_Open(PIDSCDRIVER iface)
870 {
871     HRESULT hr = S_OK;
872     IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface;
873     int err=0;
874     snd_pcm_t *pcm = NULL;
875     snd_pcm_hw_params_t *hw_params;
876
877     /* While this is not really needed, it is a good idea to do this,
878      * to see if sound can be initialized */
879
880     hw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof());
881     if (!hw_params)
882     {
883         hr = DSERR_OUTOFMEMORY;
884         WARN("--> %08x\n", hr);
885         return hr;
886     }
887
888     err = snd_pcm_open(&pcm, WOutDev[This->wDevID].pcmname, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
889     if (err < 0) goto err;
890     err = snd_pcm_hw_params_any(pcm, hw_params);
891     if (err < 0) goto err;
892     err = snd_pcm_hw_params_set_access (pcm, hw_params, SND_PCM_ACCESS_MMAP_INTERLEAVED);
893     if (err < 0) goto err;
894
895     TRACE("Success\n");
896     snd_pcm_close(pcm);
897     HeapFree(GetProcessHeap(), 0, hw_params);
898     return hr;
899
900     err:
901     hr = DSERR_GENERIC;
902     WARN("Failed to open device: %s\n", snd_strerror(err));
903     if (pcm)
904         snd_pcm_close(pcm);
905     HeapFree(GetProcessHeap(), 0, hw_params);
906     WARN("--> %08x\n", hr);
907     return hr;
908 }
909
910 static HRESULT WINAPI IDsCaptureDriverImpl_Close(PIDSCDRIVER iface)
911 {
912     IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface;
913     TRACE("(%p) stub, harmless\n",This);
914     return DS_OK;
915 }
916
917 static HRESULT WINAPI IDsCaptureDriverImpl_GetCaps(PIDSCDRIVER iface, PDSCDRIVERCAPS pCaps)
918 {
919     IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface;
920     WINE_WAVEDEV *wwi = &WInDev[This->wDevID];
921     TRACE("(%p,%p)\n",iface,pCaps);
922     pCaps->dwSize = sizeof(DSCDRIVERCAPS);
923     pCaps->dwFlags = wwi->ds_caps.dwFlags;
924     pCaps->dwFormats = wwi->incaps.dwFormats;
925     pCaps->dwChannels = wwi->incaps.wChannels;
926     return DS_OK;
927 }
928
929 static HRESULT WINAPI IDsCaptureDriverImpl_CreateCaptureBuffer(PIDSCDRIVER iface,
930                                                       LPWAVEFORMATEX pwfx,
931                                                       DWORD dwFlags, DWORD dwCardAddress,
932                                                       LPDWORD pdwcbBufferSize,
933                                                       LPBYTE *ppbBuffer,
934                                                       LPVOID *ppvObj)
935 {
936     IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface;
937     IDsCaptureDriverBufferImpl** ippdsdb = (IDsCaptureDriverBufferImpl**)ppvObj;
938     HRESULT err;
939
940     TRACE("(%p,%p,%x,%x)\n",iface,pwfx,dwFlags,dwCardAddress);
941
942     if (This->capture_buffer)
943         return DSERR_ALLOCATED;
944
945     This->capture_buffer = *ippdsdb = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDsCaptureDriverBufferImpl));
946     if (*ippdsdb == NULL)
947         return DSERR_OUTOFMEMORY;
948
949     (*ippdsdb)->hw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof());
950     (*ippdsdb)->sw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_sw_params_sizeof());
951     (*ippdsdb)->presented_buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwcbBufferSize);
952     if (!(*ippdsdb)->hw_params || !(*ippdsdb)->sw_params || !(*ippdsdb)->presented_buffer)
953     {
954         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->sw_params);
955         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->hw_params);
956         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->presented_buffer);
957         return DSERR_OUTOFMEMORY;
958     }
959     (*ippdsdb)->lpVtbl = &dsdbvt;
960     (*ippdsdb)->ref = 1;
961     (*ippdsdb)->drv = This;
962     (*ippdsdb)->mmap_buflen_bytes = *pdwcbBufferSize;
963     InitializeCriticalSection(&(*ippdsdb)->pcm_crst);
964     (*ippdsdb)->pcm_crst.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ALSA_DSCAPTURE.pcm_crst");
965
966     /* SetFormat initialises pcm */
967     err = IDsDriverBuffer_SetFormat((IDsDriverBuffer*)*ppvObj, pwfx);
968     if (FAILED(err))
969     {
970         WARN("Error occurred: %08x\n", err);
971         goto err;
972     }
973     *ppbBuffer = (*ippdsdb)->presented_buffer;
974
975     /* buffer is ready to go */
976     TRACE("buffer created at %p\n", *ippdsdb);
977     return err;
978
979     err:
980     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->presented_buffer);
981     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->sw_params);
982     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->hw_params);
983     HeapFree(GetProcessHeap(), 0, *ippdsdb);
984     *ippdsdb = NULL;
985     return err;
986 }
987
988 static const IDsCaptureDriverVtbl dscdvt =
989 {
990     IDsCaptureDriverImpl_QueryInterface,
991     IDsCaptureDriverImpl_AddRef,
992     IDsCaptureDriverImpl_Release,
993     IDsCaptureDriverImpl_GetDriverDesc,
994     IDsCaptureDriverImpl_Open,
995     IDsCaptureDriverImpl_Close,
996     IDsCaptureDriverImpl_GetCaps,
997     IDsCaptureDriverImpl_CreateCaptureBuffer
998 };
999
1000 /**************************************************************************
1001  *                              widDsCreate                     [internal]
1002  */
1003 DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
1004 {
1005     IDsCaptureDriverImpl** idrv = (IDsCaptureDriverImpl**)drv;
1006     TRACE("(%d,%p)\n",wDevID,drv);
1007
1008     if (!(WInDev[wDevID].dwSupport & WAVECAPS_DIRECTSOUND))
1009     {
1010         WARN("Hardware accelerated capture not supported, falling back to wavein\n");
1011         return MMSYSERR_NOTSUPPORTED;
1012     }
1013
1014     *idrv = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDsCaptureDriverImpl));
1015     if (!*idrv)
1016         return MMSYSERR_NOMEM;
1017     (*idrv)->lpVtbl     = &dscdvt;
1018     (*idrv)->ref        = 1;
1019
1020     (*idrv)->wDevID     = wDevID;
1021     return MMSYSERR_NOERROR;
1022 }
1023
1024 /**************************************************************************
1025  *                              widDsDesc                       [internal]
1026  */
1027 DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1028 {
1029     memcpy(desc, &(WInDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
1030     return MMSYSERR_NOERROR;
1031 }
1032
1033 #endif /* HAVE_ALSA */