ntdll: Free old memory block when reallocating to a large block.
[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     err = snd_pcm_sw_params(pcm, sw_params);
452
453     avail = snd_pcm_avail_update(pcm);
454     if ((snd_pcm_sframes_t)avail < 0)
455     {
456         ERR("No buffer is available: %s.\n", snd_strerror(avail));
457         return DSERR_GENERIC;
458     }
459     err = snd_pcm_mmap_begin(pcm, &areas, &ofs, &avail);
460     if ( err < 0 )
461     {
462         ERR("Can't map sound device for direct access: %s\n", snd_strerror(err));
463         return DSERR_GENERIC;
464     }
465     err = snd_pcm_mmap_commit(pcm, ofs, 0);
466     pdbi->mmap_buffer = areas->addr;
467
468     TRACE("created mmap buffer of %ld frames (%d bytes) at %p\n",
469         frames, pdbi->mmap_buflen_bytes, pdbi->mmap_buffer);
470
471     return DS_OK;
472 }
473
474 static HRESULT WINAPI IDsCaptureDriverBufferImpl_QueryInterface(PIDSCDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
475 {
476     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
477     if ( IsEqualGUID(riid, &IID_IUnknown) ||
478          IsEqualGUID(riid, &IID_IDsCaptureDriverBuffer) ) {
479         IDsCaptureDriverBuffer_AddRef(iface);
480         *ppobj = iface;
481         return DS_OK;
482     }
483
484     if ( IsEqualGUID( &IID_IDsDriverNotify, riid ) ) {
485         if (!This->notify)
486         {
487             This->notify = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDsCaptureDriverNotifyImpl));
488             if (!This->notify)
489                 return DSERR_OUTOFMEMORY;
490             This->notify->lpVtbl = &dscdnvt;
491             This->notify->buffer = This;
492
493             /* Keep a lock on IDsDriverNotify for ourself, so it is destroyed when the buffer is */
494             IDsDriverNotify_AddRef((PIDSDRIVERNOTIFY)This->notify);
495         }
496         IDsDriverNotify_AddRef((PIDSDRIVERNOTIFY)This->notify);
497         *ppobj = This->notify;
498         return DS_OK;
499     }
500
501     if ( IsEqualGUID( &IID_IDsDriverPropertySet, riid ) ) {
502         FIXME("Unsupported interface IID_IDsDriverPropertySet\n");
503         return E_FAIL;
504     }
505
506     FIXME("(): Unknown interface %s\n", debugstr_guid(riid));
507     return DSERR_UNSUPPORTED;
508 }
509
510 static ULONG WINAPI IDsCaptureDriverBufferImpl_AddRef(PIDSCDRIVERBUFFER iface)
511 {
512     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
513     ULONG refCount = InterlockedIncrement(&This->ref);
514
515     TRACE("(%p)->(ref before=%u)\n",This, refCount - 1);
516
517     return refCount;
518 }
519
520 static ULONG WINAPI IDsCaptureDriverBufferImpl_Release(PIDSCDRIVERBUFFER iface)
521 {
522     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
523     ULONG refCount = InterlockedDecrement(&This->ref);
524
525     TRACE("(%p)->(ref before=%u)\n",This, refCount + 1);
526
527     if (refCount)
528         return refCount;
529
530     EnterCriticalSection(&This->pcm_crst);
531     if (This->notify)
532         IDsDriverNotify_Release((PIDSDRIVERNOTIFY)This->notify);
533     TRACE("mmap buffer %p destroyed\n", This->mmap_buffer);
534
535     This->drv->capture_buffer = NULL;
536     LeaveCriticalSection(&This->pcm_crst);
537     This->pcm_crst.DebugInfo->Spare[0] = 0;
538     DeleteCriticalSection(&This->pcm_crst);
539
540     snd_pcm_drop(This->pcm);
541     snd_pcm_close(This->pcm);
542     This->pcm = NULL;
543     HeapFree(GetProcessHeap(), 0, This->presented_buffer);
544     HeapFree(GetProcessHeap(), 0, This->sw_params);
545     HeapFree(GetProcessHeap(), 0, This->hw_params);
546     HeapFree(GetProcessHeap(), 0, This);
547     return 0;
548 }
549
550 static HRESULT WINAPI IDsCaptureDriverBufferImpl_Lock(PIDSCDRIVERBUFFER iface, LPVOID*ppvAudio1,LPDWORD pdwLen1,LPVOID*ppvAudio2,LPDWORD pdwLen2, DWORD dwWritePosition,DWORD dwWriteLen, DWORD dwFlags)
551 {
552     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
553     TRACE("(%p,%p,%p,%p,%p,%d,%d,0x%08x)\n", This, ppvAudio1, pdwLen1, ppvAudio2, pdwLen2, dwWritePosition, dwWriteLen, dwFlags);
554
555     if (ppvAudio1)
556         *ppvAudio1 = (LPBYTE)This->presented_buffer + dwWritePosition;
557
558     if (dwWritePosition + dwWriteLen < This->mmap_buflen_bytes) {
559         if (pdwLen1)
560             *pdwLen1 = dwWriteLen;
561         if (ppvAudio2)
562             *ppvAudio2 = 0;
563         if (pdwLen2)
564             *pdwLen2 = 0;
565     } else {
566         if (pdwLen1)
567             *pdwLen1 = This->mmap_buflen_bytes - dwWritePosition;
568         if (ppvAudio2)
569             *ppvAudio2 = This->presented_buffer;
570         if (pdwLen2)
571             *pdwLen2 = dwWriteLen - (This->mmap_buflen_bytes - dwWritePosition);
572     }
573     return DS_OK;
574 }
575
576 static HRESULT WINAPI IDsCaptureDriverBufferImpl_Unlock(PIDSCDRIVERBUFFER iface, LPVOID pvAudio1,DWORD dwLen1, LPVOID pvAudio2,DWORD dwLen2)
577 {
578     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
579     TRACE("(%p,%p,%d,%p,%d)\n",This,pvAudio1,dwLen1,pvAudio2,dwLen2);
580     return DS_OK;
581 }
582
583 static HRESULT WINAPI IDsCaptureDriverBufferImpl_SetFormat(PIDSCDRIVERBUFFER iface, LPWAVEFORMATEX pwfx)
584 {
585     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
586     WINE_WAVEDEV *wwi = &WInDev[This->drv->wDevID];
587     snd_pcm_t *pcm = NULL;
588     snd_pcm_hw_params_t *hw_params = This->hw_params;
589     snd_pcm_format_t format = -1;
590     snd_pcm_uframes_t buffer_size;
591     DWORD rate = pwfx->nSamplesPerSec;
592     int err=0;
593
594     TRACE("(%p, %p)\n", iface, pwfx);
595
596     switch (pwfx->wBitsPerSample)
597     {
598         case  8: format = SND_PCM_FORMAT_U8; break;
599         case 16: format = SND_PCM_FORMAT_S16_LE; break;
600         case 24: format = SND_PCM_FORMAT_S24_3LE; break;
601         case 32: format = SND_PCM_FORMAT_S32_LE; break;
602         default: FIXME("Unsupported bpp: %d\n", pwfx->wBitsPerSample); return DSERR_GENERIC;
603     }
604
605     /* **** */
606     EnterCriticalSection(&This->pcm_crst);
607
608     err = snd_pcm_open(&pcm, wwi->pcmname, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
609
610     if (err < 0)
611     {
612         if (errno != EBUSY || !This->pcm)
613         {
614             /* **** */
615             LeaveCriticalSection(&This->pcm_crst);
616             WARN("Cannot open sound device: %s\n", snd_strerror(err));
617             return DSERR_GENERIC;
618         }
619         snd_pcm_drop(This->pcm);
620         snd_pcm_close(This->pcm);
621         This->pcm = NULL;
622         err = snd_pcm_open(&pcm, wwi->pcmname, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
623         if (err < 0)
624         {
625             /* **** */
626             LeaveCriticalSection(&This->pcm_crst);
627             WARN("Cannot open sound device: %s\n", snd_strerror(err));
628             return DSERR_BUFFERLOST;
629         }
630     }
631
632     /* Set some defaults */
633     snd_pcm_hw_params_any(pcm, hw_params);
634     err = snd_pcm_hw_params_set_channels(pcm, hw_params, pwfx->nChannels);
635     if (err < 0) { WARN("Could not set channels to %d\n", pwfx->nChannels); goto err; }
636
637     err = snd_pcm_hw_params_set_format(pcm, hw_params, format);
638     if (err < 0) { WARN("Could not set format to %d bpp\n", pwfx->wBitsPerSample); goto err; }
639
640     err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, NULL);
641     if (err < 0) { rate = pwfx->nSamplesPerSec; WARN("Could not set rate\n"); goto err; }
642
643     if (!ALSA_NearMatch(rate, pwfx->nSamplesPerSec))
644     {
645         WARN("Could not set sound rate to %d, but instead to %d\n", pwfx->nSamplesPerSec, rate);
646         pwfx->nSamplesPerSec = rate;
647         pwfx->nAvgBytesPerSec = rate * pwfx->nBlockAlign;
648         /* Let DirectSound detect this */
649     }
650
651     snd_pcm_hw_params_set_periods_integer(pcm, hw_params);
652     buffer_size = This->mmap_buflen_bytes / pwfx->nBlockAlign;
653     snd_pcm_hw_params_set_buffer_size_near(pcm, hw_params, &buffer_size);
654     buffer_size = 5000;
655     snd_pcm_hw_params_set_period_time_near(pcm, hw_params, (unsigned int*)&buffer_size, NULL);
656     err = snd_pcm_hw_params(pcm, hw_params);
657     err = snd_pcm_sw_params(pcm, This->sw_params);
658     snd_pcm_prepare(pcm);
659
660     if (This->pcm)
661     {
662         snd_pcm_drop(This->pcm);
663         snd_pcm_close(This->pcm);
664     }
665     This->pcm = pcm;
666
667     snd_pcm_prepare(This->pcm);
668     CreateMMAP(This);
669
670     /* **** */
671     LeaveCriticalSection(&This->pcm_crst);
672     return S_OK;
673
674     err:
675     if (err < 0)
676         WARN("Failed to apply changes: %s\n", snd_strerror(err));
677
678     if (!This->pcm)
679         This->pcm = pcm;
680     else
681         snd_pcm_close(pcm);
682
683     if (This->pcm)
684         snd_pcm_hw_params_current(This->pcm, This->hw_params);
685
686     /* **** */
687     LeaveCriticalSection(&This->pcm_crst);
688     return DSERR_BADFORMAT;
689 }
690
691 static HRESULT WINAPI IDsCaptureDriverBufferImpl_GetPosition(PIDSCDRIVERBUFFER iface, LPDWORD lpdwCappos, LPDWORD lpdwReadpos)
692 {
693     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
694     snd_pcm_uframes_t hw_pptr, hw_wptr;
695
696     EnterCriticalSection(&This->pcm_crst);
697
698     if (!This->pcm)
699     {
700         FIXME("Bad pointer for pcm: %p\n", This->pcm);
701         LeaveCriticalSection(&This->pcm_crst);
702         return DSERR_GENERIC;
703     }
704
705     if (snd_pcm_state(This->pcm) != SND_PCM_STATE_RUNNING)
706     {
707         hw_pptr = This->mmap_pos;
708         CheckXRUN(This);
709     }
710     else
711     {
712         /* FIXME: Unused at the moment */
713         snd_pcm_uframes_t used = CommitAll(This, FALSE);
714
715         if (This->mmap_pos > used)
716             hw_pptr = This->mmap_pos - used;
717         else
718             hw_pptr = This->mmap_buflen_frames - used + This->mmap_pos;
719     }
720     hw_wptr = This->mmap_pos;
721
722     if (lpdwCappos)
723         *lpdwCappos = realpos_to_fakepos(This, hw_pptr);
724     if (lpdwReadpos)
725         *lpdwReadpos = realpos_to_fakepos(This, hw_wptr);
726
727     LeaveCriticalSection(&This->pcm_crst);
728
729     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);
730     return DS_OK;
731 }
732
733 static HRESULT WINAPI IDsCaptureDriverBufferImpl_GetStatus(PIDSCDRIVERBUFFER iface, LPDWORD lpdwStatus)
734 {
735     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
736     snd_pcm_state_t state;
737     TRACE("(%p,%p)\n",iface,lpdwStatus);
738
739     state = snd_pcm_state(This->pcm);
740     switch (state)
741     {
742     case SND_PCM_STATE_XRUN:
743     case SND_PCM_STATE_SUSPENDED:
744     case SND_PCM_STATE_RUNNING:
745         *lpdwStatus = DSCBSTATUS_CAPTURING | (This->play_looping ? DSCBSTATUS_LOOPING : 0);
746         break;
747     default:
748         *lpdwStatus = 0;
749         break;
750     }
751
752     TRACE("State: %d, flags: 0x%08x\n", state, *lpdwStatus);
753     return DS_OK;
754 }
755
756 static HRESULT WINAPI IDsCaptureDriverBufferImpl_Start(PIDSCDRIVERBUFFER iface, DWORD dwFlags)
757 {
758     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
759     TRACE("(%p,%x)\n",iface,dwFlags);
760
761     /* **** */
762     EnterCriticalSection(&This->pcm_crst);
763     snd_pcm_start(This->pcm);
764     This->play_looping = !!(dwFlags & DSCBSTART_LOOPING);
765     if (!This->play_looping)
766         /* Not well supported because of the difference in ALSA size and DSOUND's notion of size
767          * what it does right now is fill the buffer once.. ALSA size */
768         FIXME("Non-looping buffers are not properly supported!\n");
769     CommitAll(This, TRUE);
770
771     if (This->notify && This->notify->nrofnotifies && This->notify->notifies)
772     {
773         DWORD playpos = realpos_to_fakepos(This, This->mmap_pos);
774         if (playpos)
775             Capture_CheckNotify(This->notify, 0, playpos);
776         This->notify->playpos = playpos;
777     }
778
779     /* **** */
780     LeaveCriticalSection(&This->pcm_crst);
781     return DS_OK;
782 }
783
784 static HRESULT WINAPI IDsCaptureDriverBufferImpl_Stop(PIDSCDRIVERBUFFER iface)
785 {
786     IDsCaptureDriverBufferImpl *This = (IDsCaptureDriverBufferImpl *)iface;
787     TRACE("(%p)\n",iface);
788
789     /* **** */
790     EnterCriticalSection(&This->pcm_crst);
791     This->play_looping = FALSE;
792     snd_pcm_drop(This->pcm);
793     snd_pcm_prepare(This->pcm);
794
795     if (This->notify && This->notify->notifies && This->notify->nrofnotifies)
796         Capture_CheckNotify(This->notify, 0, 0);
797
798     /* **** */
799     LeaveCriticalSection(&This->pcm_crst);
800     return DS_OK;
801 }
802
803 static const IDsCaptureDriverBufferVtbl dsdbvt =
804 {
805     IDsCaptureDriverBufferImpl_QueryInterface,
806     IDsCaptureDriverBufferImpl_AddRef,
807     IDsCaptureDriverBufferImpl_Release,
808     IDsCaptureDriverBufferImpl_Lock,
809     IDsCaptureDriverBufferImpl_Unlock,
810     IDsCaptureDriverBufferImpl_SetFormat,
811     IDsCaptureDriverBufferImpl_GetPosition,
812     IDsCaptureDriverBufferImpl_GetStatus,
813     IDsCaptureDriverBufferImpl_Start,
814     IDsCaptureDriverBufferImpl_Stop
815 };
816
817 static HRESULT WINAPI IDsCaptureDriverImpl_QueryInterface(PIDSCDRIVER iface, REFIID riid, LPVOID *ppobj)
818 {
819     /* IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface; */
820     FIXME("(%p): stub!\n",iface);
821     return DSERR_UNSUPPORTED;
822 }
823
824 static ULONG WINAPI IDsCaptureDriverImpl_AddRef(PIDSCDRIVER iface)
825 {
826     IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface;
827     ULONG refCount = InterlockedIncrement(&This->ref);
828
829     TRACE("(%p)->(ref before=%u)\n",This, refCount - 1);
830
831     return refCount;
832 }
833
834 static ULONG WINAPI IDsCaptureDriverImpl_Release(PIDSCDRIVER iface)
835 {
836     IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface;
837     ULONG refCount = InterlockedDecrement(&This->ref);
838
839     TRACE("(%p)->(ref before=%u)\n",This, refCount + 1);
840
841     if (refCount)
842         return refCount;
843
844     HeapFree(GetProcessHeap(), 0, This);
845     return 0;
846 }
847
848 static HRESULT WINAPI IDsCaptureDriverImpl_GetDriverDesc(PIDSCDRIVER iface, PDSDRIVERDESC pDesc)
849 {
850     IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface;
851     TRACE("(%p,%p)\n",iface,pDesc);
852     *pDesc                      = WInDev[This->wDevID].ds_desc;
853     pDesc->dwFlags              = 0;
854     pDesc->dnDevNode            = WInDev[This->wDevID].waveDesc.dnDevNode;
855     pDesc->wVxdId               = 0;
856     pDesc->wReserved            = 0;
857     pDesc->ulDeviceNum          = This->wDevID;
858     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
859     pDesc->pvDirectDrawHeap     = NULL;
860     pDesc->dwMemStartAddress    = 0xDEAD0000;
861     pDesc->dwMemEndAddress      = 0xDEAF0000;
862     pDesc->dwMemAllocExtra      = 0;
863     pDesc->pvReserved1          = NULL;
864     pDesc->pvReserved2          = NULL;
865     return DS_OK;
866 }
867
868 static HRESULT WINAPI IDsCaptureDriverImpl_Open(PIDSCDRIVER iface)
869 {
870     HRESULT hr = S_OK;
871     IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface;
872     int err=0;
873     snd_pcm_t *pcm = NULL;
874     snd_pcm_hw_params_t *hw_params;
875
876     /* While this is not really needed, it is a good idea to do this,
877      * to see if sound can be initialized */
878
879     hw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof());
880     if (!hw_params)
881     {
882         hr = DSERR_OUTOFMEMORY;
883         WARN("--> %08x\n", hr);
884         return hr;
885     }
886
887     err = snd_pcm_open(&pcm, WInDev[This->wDevID].pcmname, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
888     if (err < 0) goto err;
889     err = snd_pcm_hw_params_any(pcm, hw_params);
890     if (err < 0) goto err;
891     err = snd_pcm_hw_params_set_access (pcm, hw_params, SND_PCM_ACCESS_MMAP_INTERLEAVED);
892     if (err < 0) goto err;
893
894     TRACE("Success\n");
895     snd_pcm_close(pcm);
896     HeapFree(GetProcessHeap(), 0, hw_params);
897     return hr;
898
899     err:
900     hr = DSERR_GENERIC;
901     WARN("Failed to open device: %s\n", snd_strerror(err));
902     if (pcm)
903         snd_pcm_close(pcm);
904     HeapFree(GetProcessHeap(), 0, hw_params);
905     WARN("--> %08x\n", hr);
906     return hr;
907 }
908
909 static HRESULT WINAPI IDsCaptureDriverImpl_Close(PIDSCDRIVER iface)
910 {
911     IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface;
912     TRACE("(%p) stub, harmless\n",This);
913     return DS_OK;
914 }
915
916 static HRESULT WINAPI IDsCaptureDriverImpl_GetCaps(PIDSCDRIVER iface, PDSCDRIVERCAPS pCaps)
917 {
918     IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface;
919     WINE_WAVEDEV *wwi = &WInDev[This->wDevID];
920     TRACE("(%p,%p)\n",iface,pCaps);
921     pCaps->dwSize = sizeof(DSCDRIVERCAPS);
922     pCaps->dwFlags = wwi->ds_caps.dwFlags;
923     pCaps->dwFormats = wwi->incaps.dwFormats;
924     pCaps->dwChannels = wwi->incaps.wChannels;
925     return DS_OK;
926 }
927
928 static HRESULT WINAPI IDsCaptureDriverImpl_CreateCaptureBuffer(PIDSCDRIVER iface,
929                                                       LPWAVEFORMATEX pwfx,
930                                                       DWORD dwFlags, DWORD dwCardAddress,
931                                                       LPDWORD pdwcbBufferSize,
932                                                       LPBYTE *ppbBuffer,
933                                                       LPVOID *ppvObj)
934 {
935     IDsCaptureDriverImpl *This = (IDsCaptureDriverImpl *)iface;
936     IDsCaptureDriverBufferImpl** ippdsdb = (IDsCaptureDriverBufferImpl**)ppvObj;
937     HRESULT err;
938
939     TRACE("(%p,%p,%x,%x)\n",iface,pwfx,dwFlags,dwCardAddress);
940
941     if (This->capture_buffer)
942         return DSERR_ALLOCATED;
943
944     This->capture_buffer = *ippdsdb = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDsCaptureDriverBufferImpl));
945     if (*ippdsdb == NULL)
946         return DSERR_OUTOFMEMORY;
947
948     (*ippdsdb)->hw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof());
949     (*ippdsdb)->sw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_sw_params_sizeof());
950     (*ippdsdb)->presented_buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwcbBufferSize);
951     if (!(*ippdsdb)->hw_params || !(*ippdsdb)->sw_params || !(*ippdsdb)->presented_buffer)
952     {
953         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->sw_params);
954         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->hw_params);
955         HeapFree(GetProcessHeap(), 0, (*ippdsdb)->presented_buffer);
956         return DSERR_OUTOFMEMORY;
957     }
958     (*ippdsdb)->lpVtbl = &dsdbvt;
959     (*ippdsdb)->ref = 1;
960     (*ippdsdb)->drv = This;
961     (*ippdsdb)->mmap_buflen_bytes = *pdwcbBufferSize;
962     InitializeCriticalSection(&(*ippdsdb)->pcm_crst);
963     (*ippdsdb)->pcm_crst.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ALSA_DSCAPTURE.pcm_crst");
964
965     /* SetFormat initialises pcm */
966     err = IDsDriverBuffer_SetFormat((IDsDriverBuffer*)*ppvObj, pwfx);
967     if (FAILED(err))
968     {
969         WARN("Error occurred: %08x\n", err);
970         goto err;
971     }
972     *ppbBuffer = (*ippdsdb)->presented_buffer;
973
974     /* buffer is ready to go */
975     TRACE("buffer created at %p\n", *ippdsdb);
976     return err;
977
978     err:
979     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->presented_buffer);
980     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->sw_params);
981     HeapFree(GetProcessHeap(), 0, (*ippdsdb)->hw_params);
982     HeapFree(GetProcessHeap(), 0, *ippdsdb);
983     *ippdsdb = NULL;
984     return err;
985 }
986
987 static const IDsCaptureDriverVtbl dscdvt =
988 {
989     IDsCaptureDriverImpl_QueryInterface,
990     IDsCaptureDriverImpl_AddRef,
991     IDsCaptureDriverImpl_Release,
992     IDsCaptureDriverImpl_GetDriverDesc,
993     IDsCaptureDriverImpl_Open,
994     IDsCaptureDriverImpl_Close,
995     IDsCaptureDriverImpl_GetCaps,
996     IDsCaptureDriverImpl_CreateCaptureBuffer
997 };
998
999 /**************************************************************************
1000  *                              widDsCreate                     [internal]
1001  */
1002 DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
1003 {
1004     IDsCaptureDriverImpl** idrv = (IDsCaptureDriverImpl**)drv;
1005     TRACE("(%d,%p)\n",wDevID,drv);
1006
1007     if (!(WInDev[wDevID].dwSupport & WAVECAPS_DIRECTSOUND))
1008     {
1009         WARN("Hardware accelerated capture not supported, falling back to wavein\n");
1010         return MMSYSERR_NOTSUPPORTED;
1011     }
1012
1013     *idrv = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDsCaptureDriverImpl));
1014     if (!*idrv)
1015         return MMSYSERR_NOMEM;
1016     (*idrv)->lpVtbl     = &dscdvt;
1017     (*idrv)->ref        = 1;
1018
1019     (*idrv)->wDevID     = wDevID;
1020     return MMSYSERR_NOERROR;
1021 }
1022
1023 /**************************************************************************
1024  *                              widDsDesc                       [internal]
1025  */
1026 DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1027 {
1028     *desc = WInDev[wDevID].ds_desc;
1029     return MMSYSERR_NOERROR;
1030 }
1031
1032 #endif /* HAVE_ALSA */