dsound: Acceleration fixes for wavein emulation.
[wine] / dlls / dsound / capture.c
1 /*              DirectSoundCapture
2  *
3  * Copyright 1998 Marcus Meissner
4  * Copyright 1998 Rob Riggs
5  * Copyright 2000-2001 TransGaming Technologies, Inc.
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  * TODO:
23  *      Implement FX support.
24  *      Implement both IDirectSoundCaptureBuffer and IDirectSoundCaptureBuffer8
25  *      Make DirectSoundCaptureCreate and DirectSoundCaptureCreate8 behave differently
26  */
27
28 #include <stdarg.h>
29
30 #define NONAMELESSSTRUCT
31 #define NONAMELESSUNION
32 #include "windef.h"
33 #include "winbase.h"
34 #include "winuser.h"
35 #include "mmsystem.h"
36 #include "mmddk.h"
37 #include "winternl.h"
38 #include "winnls.h"
39 #include "wine/debug.h"
40 #include "dsound.h"
41 #include "dsdriver.h"
42 #include "dsound_private.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
45
46 /*****************************************************************************
47  * IDirectSoundCapture implementation structure
48  */
49 struct IDirectSoundCaptureImpl
50 {
51     /* IUnknown fields */
52     const IDirectSoundCaptureVtbl     *lpVtbl;
53     LONG                               ref;
54
55     DirectSoundCaptureDevice          *device;
56 };
57
58 static HRESULT IDirectSoundCaptureImpl_Create(LPDIRECTSOUNDCAPTURE8 * ppds);
59
60
61 /*****************************************************************************
62  * IDirectSoundCaptureNotify implementation structure
63  */
64 struct IDirectSoundCaptureNotifyImpl
65 {
66     /* IUnknown fields */
67     const IDirectSoundNotifyVtbl       *lpVtbl;
68     LONG                                ref;
69     IDirectSoundCaptureBufferImpl*      dscb;
70 };
71
72 static HRESULT IDirectSoundCaptureNotifyImpl_Create(IDirectSoundCaptureBufferImpl *dscb,
73                                                     IDirectSoundCaptureNotifyImpl ** pdscn);
74
75
76 DirectSoundCaptureDevice * DSOUND_capture[MAXWAVEDRIVERS];
77
78 static HRESULT DirectSoundCaptureDevice_Create(DirectSoundCaptureDevice ** ppDevice);
79
80 static const char * const captureStateString[] = {
81     "STATE_STOPPED",
82     "STATE_STARTING",
83     "STATE_CAPTURING",
84     "STATE_STOPPING"
85 };
86
87 HRESULT DSOUND_CaptureCreate(
88     REFIID riid,
89     LPDIRECTSOUNDCAPTURE *ppDSC)
90 {
91     LPDIRECTSOUNDCAPTURE pDSC;
92     HRESULT hr;
93     TRACE("(%s, %p)\n", debugstr_guid(riid), ppDSC);
94
95     if (!IsEqualIID(riid, &IID_IUnknown) &&
96         !IsEqualIID(riid, &IID_IDirectSoundCapture)) {
97         *ppDSC = 0;
98         return E_NOINTERFACE;
99     }
100
101     /* Get dsound configuration */
102     setup_dsound_options();
103
104     hr = IDirectSoundCaptureImpl_Create(&pDSC);
105     if (hr == DS_OK) {
106         IDirectSoundCapture_AddRef(pDSC);
107         *ppDSC = pDSC;
108     } else {
109         WARN("IDirectSoundCaptureImpl_Create failed\n");
110         *ppDSC = 0;
111     }
112
113     return hr;
114 }
115
116 HRESULT DSOUND_CaptureCreate8(
117     REFIID riid,
118     LPDIRECTSOUNDCAPTURE8 *ppDSC8)
119 {
120     LPDIRECTSOUNDCAPTURE8 pDSC8;
121     HRESULT hr;
122     TRACE("(%s, %p)\n", debugstr_guid(riid), ppDSC8);
123
124     if (!IsEqualIID(riid, &IID_IUnknown) &&
125         !IsEqualIID(riid, &IID_IDirectSoundCapture8)) {
126         *ppDSC8 = 0;
127         return E_NOINTERFACE;
128     }
129
130     /* Get dsound configuration */
131     setup_dsound_options();
132
133     hr = IDirectSoundCaptureImpl_Create(&pDSC8);
134     if (hr == DS_OK) {
135         IDirectSoundCapture_AddRef(pDSC8);
136         *ppDSC8 = pDSC8;
137     } else {
138         WARN("IDirectSoundCaptureImpl_Create failed\n");
139         *ppDSC8 = 0;
140     }
141
142     return hr;
143 }
144
145 /***************************************************************************
146  * DirectSoundCaptureCreate [DSOUND.6]
147  *
148  * Create and initialize a DirectSoundCapture interface.
149  *
150  * PARAMS
151  *    lpcGUID   [I] Address of the GUID that identifies the sound capture device.
152  *    lplpDSC   [O] Address of a variable to receive the interface pointer.
153  *    pUnkOuter [I] Must be NULL.
154  *
155  * RETURNS
156  *    Success: DS_OK
157  *    Failure: DSERR_NOAGGREGATION, DSERR_ALLOCATED, DSERR_INVALIDPARAM,
158  *             DSERR_OUTOFMEMORY
159  *
160  * NOTES
161  *    lpcGUID must be one of the values returned from DirectSoundCaptureEnumerate
162  *    or NULL for the default device or DSDEVID_DefaultCapture or
163  *    DSDEVID_DefaultVoiceCapture.
164  *
165  *    DSERR_ALLOCATED is returned for sound devices that do not support full duplex.
166  */
167 HRESULT WINAPI DirectSoundCaptureCreate(
168     LPCGUID lpcGUID,
169     LPDIRECTSOUNDCAPTURE *ppDSC,
170     LPUNKNOWN pUnkOuter)
171 {
172     HRESULT hr;
173     LPDIRECTSOUNDCAPTURE pDSC;
174     TRACE("(%s,%p,%p)\n", debugstr_guid(lpcGUID), ppDSC, pUnkOuter);
175
176     if (ppDSC == NULL) {
177         WARN("invalid parameter: ppDSC == NULL\n");
178         return DSERR_INVALIDPARAM;
179     }
180
181     if (pUnkOuter) {
182         WARN("invalid parameter: pUnkOuter != NULL\n");
183         *ppDSC = NULL;
184         return DSERR_NOAGGREGATION;
185     }
186
187     hr = DSOUND_CaptureCreate(&IID_IDirectSoundCapture, &pDSC);
188     if (hr == DS_OK) {
189         hr = IDirectSoundCapture_Initialize(pDSC, lpcGUID);
190         if (hr != DS_OK) {
191             IDirectSoundCapture_Release(pDSC);
192             pDSC = 0;
193         }
194     }
195
196     *ppDSC = pDSC;
197
198     return hr;
199 }
200
201 /***************************************************************************
202  * DirectSoundCaptureCreate8 [DSOUND.12]
203  *
204  * Create and initialize a DirectSoundCapture interface.
205  *
206  * PARAMS
207  *    lpcGUID   [I] Address of the GUID that identifies the sound capture device.
208  *    lplpDSC   [O] Address of a variable to receive the interface pointer.
209  *    pUnkOuter [I] Must be NULL.
210  *
211  * RETURNS
212  *    Success: DS_OK
213  *    Failure: DSERR_NOAGGREGATION, DSERR_ALLOCATED, DSERR_INVALIDPARAM,
214  *             DSERR_OUTOFMEMORY
215  *
216  * NOTES
217  *    lpcGUID must be one of the values returned from DirectSoundCaptureEnumerate
218  *    or NULL for the default device or DSDEVID_DefaultCapture or
219  *    DSDEVID_DefaultVoiceCapture.
220  *
221  *    DSERR_ALLOCATED is returned for sound devices that do not support full duplex.
222  */
223 HRESULT WINAPI DirectSoundCaptureCreate8(
224     LPCGUID lpcGUID,
225     LPDIRECTSOUNDCAPTURE8 *ppDSC8,
226     LPUNKNOWN pUnkOuter)
227 {
228     HRESULT hr;
229     LPDIRECTSOUNDCAPTURE8 pDSC8;
230     TRACE("(%s,%p,%p)\n", debugstr_guid(lpcGUID), ppDSC8, pUnkOuter);
231
232     if (ppDSC8 == NULL) {
233         WARN("invalid parameter: ppDSC8 == NULL\n");
234         return DSERR_INVALIDPARAM;
235     }
236
237     if (pUnkOuter) {
238         WARN("invalid parameter: pUnkOuter != NULL\n");
239         *ppDSC8 = NULL;
240         return DSERR_NOAGGREGATION;
241     }
242
243     hr = DSOUND_CaptureCreate8(&IID_IDirectSoundCapture8, &pDSC8);
244     if (hr == DS_OK) {
245         hr = IDirectSoundCapture_Initialize(pDSC8, lpcGUID);
246         if (hr != DS_OK) {
247             IDirectSoundCapture_Release(pDSC8);
248             pDSC8 = 0;
249         }
250     }
251
252     *ppDSC8 = pDSC8;
253
254     return hr;
255 }
256
257 /***************************************************************************
258  * DirectSoundCaptureEnumerateA [DSOUND.7]
259  *
260  * Enumerate all DirectSound drivers installed in the system.
261  *
262  * PARAMS
263  *    lpDSEnumCallback  [I] Address of callback function.
264  *    lpContext         [I] Address of user defined context passed to callback function.
265  *
266  * RETURNS
267  *    Success: DS_OK
268  *    Failure: DSERR_INVALIDPARAM
269  */
270 HRESULT WINAPI
271 DirectSoundCaptureEnumerateA(
272     LPDSENUMCALLBACKA lpDSEnumCallback,
273     LPVOID lpContext)
274 {
275     unsigned devs, wid;
276     DSDRIVERDESC desc;
277     GUID guid;
278     int err;
279
280     TRACE("(%p,%p)\n", lpDSEnumCallback, lpContext );
281
282     if (lpDSEnumCallback == NULL) {
283         WARN("invalid parameter: lpDSEnumCallback == NULL\n");
284         return DSERR_INVALIDPARAM;
285     }
286
287     devs = waveInGetNumDevs();
288     if (devs > 0) {
289         if (GetDeviceID(&DSDEVID_DefaultCapture, &guid) == DS_OK) {
290             for (wid = 0; wid < devs; ++wid) {
291                 if (IsEqualGUID( &guid, &DSOUND_capture_guids[wid] ) ) {
292                     err = mmErr(waveInMessage((HWAVEIN)wid,DRV_QUERYDSOUNDDESC,(DWORD_PTR)&desc,0));
293                     if (err == DS_OK) {
294                         TRACE("calling lpDSEnumCallback(NULL,\"%s\",\"%s\",%p)\n",
295                               "Primary Sound Capture Driver",desc.szDrvname,lpContext);
296                         if (lpDSEnumCallback(NULL, "Primary Sound Capture Driver", desc.szDrvname, lpContext) == FALSE)
297                             return DS_OK;
298                     }
299                 }
300             }
301         }
302     }
303
304     for (wid = 0; wid < devs; ++wid) {
305         err = mmErr(waveInMessage((HWAVEIN)wid,DRV_QUERYDSOUNDDESC,(DWORD_PTR)&desc,0));
306         if (err == DS_OK) {
307             TRACE("calling lpDSEnumCallback(%s,\"%s\",\"%s\",%p)\n",
308                   debugstr_guid(&DSOUND_capture_guids[wid]),desc.szDesc,desc.szDrvname,lpContext);
309             if (lpDSEnumCallback(&DSOUND_capture_guids[wid], desc.szDesc, desc.szDrvname, lpContext) == FALSE)
310                 return DS_OK;
311         }
312     }
313
314     return DS_OK;
315 }
316
317 /***************************************************************************
318  * DirectSoundCaptureEnumerateW [DSOUND.8]
319  *
320  * Enumerate all DirectSound drivers installed in the system.
321  *
322  * PARAMS
323  *    lpDSEnumCallback  [I] Address of callback function.
324  *    lpContext         [I] Address of user defined context passed to callback function.
325  *
326  * RETURNS
327  *    Success: DS_OK
328  *    Failure: DSERR_INVALIDPARAM
329  */
330 HRESULT WINAPI
331 DirectSoundCaptureEnumerateW(
332     LPDSENUMCALLBACKW lpDSEnumCallback,
333     LPVOID lpContext)
334 {
335     unsigned devs, wid;
336     DSDRIVERDESC desc;
337     GUID guid;
338     int err;
339     WCHAR wDesc[MAXPNAMELEN];
340     WCHAR wName[MAXPNAMELEN];
341
342     TRACE("(%p,%p)\n", lpDSEnumCallback, lpContext );
343
344     if (lpDSEnumCallback == NULL) {
345         WARN("invalid parameter: lpDSEnumCallback == NULL\n");
346         return DSERR_INVALIDPARAM;
347     }
348
349     devs = waveInGetNumDevs();
350     if (devs > 0) {
351         if (GetDeviceID(&DSDEVID_DefaultCapture, &guid) == DS_OK) {
352             for (wid = 0; wid < devs; ++wid) {
353                 if (IsEqualGUID( &guid, &DSOUND_capture_guids[wid] ) ) {
354                     err = mmErr(waveInMessage((HWAVEIN)wid,DRV_QUERYDSOUNDDESC,(DWORD_PTR)&desc,0));
355                     if (err == DS_OK) {
356                         TRACE("calling lpDSEnumCallback(NULL,\"%s\",\"%s\",%p)\n",
357                               "Primary Sound Capture Driver",desc.szDrvname,lpContext);
358                         MultiByteToWideChar( CP_ACP, 0, "Primary Sound Capture Driver", -1,
359                                              wDesc, sizeof(wDesc)/sizeof(WCHAR) );
360                         MultiByteToWideChar( CP_ACP, 0, desc.szDrvname, -1,
361                                              wName, sizeof(wName)/sizeof(WCHAR) );
362                         if (lpDSEnumCallback(NULL, wDesc, wName, lpContext) == FALSE)
363                             return DS_OK;
364                     }
365                 }
366             }
367         }
368     }
369
370     for (wid = 0; wid < devs; ++wid) {
371         err = mmErr(waveInMessage((HWAVEIN)wid,DRV_QUERYDSOUNDDESC,(DWORD_PTR)&desc,0));
372         if (err == DS_OK) {
373             TRACE("calling lpDSEnumCallback(%s,\"%s\",\"%s\",%p)\n",
374                   debugstr_guid(&DSOUND_capture_guids[wid]),desc.szDesc,desc.szDrvname,lpContext);
375             MultiByteToWideChar( CP_ACP, 0, desc.szDesc, -1,
376                                  wDesc, sizeof(wDesc)/sizeof(WCHAR) );
377             MultiByteToWideChar( CP_ACP, 0, desc.szDrvname, -1,
378                                  wName, sizeof(wName)/sizeof(WCHAR) );
379             if (lpDSEnumCallback((LPGUID)&DSOUND_capture_guids[wid], wDesc, wName, lpContext) == FALSE)
380                 return DS_OK;
381         }
382     }
383
384     return DS_OK;
385 }
386
387 static void CALLBACK
388 DSOUND_capture_callback(
389     HWAVEIN hwi,
390     UINT msg,
391     DWORD dwUser,
392     DWORD dw1,
393     DWORD dw2 )
394 {
395     DirectSoundCaptureDevice * This = (DirectSoundCaptureDevice*)dwUser;
396     TRACE("(%p,%08x(%s),%08x,%08x,%08x) entering at %d\n",hwi,msg,
397         msg == MM_WIM_OPEN ? "MM_WIM_OPEN" : msg == MM_WIM_CLOSE ? "MM_WIM_CLOSE" :
398         msg == MM_WIM_DATA ? "MM_WIM_DATA" : "UNKNOWN",dwUser,dw1,dw2,GetTickCount());
399
400     if (msg == MM_WIM_DATA) {
401         LPWAVEHDR pHdr = (LPWAVEHDR)dw1;
402         EnterCriticalSection( &(This->lock) );
403         TRACE("DirectSoundCapture msg=MM_WIM_DATA, old This->state=%s, old This->index=%d\n",
404             captureStateString[This->state],This->index);
405         if (This->state != STATE_STOPPED) {
406             int index = This->index;
407             if (This->state == STATE_STARTING) {
408                 This->read_position = pHdr->dwBytesRecorded;
409                 This->state = STATE_CAPTURING;
410             }
411             if (This->capture_buffer->nrofnotifies)
412                 SetEvent(This->capture_buffer->notifies[This->index].hEventNotify);
413             This->index = (This->index + 1) % This->nrofpwaves;
414             if ( (This->index == 0) && !(This->capture_buffer->flags & DSCBSTART_LOOPING) ) {
415                 TRACE("end of buffer\n");
416                 This->state = STATE_STOPPED;
417             } else {
418                 if (This->state == STATE_CAPTURING) {
419                     waveInAddBuffer(hwi, &(This->pwave[index]), sizeof(WAVEHDR));
420                 } else if (This->state == STATE_STOPPING) {
421                     TRACE("stopping\n");
422                     This->state = STATE_STOPPED;
423                 }
424             }
425         }
426         TRACE("DirectSoundCapture new This->state=%s, new This->index=%d\n",
427             captureStateString[This->state],This->index);
428         LeaveCriticalSection( &(This->lock) );
429     }
430
431     TRACE("completed\n");
432 }
433
434 /***************************************************************************
435  * IDirectSoundCaptureImpl
436  */
437 static HRESULT WINAPI
438 IDirectSoundCaptureImpl_QueryInterface(
439     LPDIRECTSOUNDCAPTURE iface,
440     REFIID riid,
441     LPVOID* ppobj )
442 {
443     IDirectSoundCaptureImpl *This = (IDirectSoundCaptureImpl *)iface;
444     TRACE( "(%p,%s,%p)\n", This, debugstr_guid(riid), ppobj );
445
446     if (ppobj == NULL) {
447         WARN("invalid parameter\n");
448         return E_INVALIDARG;
449     }
450
451     *ppobj = NULL;
452
453     if (IsEqualIID(riid, &IID_IUnknown)) {
454         IDirectSoundCapture_AddRef((LPDIRECTSOUNDCAPTURE)This);
455         *ppobj = This;
456         return DS_OK;
457     } else if (IsEqualIID(riid, &IID_IDirectSoundCapture)) {
458         IDirectSoundCapture_AddRef((LPDIRECTSOUNDCAPTURE)This);
459         *ppobj = This;
460         return DS_OK;
461     }
462
463     WARN("unsupported riid: %s\n", debugstr_guid(riid));
464     return E_NOINTERFACE;
465 }
466
467 static ULONG WINAPI
468 IDirectSoundCaptureImpl_AddRef( LPDIRECTSOUNDCAPTURE iface )
469 {
470     IDirectSoundCaptureImpl *This = (IDirectSoundCaptureImpl *)iface;
471     ULONG ref = InterlockedIncrement(&(This->ref));
472     TRACE("(%p) ref was %d\n", This, ref - 1);
473     return ref;
474 }
475
476 static ULONG WINAPI
477 IDirectSoundCaptureImpl_Release( LPDIRECTSOUNDCAPTURE iface )
478 {
479     IDirectSoundCaptureImpl *This = (IDirectSoundCaptureImpl *)iface;
480     ULONG ref = InterlockedDecrement(&(This->ref));
481     TRACE("(%p) ref was %d\n", This, ref + 1);
482
483     if (!ref) {
484         if (This->device)
485             DirectSoundCaptureDevice_Release(This->device);
486
487         HeapFree( GetProcessHeap(), 0, This );
488         TRACE("(%p) released\n", This);
489     }
490     return ref;
491 }
492
493 HRESULT WINAPI IDirectSoundCaptureImpl_CreateCaptureBuffer(
494     LPDIRECTSOUNDCAPTURE iface,
495     LPCDSCBUFFERDESC lpcDSCBufferDesc,
496     LPDIRECTSOUNDCAPTUREBUFFER* lplpDSCaptureBuffer,
497     LPUNKNOWN pUnk )
498 {
499     HRESULT hr;
500     IDirectSoundCaptureImpl *This = (IDirectSoundCaptureImpl *)iface;
501
502     TRACE( "(%p,%p,%p,%p)\n",iface,lpcDSCBufferDesc,lplpDSCaptureBuffer,pUnk);
503
504     if (lpcDSCBufferDesc == NULL) {
505         WARN("invalid parameter: lpcDSCBufferDesc == NULL)\n");
506         return DSERR_INVALIDPARAM;
507     }
508
509     if (lplpDSCaptureBuffer == NULL) {
510         WARN("invalid parameter: lplpDSCaptureBuffer == NULL\n");
511         return DSERR_INVALIDPARAM;
512     }
513
514     if (pUnk != NULL) {
515         WARN("invalid parameter: pUnk != NULL\n");
516         return DSERR_INVALIDPARAM;
517     }
518
519     /* FIXME: We can only have one buffer so what do we do here? */
520     if (This->device->capture_buffer) {
521         WARN("lnvalid parameter: already has buffer\n");
522         return DSERR_INVALIDPARAM;    /* DSERR_GENERIC ? */
523     }
524
525     hr = IDirectSoundCaptureBufferImpl_Create(This->device,
526         (IDirectSoundCaptureBufferImpl **)lplpDSCaptureBuffer, lpcDSCBufferDesc);
527
528     if (hr != DS_OK)
529         WARN("IDirectSoundCaptureBufferImpl_Create failed\n");
530
531     return hr;
532 }
533
534 HRESULT WINAPI IDirectSoundCaptureImpl_GetCaps(
535     LPDIRECTSOUNDCAPTURE iface,
536     LPDSCCAPS lpDSCCaps )
537 {
538     IDirectSoundCaptureImpl *This = (IDirectSoundCaptureImpl *)iface;
539     TRACE("(%p,%p)\n",This,lpDSCCaps);
540
541     if (This->device == NULL) {
542         WARN("not initialized\n");
543         return DSERR_UNINITIALIZED;
544     }
545
546     if (lpDSCCaps== NULL) {
547         WARN("invalid parameter: lpDSCCaps== NULL\n");
548         return DSERR_INVALIDPARAM;
549     }
550
551     if (lpDSCCaps->dwSize < sizeof(*lpDSCCaps)) {
552         WARN("invalid parameter: lpDSCCaps->dwSize = %d\n", lpDSCCaps->dwSize);
553         return DSERR_INVALIDPARAM;
554     }
555
556     lpDSCCaps->dwFlags = This->device->drvcaps.dwFlags;
557     lpDSCCaps->dwFormats = This->device->drvcaps.dwFormats;
558     lpDSCCaps->dwChannels = This->device->drvcaps.dwChannels;
559
560     TRACE("(flags=0x%08x,format=0x%08x,channels=%d)\n",lpDSCCaps->dwFlags,
561         lpDSCCaps->dwFormats, lpDSCCaps->dwChannels);
562
563     return DS_OK;
564 }
565
566 HRESULT WINAPI IDirectSoundCaptureImpl_Initialize(
567     LPDIRECTSOUNDCAPTURE iface,
568     LPCGUID lpcGUID )
569 {
570     IDirectSoundCaptureImpl *This = (IDirectSoundCaptureImpl *)iface;
571     TRACE("(%p,%s)\n", This, debugstr_guid(lpcGUID));
572
573     if (This->device != NULL) {
574         WARN("already initialized\n");
575         return DSERR_ALREADYINITIALIZED;
576     }
577
578     return DirectSoundCaptureDevice_Initialize(&This->device, lpcGUID);
579 }
580
581 static const IDirectSoundCaptureVtbl dscvt =
582 {
583     /* IUnknown methods */
584     IDirectSoundCaptureImpl_QueryInterface,
585     IDirectSoundCaptureImpl_AddRef,
586     IDirectSoundCaptureImpl_Release,
587
588     /* IDirectSoundCapture methods */
589     IDirectSoundCaptureImpl_CreateCaptureBuffer,
590     IDirectSoundCaptureImpl_GetCaps,
591     IDirectSoundCaptureImpl_Initialize
592 };
593
594 static HRESULT IDirectSoundCaptureImpl_Create(
595     LPDIRECTSOUNDCAPTURE8 * ppDSC)
596 {
597     IDirectSoundCaptureImpl *pDSC;
598     TRACE("(%p)\n", ppDSC);
599
600     /* Allocate memory */
601     pDSC = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDirectSoundCaptureImpl));
602     if (pDSC == NULL) {
603         WARN("out of memory\n");
604         *ppDSC = NULL;
605         return DSERR_OUTOFMEMORY;
606     }
607
608     pDSC->lpVtbl = &dscvt;
609     pDSC->ref    = 0;
610     pDSC->device = NULL;
611
612     *ppDSC = (LPDIRECTSOUNDCAPTURE8)pDSC;
613
614     return DS_OK;
615 }
616
617 /*******************************************************************************
618  *              IDirectSoundCaptureNotify
619  */
620 static HRESULT WINAPI IDirectSoundCaptureNotifyImpl_QueryInterface(
621     LPDIRECTSOUNDNOTIFY iface,
622     REFIID riid,
623     LPVOID *ppobj)
624 {
625     IDirectSoundCaptureNotifyImpl *This = (IDirectSoundCaptureNotifyImpl *)iface;
626     TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
627
628     if (This->dscb == NULL) {
629         WARN("invalid parameter\n");
630         return E_INVALIDARG;
631     }
632
633     return IDirectSoundCaptureBuffer_QueryInterface((LPDIRECTSOUNDCAPTUREBUFFER)This->dscb, riid, ppobj);
634 }
635
636 static ULONG WINAPI IDirectSoundCaptureNotifyImpl_AddRef(LPDIRECTSOUNDNOTIFY iface)
637 {
638     IDirectSoundCaptureNotifyImpl *This = (IDirectSoundCaptureNotifyImpl *)iface;
639     ULONG ref = InterlockedIncrement(&(This->ref));
640     TRACE("(%p) ref was %d\n", This, ref - 1);
641     return ref;
642 }
643
644 static ULONG WINAPI IDirectSoundCaptureNotifyImpl_Release(LPDIRECTSOUNDNOTIFY iface)
645 {
646     IDirectSoundCaptureNotifyImpl *This = (IDirectSoundCaptureNotifyImpl *)iface;
647     ULONG ref = InterlockedDecrement(&(This->ref));
648     TRACE("(%p) ref was %d\n", This, ref + 1);
649
650     if (!ref) {
651         if (This->dscb->hwnotify)
652             IDsDriverNotify_Release(This->dscb->hwnotify);
653         This->dscb->notify=NULL;
654         IDirectSoundCaptureBuffer_Release((LPDIRECTSOUNDCAPTUREBUFFER)This->dscb);
655         HeapFree(GetProcessHeap(),0,This);
656         TRACE("(%p) released\n", This);
657     }
658     return ref;
659 }
660
661 static HRESULT WINAPI IDirectSoundCaptureNotifyImpl_SetNotificationPositions(
662     LPDIRECTSOUNDNOTIFY iface,
663     DWORD howmuch,
664     LPCDSBPOSITIONNOTIFY notify)
665 {
666     IDirectSoundCaptureNotifyImpl *This = (IDirectSoundCaptureNotifyImpl *)iface;
667     TRACE("(%p,0x%08x,%p)\n",This,howmuch,notify);
668
669     if (howmuch > 0 && notify == NULL) {
670         WARN("invalid parameter: notify == NULL\n");
671         return DSERR_INVALIDPARAM;
672     }
673
674     if (TRACE_ON(dsound)) {
675         unsigned int i;
676         for (i=0;i<howmuch;i++)
677             TRACE("notify at %d to %p\n",
678             notify[i].dwOffset,notify[i].hEventNotify);
679     }
680
681     if (This->dscb->hwnotify) {
682         HRESULT hres;
683         hres = IDsDriverNotify_SetNotificationPositions(This->dscb->hwnotify, howmuch, notify);
684         if (hres != DS_OK)
685             WARN("IDsDriverNotify_SetNotificationPositions failed\n");
686         return hres;
687     } else if (howmuch > 0) {
688         /* Make an internal copy of the caller-supplied array.
689          * Replace the existing copy if one is already present. */
690         if (This->dscb->notifies)
691             This->dscb->notifies = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
692                 This->dscb->notifies, howmuch * sizeof(DSBPOSITIONNOTIFY));
693         else
694             This->dscb->notifies = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
695                 howmuch * sizeof(DSBPOSITIONNOTIFY));
696
697         if (This->dscb->notifies == NULL) {
698             WARN("out of memory\n");
699             return DSERR_OUTOFMEMORY;
700         }
701         CopyMemory(This->dscb->notifies, notify, howmuch * sizeof(DSBPOSITIONNOTIFY));
702         This->dscb->nrofnotifies = howmuch;
703     } else {
704         HeapFree(GetProcessHeap(), 0, This->dscb->notifies);
705         This->dscb->notifies = NULL;
706         This->dscb->nrofnotifies = 0;
707     }
708
709     return S_OK;
710 }
711
712 static const IDirectSoundNotifyVtbl dscnvt =
713 {
714     IDirectSoundCaptureNotifyImpl_QueryInterface,
715     IDirectSoundCaptureNotifyImpl_AddRef,
716     IDirectSoundCaptureNotifyImpl_Release,
717     IDirectSoundCaptureNotifyImpl_SetNotificationPositions,
718 };
719
720 static HRESULT IDirectSoundCaptureNotifyImpl_Create(
721     IDirectSoundCaptureBufferImpl *dscb,
722     IDirectSoundCaptureNotifyImpl **pdscn)
723 {
724     IDirectSoundCaptureNotifyImpl * dscn;
725     TRACE("(%p,%p)\n",dscb,pdscn);
726
727     dscn = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(dscn));
728
729     if (dscn == NULL) {
730         WARN("out of memory\n");
731         return DSERR_OUTOFMEMORY;
732     }
733
734     dscn->ref = 0;
735     dscn->lpVtbl = &dscnvt;
736     dscn->dscb = dscb;
737     dscb->notify = dscn;
738     IDirectSoundCaptureBuffer_AddRef((LPDIRECTSOUNDCAPTUREBUFFER)dscb);
739
740     *pdscn = dscn;
741     return DS_OK;
742 }
743
744 /*******************************************************************************
745  *              IDirectSoundCaptureBuffer
746  */
747 static HRESULT WINAPI
748 IDirectSoundCaptureBufferImpl_QueryInterface(
749     LPDIRECTSOUNDCAPTUREBUFFER8 iface,
750     REFIID riid,
751     LPVOID* ppobj )
752 {
753     IDirectSoundCaptureBufferImpl *This = (IDirectSoundCaptureBufferImpl *)iface;
754     HRESULT hres;
755     TRACE( "(%p,%s,%p)\n", This, debugstr_guid(riid), ppobj );
756
757     if (ppobj == NULL) {
758         WARN("invalid parameter\n");
759         return E_INVALIDARG;
760     }
761
762     *ppobj = NULL;
763
764     if ( IsEqualGUID( &IID_IDirectSoundNotify, riid ) ) {
765         if (!This->notify)
766             hres = IDirectSoundCaptureNotifyImpl_Create(This, &This->notify);
767         if (This->notify) {
768             if (This->device->hwbuf) {
769                 hres = IDsCaptureDriverBuffer_QueryInterface(This->device->hwbuf,
770                     &IID_IDsDriverNotify, (LPVOID*)&(This->hwnotify));
771                 if (hres != DS_OK) {
772                     WARN("IDsCaptureDriverBuffer_QueryInterface failed\n");
773                     *ppobj = 0;
774                     return hres;
775                 }
776             }
777
778             IDirectSoundNotify_AddRef((LPDIRECTSOUNDNOTIFY)This->notify);
779             *ppobj = (LPVOID)This->notify;
780             return DS_OK;
781         }
782
783         WARN("IID_IDirectSoundNotify\n");
784         return E_FAIL;
785     }
786
787     if ( IsEqualGUID( &IID_IDirectSoundCaptureBuffer, riid ) ||
788          IsEqualGUID( &IID_IDirectSoundCaptureBuffer8, riid ) ) {
789         IDirectSoundCaptureBuffer8_AddRef(iface);
790         *ppobj = This;
791         return NO_ERROR;
792     }
793
794     FIXME("(%p,%s,%p) unsupported GUID\n", This, debugstr_guid(riid), ppobj);
795     return E_NOINTERFACE;
796 }
797
798 static ULONG WINAPI
799 IDirectSoundCaptureBufferImpl_AddRef( LPDIRECTSOUNDCAPTUREBUFFER8 iface )
800 {
801     IDirectSoundCaptureBufferImpl *This = (IDirectSoundCaptureBufferImpl *)iface;
802     ULONG ref = InterlockedIncrement(&(This->ref));
803     TRACE("(%p) ref was %d\n", This, ref - 1);
804     return ref;
805 }
806
807 static ULONG WINAPI
808 IDirectSoundCaptureBufferImpl_Release( LPDIRECTSOUNDCAPTUREBUFFER8 iface )
809 {
810     IDirectSoundCaptureBufferImpl *This = (IDirectSoundCaptureBufferImpl *)iface;
811     ULONG ref = InterlockedDecrement(&(This->ref));
812     TRACE("(%p) ref was %d\n", This, ref + 1);
813
814     if (!ref) {
815         TRACE("deleting object\n");
816         if (This->device->state == STATE_CAPTURING)
817             This->device->state = STATE_STOPPING;
818
819         HeapFree(GetProcessHeap(),0, This->pdscbd);
820
821         if (This->device->hwi) {
822             waveInReset(This->device->hwi);
823             waveInClose(This->device->hwi);
824             HeapFree(GetProcessHeap(),0, This->device->pwave);
825             This->device->pwave = 0;
826             This->device->hwi = 0;
827         }
828
829         if (This->device->hwbuf)
830             IDsCaptureDriverBuffer_Release(This->device->hwbuf);
831
832         /* remove from DirectSoundCaptureDevice */
833         This->device->capture_buffer = NULL;
834
835         if (This->notify)
836             IDirectSoundNotify_Release((LPDIRECTSOUNDNOTIFY)This->notify);
837
838         HeapFree(GetProcessHeap(), 0, This->notifies);
839         HeapFree( GetProcessHeap(), 0, This );
840         TRACE("(%p) released\n", This);
841     }
842     return ref;
843 }
844
845 static HRESULT WINAPI
846 IDirectSoundCaptureBufferImpl_GetCaps(
847     LPDIRECTSOUNDCAPTUREBUFFER8 iface,
848     LPDSCBCAPS lpDSCBCaps )
849 {
850     IDirectSoundCaptureBufferImpl *This = (IDirectSoundCaptureBufferImpl *)iface;
851     TRACE( "(%p,%p)\n", This, lpDSCBCaps );
852
853     if (lpDSCBCaps == NULL) {
854         WARN("invalid parameter: lpDSCBCaps == NULL\n");
855         return DSERR_INVALIDPARAM;
856     }
857
858     if (lpDSCBCaps->dwSize < sizeof(DSCBCAPS)) {
859         WARN("invalid parameter: lpDSCBCaps->dwSize = %d\n", lpDSCBCaps->dwSize);
860         return DSERR_INVALIDPARAM;
861     }
862
863     if (This->device == NULL) {
864         WARN("invalid parameter: This->device == NULL\n");
865         return DSERR_INVALIDPARAM;
866     }
867
868     lpDSCBCaps->dwSize = sizeof(DSCBCAPS);
869     lpDSCBCaps->dwFlags = This->flags;
870     lpDSCBCaps->dwBufferBytes = This->pdscbd->dwBufferBytes;
871     lpDSCBCaps->dwReserved = 0;
872
873     TRACE("returning DS_OK\n");
874     return DS_OK;
875 }
876
877 static HRESULT WINAPI
878 IDirectSoundCaptureBufferImpl_GetCurrentPosition(
879     LPDIRECTSOUNDCAPTUREBUFFER8 iface,
880     LPDWORD lpdwCapturePosition,
881     LPDWORD lpdwReadPosition )
882 {
883     IDirectSoundCaptureBufferImpl *This = (IDirectSoundCaptureBufferImpl *)iface;
884     HRESULT hres = DS_OK;
885     TRACE( "(%p,%p,%p)\n", This, lpdwCapturePosition, lpdwReadPosition );
886
887     if (This->device == NULL) {
888         WARN("invalid parameter: This->device == NULL\n");
889         return DSERR_INVALIDPARAM;
890     }
891
892     if (This->device->driver) {
893         hres = IDsCaptureDriverBuffer_GetPosition(This->device->hwbuf, lpdwCapturePosition, lpdwReadPosition );
894         if (hres != DS_OK)
895             WARN("IDsCaptureDriverBuffer_GetPosition failed\n");
896     } else if (This->device->hwi) {
897         TRACE("old This->device->state=%s\n",captureStateString[This->device->state]);
898         if (lpdwCapturePosition) {
899             MMTIME mtime;
900             mtime.wType = TIME_BYTES;
901             waveInGetPosition(This->device->hwi, &mtime, sizeof(mtime));
902             TRACE("mtime.u.cb=%d,This->device->buflen=%d\n", mtime.u.cb,
903                 This->device->buflen);
904             mtime.u.cb = mtime.u.cb % This->device->buflen;
905             *lpdwCapturePosition = mtime.u.cb;
906         }
907
908         EnterCriticalSection(&(This->device->lock));
909         if (lpdwReadPosition) {
910             if (This->device->state == STATE_STARTING) {
911                 if (lpdwCapturePosition)
912                     This->device->read_position = *lpdwCapturePosition;
913                 This->device->state = STATE_CAPTURING;
914             }
915             *lpdwReadPosition = This->device->read_position;
916         }
917         TRACE("new This->device->state=%s\n",captureStateString[This->device->state]);
918         LeaveCriticalSection(&(This->device->lock));
919         if (lpdwCapturePosition) TRACE("*lpdwCapturePosition=%d\n",*lpdwCapturePosition);
920         if (lpdwReadPosition) TRACE("*lpdwReadPosition=%d\n",*lpdwReadPosition);
921     } else {
922         WARN("no driver\n");
923         hres = DSERR_NODRIVER;
924     }
925
926     TRACE("returning %08x\n", hres);
927     return hres;
928 }
929
930 static HRESULT WINAPI
931 IDirectSoundCaptureBufferImpl_GetFormat(
932     LPDIRECTSOUNDCAPTUREBUFFER8 iface,
933     LPWAVEFORMATEX lpwfxFormat,
934     DWORD dwSizeAllocated,
935     LPDWORD lpdwSizeWritten )
936 {
937     IDirectSoundCaptureBufferImpl *This = (IDirectSoundCaptureBufferImpl *)iface;
938     HRESULT hres = DS_OK;
939     TRACE( "(%p,%p,0x%08x,%p)\n", This, lpwfxFormat, dwSizeAllocated,
940         lpdwSizeWritten );
941
942     if (This->device == NULL) {
943         WARN("invalid parameter: This->device == NULL\n");
944         return DSERR_INVALIDPARAM;
945     }
946
947     if (dwSizeAllocated > (sizeof(WAVEFORMATEX) + This->device->pwfx->cbSize))
948         dwSizeAllocated = sizeof(WAVEFORMATEX) + This->device->pwfx->cbSize;
949
950     if (lpwfxFormat) { /* NULL is valid (just want size) */
951         CopyMemory(lpwfxFormat, This->device->pwfx, dwSizeAllocated);
952         if (lpdwSizeWritten)
953             *lpdwSizeWritten = dwSizeAllocated;
954     } else {
955         if (lpdwSizeWritten)
956             *lpdwSizeWritten = sizeof(WAVEFORMATEX) + This->device->pwfx->cbSize;
957         else {
958             TRACE("invalid parameter: lpdwSizeWritten = NULL\n");
959             hres = DSERR_INVALIDPARAM;
960         }
961     }
962
963     TRACE("returning %08x\n", hres);
964     return hres;
965 }
966
967 static HRESULT WINAPI
968 IDirectSoundCaptureBufferImpl_GetStatus(
969     LPDIRECTSOUNDCAPTUREBUFFER8 iface,
970     LPDWORD lpdwStatus )
971 {
972     IDirectSoundCaptureBufferImpl *This = (IDirectSoundCaptureBufferImpl *)iface;
973     TRACE( "(%p, %p), thread is %04x\n", This, lpdwStatus, GetCurrentThreadId() );
974
975     if (This->device == NULL) {
976         WARN("invalid parameter: This->device == NULL\n");
977         return DSERR_INVALIDPARAM;
978     }
979
980     if (lpdwStatus == NULL) {
981         WARN("invalid parameter: lpdwStatus == NULL\n");
982         return DSERR_INVALIDPARAM;
983     }
984
985     *lpdwStatus = 0;
986     EnterCriticalSection(&(This->device->lock));
987
988     TRACE("old This->device->state=%s, old lpdwStatus=%08x\n",
989         captureStateString[This->device->state],*lpdwStatus);
990     if ((This->device->state == STATE_STARTING) ||
991         (This->device->state == STATE_CAPTURING)) {
992         *lpdwStatus |= DSCBSTATUS_CAPTURING;
993         if (This->flags & DSCBSTART_LOOPING)
994             *lpdwStatus |= DSCBSTATUS_LOOPING;
995     }
996     TRACE("new This->device->state=%s, new lpdwStatus=%08x\n",
997         captureStateString[This->device->state],*lpdwStatus);
998     LeaveCriticalSection(&(This->device->lock));
999
1000     TRACE("status=%x\n", *lpdwStatus);
1001     TRACE("returning DS_OK\n");
1002     return DS_OK;
1003 }
1004
1005 static HRESULT WINAPI
1006 IDirectSoundCaptureBufferImpl_Initialize(
1007     LPDIRECTSOUNDCAPTUREBUFFER8 iface,
1008     LPDIRECTSOUNDCAPTURE lpDSC,
1009     LPCDSCBUFFERDESC lpcDSCBDesc )
1010 {
1011     IDirectSoundCaptureBufferImpl *This = (IDirectSoundCaptureBufferImpl *)iface;
1012
1013     FIXME( "(%p,%p,%p): stub\n", This, lpDSC, lpcDSCBDesc );
1014
1015     return DS_OK;
1016 }
1017
1018 static HRESULT WINAPI
1019 IDirectSoundCaptureBufferImpl_Lock(
1020     LPDIRECTSOUNDCAPTUREBUFFER8 iface,
1021     DWORD dwReadCusor,
1022     DWORD dwReadBytes,
1023     LPVOID* lplpvAudioPtr1,
1024     LPDWORD lpdwAudioBytes1,
1025     LPVOID* lplpvAudioPtr2,
1026     LPDWORD lpdwAudioBytes2,
1027     DWORD dwFlags )
1028 {
1029     HRESULT hres = DS_OK;
1030     IDirectSoundCaptureBufferImpl *This = (IDirectSoundCaptureBufferImpl *)iface;
1031     TRACE( "(%p,%08u,%08u,%p,%p,%p,%p,0x%08x) at %d\n", This, dwReadCusor,
1032         dwReadBytes, lplpvAudioPtr1, lpdwAudioBytes1, lplpvAudioPtr2,
1033         lpdwAudioBytes2, dwFlags, GetTickCount() );
1034
1035     if (This->device == NULL) {
1036         WARN("invalid parameter: This->device == NULL\n");
1037         return DSERR_INVALIDPARAM;
1038     }
1039
1040     if (lplpvAudioPtr1 == NULL) {
1041         WARN("invalid parameter: lplpvAudioPtr1 == NULL\n");
1042         return DSERR_INVALIDPARAM;
1043     }
1044
1045     if (lpdwAudioBytes1 == NULL) {
1046         WARN("invalid parameter: lpdwAudioBytes1 == NULL\n");
1047         return DSERR_INVALIDPARAM;
1048     }
1049
1050     EnterCriticalSection(&(This->device->lock));
1051
1052     if (This->device->driver) {
1053         hres = IDsCaptureDriverBuffer_Lock(This->device->hwbuf, lplpvAudioPtr1,
1054                                            lpdwAudioBytes1, lplpvAudioPtr2,
1055                                            lpdwAudioBytes2, dwReadCusor,
1056                                            dwReadBytes, dwFlags);
1057         if (hres != DS_OK)
1058             WARN("IDsCaptureDriverBuffer_Lock failed\n");
1059     } else if (This->device->hwi) {
1060         *lplpvAudioPtr1 = This->device->buffer + dwReadCusor;
1061         if ( (dwReadCusor + dwReadBytes) > This->device->buflen) {
1062             *lpdwAudioBytes1 = This->device->buflen - dwReadCusor;
1063             if (lplpvAudioPtr2)
1064                 *lplpvAudioPtr2 = This->device->buffer;
1065             if (lpdwAudioBytes2)
1066                 *lpdwAudioBytes2 = dwReadBytes - *lpdwAudioBytes1;
1067         } else {
1068             *lpdwAudioBytes1 = dwReadBytes;
1069             if (lplpvAudioPtr2)
1070                 *lplpvAudioPtr2 = 0;
1071             if (lpdwAudioBytes2)
1072                 *lpdwAudioBytes2 = 0;
1073         }
1074     } else {
1075         TRACE("invalid call\n");
1076         hres = DSERR_INVALIDCALL;   /* DSERR_NODRIVER ? */
1077     }
1078
1079     LeaveCriticalSection(&(This->device->lock));
1080
1081     TRACE("returning %08x\n", hres);
1082     return hres;
1083 }
1084
1085 static HRESULT WINAPI
1086 IDirectSoundCaptureBufferImpl_Start(
1087     LPDIRECTSOUNDCAPTUREBUFFER8 iface,
1088     DWORD dwFlags )
1089 {
1090     HRESULT hres = DS_OK;
1091     IDirectSoundCaptureBufferImpl *This = (IDirectSoundCaptureBufferImpl *)iface;
1092     TRACE( "(%p,0x%08x)\n", This, dwFlags );
1093
1094     if (This->device == NULL) {
1095         WARN("invalid parameter: This->device == NULL\n");
1096         return DSERR_INVALIDPARAM;
1097     }
1098
1099     if ( (This->device->driver == 0) && (This->device->hwi == 0) ) {
1100         WARN("no driver\n");
1101         return DSERR_NODRIVER;
1102     }
1103
1104     EnterCriticalSection(&(This->device->lock));
1105
1106     This->flags = dwFlags;
1107     TRACE("old This->state=%s\n",captureStateString[This->device->state]);
1108     if (This->device->state == STATE_STOPPED)
1109         This->device->state = STATE_STARTING;
1110     else if (This->device->state == STATE_STOPPING)
1111         This->device->state = STATE_CAPTURING;
1112     TRACE("new This->device->state=%s\n",captureStateString[This->device->state]);
1113
1114     LeaveCriticalSection(&(This->device->lock));
1115
1116     if (This->device->driver) {
1117         hres = IDsCaptureDriverBuffer_Start(This->device->hwbuf, dwFlags);
1118         if (hres != DS_OK)
1119             WARN("IDsCaptureDriverBuffer_Start failed\n");
1120     } else if (This->device->hwi) {
1121         DirectSoundCaptureDevice *device = This->device;
1122
1123         if (device->buffer) {
1124             if (This->nrofnotifies) {
1125                 int c;
1126
1127                 device->nrofpwaves = This->nrofnotifies;
1128                 TRACE("nrofnotifies=%d\n", This->nrofnotifies);
1129
1130                 /* prepare headers */
1131                 if (device->pwave)
1132                     device->pwave = HeapReAlloc(GetProcessHeap(),0,device->pwave,
1133                         device->nrofpwaves*sizeof(WAVEHDR));
1134                 else
1135                     device->pwave = HeapAlloc(GetProcessHeap(),0,
1136                         device->nrofpwaves*sizeof(WAVEHDR));
1137
1138                 for (c = 0; c < device->nrofpwaves; c++) {
1139                     if (This->notifies[c].dwOffset == DSBPN_OFFSETSTOP) {
1140                         TRACE("got DSBPN_OFFSETSTOP\n");
1141                         device->nrofpwaves = c;
1142                         break;
1143                     }
1144                     if (c == 0) {
1145                         device->pwave[0].lpData = (LPSTR)device->buffer;
1146                         device->pwave[0].dwBufferLength =
1147                             This->notifies[0].dwOffset + 1;
1148                     } else {
1149                         device->pwave[c].lpData = (LPSTR)device->buffer +
1150                             This->notifies[c-1].dwOffset + 1;
1151                         device->pwave[c].dwBufferLength =
1152                             This->notifies[c].dwOffset -
1153                             This->notifies[c-1].dwOffset;
1154                     }
1155                     device->pwave[c].dwBytesRecorded = 0;
1156                     device->pwave[c].dwUser = (DWORD)device;
1157                     device->pwave[c].dwFlags = 0;
1158                     device->pwave[c].dwLoops = 0;
1159                     hres = mmErr(waveInPrepareHeader(device->hwi,
1160                         &(device->pwave[c]),sizeof(WAVEHDR)));
1161                     if (hres != DS_OK) {
1162                         WARN("waveInPrepareHeader failed\n");
1163                         while (c--)
1164                             waveInUnprepareHeader(device->hwi,
1165                                 &(device->pwave[c]),sizeof(WAVEHDR));
1166                         break;
1167                     }
1168
1169                     hres = mmErr(waveInAddBuffer(device->hwi,
1170                         &(device->pwave[c]), sizeof(WAVEHDR)));
1171                     if (hres != DS_OK) {
1172                         WARN("waveInAddBuffer failed\n");
1173                         while (c--)
1174                             waveInUnprepareHeader(device->hwi,
1175                                 &(device->pwave[c]),sizeof(WAVEHDR));
1176                         break;
1177                     }
1178                 }
1179
1180                 FillMemory(device->buffer, device->buflen,
1181                     (device->pwfx->wBitsPerSample == 8) ? 128 : 0);
1182             } else {
1183                 TRACE("no notifiers specified\n");
1184                 /* no notifiers specified so just create a single default header */
1185                 device->nrofpwaves = 1;
1186                 if (device->pwave)
1187                     device->pwave = HeapReAlloc(GetProcessHeap(),0,device->pwave,sizeof(WAVEHDR));
1188                 else
1189                     device->pwave = HeapAlloc(GetProcessHeap(),0,sizeof(WAVEHDR));
1190
1191                 device->pwave[0].lpData = (LPSTR)device->buffer;
1192                 device->pwave[0].dwBufferLength = device->buflen;
1193                 device->pwave[0].dwBytesRecorded = 0;
1194                 device->pwave[0].dwUser = (DWORD)device;
1195                 device->pwave[0].dwFlags = 0;
1196                 device->pwave[0].dwLoops = 0;
1197
1198                 hres = mmErr(waveInPrepareHeader(device->hwi,
1199                     &(device->pwave[0]),sizeof(WAVEHDR)));
1200                 if (hres != DS_OK) {
1201                     WARN("waveInPrepareHeader failed\n");
1202                     waveInUnprepareHeader(device->hwi,
1203                         &(device->pwave[0]),sizeof(WAVEHDR));
1204                 }
1205                 hres = mmErr(waveInAddBuffer(device->hwi,
1206                     &(device->pwave[0]), sizeof(WAVEHDR)));
1207                 if (hres != DS_OK) {
1208                     WARN("waveInAddBuffer failed\n");
1209                     waveInUnprepareHeader(device->hwi,
1210                         &(device->pwave[0]),sizeof(WAVEHDR));
1211                 }
1212             }
1213         }
1214
1215         device->index = 0;
1216         device->read_position = 0;
1217
1218         if (hres == DS_OK) {
1219             /* start filling the first buffer */
1220             hres = mmErr(waveInStart(device->hwi));
1221             if (hres != DS_OK)
1222                 WARN("waveInStart failed\n");
1223         }
1224
1225         if (hres != DS_OK) {
1226             WARN("calling waveInClose because of error\n");
1227             waveInClose(device->hwi);
1228             device->hwi = 0;
1229         }
1230     } else {
1231         WARN("no driver\n");
1232         hres = DSERR_NODRIVER;
1233     }
1234
1235     TRACE("returning %08x\n", hres);
1236     return hres;
1237 }
1238
1239 static HRESULT WINAPI
1240 IDirectSoundCaptureBufferImpl_Stop( LPDIRECTSOUNDCAPTUREBUFFER8 iface )
1241 {
1242     HRESULT hres = DS_OK;
1243     IDirectSoundCaptureBufferImpl *This = (IDirectSoundCaptureBufferImpl *)iface;
1244     TRACE( "(%p)\n", This );
1245
1246     if (This->device == NULL) {
1247         WARN("invalid parameter: This->device == NULL\n");
1248         return DSERR_INVALIDPARAM;
1249     }
1250
1251     EnterCriticalSection(&(This->device->lock));
1252
1253     TRACE("old This->device->state=%s\n",captureStateString[This->device->state]);
1254     if (This->device->state == STATE_CAPTURING)
1255         This->device->state = STATE_STOPPING;
1256     else if (This->device->state == STATE_STARTING)
1257         This->device->state = STATE_STOPPED;
1258     TRACE("new This->device->state=%s\n",captureStateString[This->device->state]);
1259
1260     LeaveCriticalSection(&(This->device->lock));
1261
1262     if (This->device->driver) {
1263         hres = IDsCaptureDriverBuffer_Stop(This->device->hwbuf);
1264         if (hres != DS_OK)
1265             WARN("IDsCaptureDriverBuffer_Stop() failed\n");
1266     } else if (This->device->hwi) {
1267         hres = mmErr(waveInReset(This->device->hwi));
1268         if (hres != DS_OK)
1269             WARN("waveInReset() failed\n");
1270     } else {
1271         WARN("no driver\n");
1272         hres = DSERR_NODRIVER;
1273     }
1274
1275     TRACE("returning %08x\n", hres);
1276     return hres;
1277 }
1278
1279 static HRESULT WINAPI
1280 IDirectSoundCaptureBufferImpl_Unlock(
1281     LPDIRECTSOUNDCAPTUREBUFFER8 iface,
1282     LPVOID lpvAudioPtr1,
1283     DWORD dwAudioBytes1,
1284     LPVOID lpvAudioPtr2,
1285     DWORD dwAudioBytes2 )
1286 {
1287     HRESULT hres = DS_OK;
1288     IDirectSoundCaptureBufferImpl *This = (IDirectSoundCaptureBufferImpl *)iface;
1289     TRACE( "(%p,%p,%08u,%p,%08u)\n", This, lpvAudioPtr1, dwAudioBytes1,
1290         lpvAudioPtr2, dwAudioBytes2 );
1291
1292     if (lpvAudioPtr1 == NULL) {
1293         WARN("invalid parameter: lpvAudioPtr1 == NULL\n");
1294         return DSERR_INVALIDPARAM;
1295     }
1296
1297     if (This->device->driver) {
1298         hres = IDsCaptureDriverBuffer_Unlock(This->device->hwbuf, lpvAudioPtr1,
1299                                              dwAudioBytes1, lpvAudioPtr2, dwAudioBytes2);
1300         if (hres != DS_OK)
1301             WARN("IDsCaptureDriverBuffer_Unlock failed\n");
1302     } else if (This->device->hwi) {
1303         This->device->read_position = (This->device->read_position +
1304             (dwAudioBytes1 + dwAudioBytes2)) % This->device->buflen;
1305     } else {
1306         WARN("invalid call\n");
1307         hres = DSERR_INVALIDCALL;
1308     }
1309
1310     TRACE("returning %08x\n", hres);
1311     return hres;
1312 }
1313
1314 static HRESULT WINAPI
1315 IDirectSoundCaptureBufferImpl_GetObjectInPath(
1316     LPDIRECTSOUNDCAPTUREBUFFER8 iface,
1317     REFGUID rguidObject,
1318     DWORD dwIndex,
1319     REFGUID rguidInterface,
1320     LPVOID* ppObject )
1321 {
1322     IDirectSoundCaptureBufferImpl *This = (IDirectSoundCaptureBufferImpl *)iface;
1323
1324     FIXME( "(%p,%s,%u,%s,%p): stub\n", This, debugstr_guid(rguidObject),
1325         dwIndex, debugstr_guid(rguidInterface), ppObject );
1326
1327     return DS_OK;
1328 }
1329
1330 static HRESULT WINAPI
1331 IDirectSoundCaptureBufferImpl_GetFXStatus(
1332     LPDIRECTSOUNDCAPTUREBUFFER8 iface,
1333     DWORD dwFXCount,
1334     LPDWORD pdwFXStatus )
1335 {
1336     IDirectSoundCaptureBufferImpl *This = (IDirectSoundCaptureBufferImpl *)iface;
1337
1338     FIXME( "(%p,%u,%p): stub\n", This, dwFXCount, pdwFXStatus );
1339
1340     return DS_OK;
1341 }
1342
1343 static const IDirectSoundCaptureBuffer8Vtbl dscbvt =
1344 {
1345     /* IUnknown methods */
1346     IDirectSoundCaptureBufferImpl_QueryInterface,
1347     IDirectSoundCaptureBufferImpl_AddRef,
1348     IDirectSoundCaptureBufferImpl_Release,
1349
1350     /* IDirectSoundCaptureBuffer methods */
1351     IDirectSoundCaptureBufferImpl_GetCaps,
1352     IDirectSoundCaptureBufferImpl_GetCurrentPosition,
1353     IDirectSoundCaptureBufferImpl_GetFormat,
1354     IDirectSoundCaptureBufferImpl_GetStatus,
1355     IDirectSoundCaptureBufferImpl_Initialize,
1356     IDirectSoundCaptureBufferImpl_Lock,
1357     IDirectSoundCaptureBufferImpl_Start,
1358     IDirectSoundCaptureBufferImpl_Stop,
1359     IDirectSoundCaptureBufferImpl_Unlock,
1360
1361     /* IDirectSoundCaptureBuffer methods */
1362     IDirectSoundCaptureBufferImpl_GetObjectInPath,
1363     IDirectSoundCaptureBufferImpl_GetFXStatus
1364 };
1365
1366 HRESULT IDirectSoundCaptureBufferImpl_Create(
1367     DirectSoundCaptureDevice *device,
1368     IDirectSoundCaptureBufferImpl ** ppobj,
1369     LPCDSCBUFFERDESC lpcDSCBufferDesc)
1370 {
1371     LPWAVEFORMATEX  wfex;
1372     TRACE( "(%p,%p,%p)\n", device, ppobj, lpcDSCBufferDesc);
1373
1374     if (ppobj == NULL) {
1375         WARN("invalid parameter: ppobj == NULL\n");
1376         return DSERR_INVALIDPARAM;
1377     }
1378
1379     if (!device) {
1380         WARN("not initialized\n");
1381         *ppobj = NULL;
1382         return DSERR_UNINITIALIZED;
1383     }
1384
1385     if (lpcDSCBufferDesc == NULL) {
1386         WARN("invalid parameter: lpcDSCBufferDesc == NULL\n");
1387         *ppobj = NULL;
1388         return DSERR_INVALIDPARAM;
1389     }
1390
1391     if ( ((lpcDSCBufferDesc->dwSize != sizeof(DSCBUFFERDESC)) &&
1392           (lpcDSCBufferDesc->dwSize != sizeof(DSCBUFFERDESC1))) ||
1393         (lpcDSCBufferDesc->dwBufferBytes == 0) ||
1394         (lpcDSCBufferDesc->lpwfxFormat == NULL) ) {
1395         WARN("invalid lpcDSCBufferDesc\n");
1396         *ppobj = NULL;
1397         return DSERR_INVALIDPARAM;
1398     }
1399
1400     wfex = lpcDSCBufferDesc->lpwfxFormat;
1401
1402     if (wfex) {
1403         TRACE("(formattag=0x%04x,chans=%d,samplerate=%d,"
1404             "bytespersec=%d,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
1405             wfex->wFormatTag, wfex->nChannels, wfex->nSamplesPerSec,
1406             wfex->nAvgBytesPerSec, wfex->nBlockAlign,
1407             wfex->wBitsPerSample, wfex->cbSize);
1408
1409         if (wfex->wFormatTag == WAVE_FORMAT_PCM) {
1410             device->pwfx = HeapAlloc(GetProcessHeap(),0,sizeof(WAVEFORMATEX));
1411             CopyMemory(device->pwfx, wfex, sizeof(WAVEFORMATEX));
1412             device->pwfx->cbSize = 0;
1413         } else {
1414             device->pwfx = HeapAlloc(GetProcessHeap(),0,sizeof(WAVEFORMATEX)+wfex->cbSize);
1415             CopyMemory(device->pwfx, wfex, sizeof(WAVEFORMATEX)+wfex->cbSize);
1416         }
1417     } else {
1418         WARN("lpcDSCBufferDesc->lpwfxFormat == 0\n");
1419         *ppobj = NULL;
1420         return DSERR_INVALIDPARAM; /* FIXME: DSERR_BADFORMAT ? */
1421     }
1422
1423     *ppobj = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
1424         sizeof(IDirectSoundCaptureBufferImpl));
1425
1426     if ( *ppobj == NULL ) {
1427         WARN("out of memory\n");
1428         *ppobj = NULL;
1429         return DSERR_OUTOFMEMORY;
1430     } else {
1431         HRESULT err = DS_OK;
1432         LPBYTE newbuf;
1433         DWORD buflen;
1434         IDirectSoundCaptureBufferImpl *This = (IDirectSoundCaptureBufferImpl *)*ppobj;
1435
1436         This->ref = 1;
1437         This->device = device;
1438         This->device->capture_buffer = This;
1439         This->notify = NULL;
1440         This->nrofnotifies = 0;
1441         This->hwnotify = NULL;
1442
1443         This->pdscbd = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
1444             lpcDSCBufferDesc->dwSize);
1445         if (This->pdscbd)
1446             CopyMemory(This->pdscbd, lpcDSCBufferDesc, lpcDSCBufferDesc->dwSize);
1447         else {
1448             WARN("no memory\n");
1449             This->device->capture_buffer = 0;
1450             HeapFree( GetProcessHeap(), 0, This );
1451             *ppobj = NULL;
1452             return DSERR_OUTOFMEMORY;
1453         }
1454
1455         This->lpVtbl = &dscbvt;
1456
1457         if (device->driver) {
1458             if (This->device->drvdesc.dwFlags & DSDDESC_DOMMSYSTEMOPEN)
1459                 FIXME("DSDDESC_DOMMSYSTEMOPEN not supported\n");
1460
1461             if (This->device->drvdesc.dwFlags & DSDDESC_USESYSTEMMEMORY) {
1462                 /* allocate buffer from system memory */
1463                 buflen = lpcDSCBufferDesc->dwBufferBytes;
1464                 TRACE("desired buflen=%d, old buffer=%p\n", buflen, device->buffer);
1465                 if (device->buffer)
1466                     newbuf = HeapReAlloc(GetProcessHeap(),0,device->buffer,buflen);
1467                 else
1468                     newbuf = HeapAlloc(GetProcessHeap(),0,buflen);
1469
1470                 if (newbuf == NULL) {
1471                     WARN("failed to allocate capture buffer\n");
1472                     err = DSERR_OUTOFMEMORY;
1473                     /* but the old buffer might still exist and must be re-prepared */
1474                 } else {
1475                     device->buffer = newbuf;
1476                     device->buflen = buflen;
1477                 }
1478             } else {
1479                 /* let driver allocate memory */
1480                 device->buflen = lpcDSCBufferDesc->dwBufferBytes;
1481                 /* FIXME: */
1482                 HeapFree( GetProcessHeap(), 0, device->buffer);
1483                 device->buffer = NULL;
1484             }
1485
1486             err = IDsCaptureDriver_CreateCaptureBuffer(device->driver,
1487                 device->pwfx,0,0,&(device->buflen),&(device->buffer),(LPVOID*)&(device->hwbuf));
1488             if (err != DS_OK) {
1489                 WARN("IDsCaptureDriver_CreateCaptureBuffer failed\n");
1490                 This->device->capture_buffer = 0;
1491                 HeapFree( GetProcessHeap(), 0, This );
1492                 *ppobj = NULL;
1493                 return err;
1494             }
1495         } else {
1496             DWORD flags = CALLBACK_FUNCTION;
1497             err = mmErr(waveInOpen(&(device->hwi),
1498                 device->drvdesc.dnDevNode, device->pwfx,
1499                 (DWORD_PTR)DSOUND_capture_callback, (DWORD)device, flags));
1500             if (err != DS_OK) {
1501                 WARN("waveInOpen failed\n");
1502                 This->device->capture_buffer = 0;
1503                 HeapFree( GetProcessHeap(), 0, This );
1504                 *ppobj = NULL;
1505                 return err;
1506             }
1507
1508             buflen = lpcDSCBufferDesc->dwBufferBytes;
1509             TRACE("desired buflen=%d, old buffer=%p\n", buflen, device->buffer);
1510             if (device->buffer)
1511                 newbuf = HeapReAlloc(GetProcessHeap(),0,device->buffer,buflen);
1512             else
1513                 newbuf = HeapAlloc(GetProcessHeap(),0,buflen);
1514             if (newbuf == NULL) {
1515                 WARN("failed to allocate capture buffer\n");
1516                 err = DSERR_OUTOFMEMORY;
1517                 /* but the old buffer might still exist and must be re-prepared */
1518             } else {
1519                 device->buffer = newbuf;
1520                 device->buflen = buflen;
1521             }
1522         }
1523     }
1524
1525     TRACE("returning DS_OK\n");
1526     return DS_OK;
1527 }
1528
1529 /*******************************************************************************
1530  * DirectSoundCaptureDevice
1531  */
1532 HRESULT DirectSoundCaptureDevice_Initialize(
1533     DirectSoundCaptureDevice ** ppDevice,
1534     LPCGUID lpcGUID)
1535 {
1536     HRESULT err = DSERR_INVALIDPARAM;
1537     unsigned wid, widn;
1538     BOOLEAN found = FALSE;
1539     GUID devGUID;
1540     DirectSoundCaptureDevice *device = *ppDevice;
1541     TRACE("(%p, %s)\n", ppDevice, debugstr_guid(lpcGUID));
1542
1543     /* Default device? */
1544     if ( !lpcGUID || IsEqualGUID(lpcGUID, &GUID_NULL) )
1545         lpcGUID = &DSDEVID_DefaultCapture;
1546
1547     if (GetDeviceID(lpcGUID, &devGUID) != DS_OK) {
1548         WARN("invalid parameter: lpcGUID\n");
1549         return DSERR_INVALIDPARAM;
1550     }
1551
1552     widn = waveInGetNumDevs();
1553     if (!widn) {
1554         WARN("no audio devices found\n");
1555         return DSERR_NODRIVER;
1556     }
1557
1558     /* enumerate WINMM audio devices and find the one we want */
1559     for (wid=0; wid<widn; wid++) {
1560         if (IsEqualGUID( &devGUID, &DSOUND_capture_guids[wid]) ) {
1561             found = TRUE;
1562             break;
1563         }
1564     }
1565
1566     if (found == FALSE) {
1567         WARN("No device found matching given ID!\n");
1568         return DSERR_NODRIVER;
1569     }
1570
1571     if (DSOUND_capture[wid]) {
1572         WARN("already in use\n");
1573         return DSERR_ALLOCATED;
1574     }
1575
1576     err = DirectSoundCaptureDevice_Create(&(device));
1577     if (err != DS_OK) {
1578         WARN("DirectSoundCaptureDevice_Create failed\n");
1579         return err;
1580     }
1581
1582     *ppDevice = device;
1583     device->guid = devGUID;
1584
1585     /* Disable the direct sound driver to force emulation if requested. */
1586     device->driver = NULL;
1587     if (ds_hw_accel > DS_HW_ACCEL_EMULATION)
1588     {
1589         err = mmErr(waveInMessage((HWAVEIN)wid,DRV_QUERYDSOUNDIFACE,(DWORD_PTR)&(device->driver),0));
1590         if ( (err != DS_OK) && (err != DSERR_UNSUPPORTED) ) {
1591             WARN("waveInMessage failed; err=%x\n",err);
1592             return err;
1593         }
1594     }
1595     err = DS_OK;
1596
1597
1598     /* Get driver description */
1599     if (device->driver) {
1600         TRACE("using DirectSound driver\n");
1601         err = IDsCaptureDriver_GetDriverDesc(device->driver, &(device->drvdesc));
1602         if (err != DS_OK) {
1603             WARN("IDsCaptureDriver_GetDriverDesc failed\n");
1604             return err;
1605         }
1606     } else {
1607         TRACE("using WINMM\n");
1608         /* if no DirectSound interface available, use WINMM API instead */
1609         device->drvdesc.dwFlags = DSDDESC_DOMMSYSTEMOPEN |
1610             DSDDESC_DOMMSYSTEMSETFORMAT;
1611     }
1612
1613     device->drvdesc.dnDevNode = wid;
1614
1615     /* open the DirectSound driver if available */
1616     if (device->driver && (err == DS_OK))
1617         err = IDsCaptureDriver_Open(device->driver);
1618
1619     if (err == DS_OK) {
1620         *ppDevice = device;
1621
1622         /* the driver is now open, so it's now allowed to call GetCaps */
1623         if (device->driver) {
1624             device->drvcaps.dwSize = sizeof(device->drvcaps);
1625             err = IDsCaptureDriver_GetCaps(device->driver,&(device->drvcaps));
1626             if (err != DS_OK) {
1627                 WARN("IDsCaptureDriver_GetCaps failed\n");
1628                 return err;
1629             }
1630         } else /*if (device->hwi)*/ {
1631             WAVEINCAPSA    wic;
1632             err = mmErr(waveInGetDevCapsA((UINT)device->drvdesc.dnDevNode, &wic, sizeof(wic)));
1633
1634             if (err == DS_OK) {
1635                 device->drvcaps.dwFlags = 0;
1636                 lstrcpynA(device->drvdesc.szDrvname, wic.szPname,
1637                           sizeof(device->drvdesc.szDrvname));
1638
1639                 device->drvcaps.dwFlags |= DSCCAPS_EMULDRIVER;
1640                 device->drvcaps.dwFormats = wic.dwFormats;
1641                 device->drvcaps.dwChannels = wic.wChannels;
1642             }
1643         }
1644     }
1645
1646     return err;
1647 }
1648
1649 static HRESULT DirectSoundCaptureDevice_Create(
1650     DirectSoundCaptureDevice ** ppDevice)
1651 {
1652     DirectSoundCaptureDevice * device;
1653     TRACE("(%p)\n", ppDevice);
1654
1655     /* Allocate memory */
1656     device = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(DirectSoundCaptureDevice));
1657
1658     if (device == NULL) {
1659         WARN("out of memory\n");
1660         return DSERR_OUTOFMEMORY;
1661     }
1662
1663     device->ref = 1;
1664     device->state = STATE_STOPPED;
1665
1666     InitializeCriticalSection( &(device->lock) );
1667     device->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": DirectSoundCaptureDevice.lock");
1668
1669     *ppDevice = device;
1670
1671     return DS_OK;
1672 }
1673
1674 ULONG DirectSoundCaptureDevice_AddRef(
1675     DirectSoundCaptureDevice * device)
1676 {
1677     ULONG ref = InterlockedIncrement(&(device->ref));
1678     TRACE("(%p) ref was %d\n", device, ref - 1);
1679     return ref;
1680 }
1681
1682 ULONG DirectSoundCaptureDevice_Release(
1683     DirectSoundCaptureDevice * device)
1684 {
1685     ULONG ref = InterlockedDecrement(&(device->ref));
1686     TRACE("(%p) ref was %d\n", device, ref + 1);
1687
1688     if (!ref) {
1689         TRACE("deleting object\n");
1690         if (device->capture_buffer)
1691             IDirectSoundCaptureBufferImpl_Release(
1692                 (LPDIRECTSOUNDCAPTUREBUFFER8) device->capture_buffer);
1693
1694         if (device->driver) {
1695             IDsCaptureDriver_Close(device->driver);
1696             IDsCaptureDriver_Release(device->driver);
1697         }
1698
1699         HeapFree(GetProcessHeap(), 0, device->pwfx);
1700         device->lock.DebugInfo->Spare[0] = 0;
1701         DeleteCriticalSection( &(device->lock) );
1702         DSOUND_capture[device->drvdesc.dnDevNode] = NULL;
1703         HeapFree(GetProcessHeap(), 0, device);
1704         TRACE("(%p) released\n", device);
1705     }
1706     return ref;
1707 }