kernel32: Add the directory the executable was loaded from to the module search path...
[wine] / dlls / wineoss.drv / dsrender.c
1 /*
2  * Sample Wine Driver for Open Sound System (featured in Linux and FreeBSD)
3  *
4  * Copyright 1994 Martin Ayotte
5  *           1999 Eric Pouech (async playing in waveOut/waveIn)
6  *           2000 Eric Pouech (loops in waveOut)
7  *           2002 Eric Pouech (full duplex)
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
27 #include <stdlib.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34 #include <errno.h>
35 #include <fcntl.h>
36 #ifdef HAVE_SYS_IOCTL_H
37 # include <sys/ioctl.h>
38 #endif
39 #ifdef HAVE_SYS_MMAN_H
40 # include <sys/mman.h>
41 #endif
42 #ifdef HAVE_POLL_H
43 #include <poll.h>
44 #endif
45 #ifdef HAVE_SYS_POLL_H
46 # include <sys/poll.h>
47 #endif
48
49 #include "windef.h"
50 #include "winbase.h"
51 #include "wingdi.h"
52 #include "winuser.h"
53 #include "winerror.h"
54 #include "mmddk.h"
55 #include "mmreg.h"
56 #include "dsound.h"
57 #include "dsdriver.h"
58 #include "oss.h"
59 #include "wine/debug.h"
60
61 #include "audio.h"
62
63 WINE_DEFAULT_DEBUG_CHANNEL(wave);
64
65 #ifdef HAVE_OSS
66
67 /*======================================================================*
68  *                  Low level DSOUND definitions                        *
69  *======================================================================*/
70
71 typedef struct IDsDriverPropertySetImpl IDsDriverPropertySetImpl;
72 typedef struct IDsDriverNotifyImpl IDsDriverNotifyImpl;
73 typedef struct IDsDriverImpl IDsDriverImpl;
74 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
75
76 struct IDsDriverPropertySetImpl
77 {
78     /* IUnknown fields */
79     const IDsDriverPropertySetVtbl *lpVtbl;
80     LONG                        ref;
81
82     IDsDriverBufferImpl*        buffer;
83 };
84
85 struct IDsDriverNotifyImpl
86 {
87     /* IUnknown fields */
88     const IDsDriverNotifyVtbl  *lpVtbl;
89     LONG                        ref;
90
91     /* IDsDriverNotifyImpl fields */
92     LPDSBPOSITIONNOTIFY         notifies;
93     int                         nrofnotifies;
94
95     IDsDriverBufferImpl*        buffer;
96 };
97
98 struct IDsDriverImpl
99 {
100     /* IUnknown fields */
101     const IDsDriverVtbl        *lpVtbl;
102     LONG                        ref;
103
104     /* IDsDriverImpl fields */
105     UINT                        wDevID;
106     IDsDriverBufferImpl*        primary;
107
108     int                         nrofsecondaries;
109     IDsDriverBufferImpl**       secondaries;
110 };
111
112 struct IDsDriverBufferImpl
113 {
114     /* IUnknown fields */
115     const IDsDriverBufferVtbl  *lpVtbl;
116     LONG                        ref;
117
118     /* IDsDriverBufferImpl fields */
119     IDsDriverImpl*              drv;
120     DWORD                       buflen;
121     WAVEFORMATPCMEX             wfex;
122     LPBYTE                      mapping;
123     DWORD                       maplen;
124     int                         fd;
125     DWORD                       dwFlags;
126
127     /* IDsDriverNotifyImpl fields */
128     IDsDriverNotifyImpl*        notify;
129     int                         notify_index;
130
131     /* IDsDriverPropertySetImpl fields */
132     IDsDriverPropertySetImpl*   property_set;
133 };
134
135 static HRESULT WINAPI IDsDriverPropertySetImpl_Create(
136     IDsDriverBufferImpl * dsdb,
137     IDsDriverPropertySetImpl **pdsdps);
138
139 static HRESULT WINAPI IDsDriverNotifyImpl_Create(
140     IDsDriverBufferImpl * dsdb,
141     IDsDriverNotifyImpl **pdsdn);
142
143 /*======================================================================*
144  *                  Low level DSOUND property set implementation        *
145  *======================================================================*/
146
147 static HRESULT WINAPI IDsDriverPropertySetImpl_QueryInterface(
148     PIDSDRIVERPROPERTYSET iface,
149     REFIID riid,
150     LPVOID *ppobj)
151 {
152     IDsDriverPropertySetImpl *This = (IDsDriverPropertySetImpl *)iface;
153     TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
154
155     if ( IsEqualGUID(riid, &IID_IUnknown) ||
156          IsEqualGUID(riid, &IID_IDsDriverPropertySet) ) {
157         IDsDriverPropertySet_AddRef(iface);
158         *ppobj = (LPVOID)This;
159         return DS_OK;
160     }
161
162     FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
163
164     *ppobj = 0;
165     return E_NOINTERFACE;
166 }
167
168 static ULONG WINAPI IDsDriverPropertySetImpl_AddRef(PIDSDRIVERPROPERTYSET iface)
169 {
170     IDsDriverPropertySetImpl *This = (IDsDriverPropertySetImpl *)iface;
171     ULONG refCount = InterlockedIncrement(&This->ref);
172
173     TRACE("(%p) ref was %d\n", This, refCount - 1);
174
175     return refCount;
176 }
177
178 static ULONG WINAPI IDsDriverPropertySetImpl_Release(PIDSDRIVERPROPERTYSET iface)
179 {
180     IDsDriverPropertySetImpl *This = (IDsDriverPropertySetImpl *)iface;
181     ULONG refCount = InterlockedDecrement(&This->ref);
182
183     TRACE("(%p) ref was %d\n", This, refCount + 1);
184
185     if (!refCount) {
186         IDsDriverBuffer_Release((PIDSDRIVERBUFFER)This->buffer);
187         HeapFree(GetProcessHeap(),0,This);
188         TRACE("(%p) released\n",This);
189     }
190     return refCount;
191 }
192
193 static HRESULT WINAPI IDsDriverPropertySetImpl_Get(
194     PIDSDRIVERPROPERTYSET iface,
195     PDSPROPERTY pDsProperty,
196     LPVOID pPropertyParams,
197     ULONG cbPropertyParams,
198     LPVOID pPropertyData,
199     ULONG cbPropertyData,
200     PULONG pcbReturnedData )
201 {
202     IDsDriverPropertySetImpl *This = (IDsDriverPropertySetImpl *)iface;
203     FIXME("(%p,%p,%p,%x,%p,%x,%p)\n",This,pDsProperty,pPropertyParams,cbPropertyParams,pPropertyData,cbPropertyData,pcbReturnedData);
204     return DSERR_UNSUPPORTED;
205 }
206
207 static HRESULT WINAPI IDsDriverPropertySetImpl_Set(
208     PIDSDRIVERPROPERTYSET iface,
209     PDSPROPERTY pDsProperty,
210     LPVOID pPropertyParams,
211     ULONG cbPropertyParams,
212     LPVOID pPropertyData,
213     ULONG cbPropertyData )
214 {
215     IDsDriverPropertySetImpl *This = (IDsDriverPropertySetImpl *)iface;
216     FIXME("(%p,%p,%p,%x,%p,%x)\n",This,pDsProperty,pPropertyParams,cbPropertyParams,pPropertyData,cbPropertyData);
217     return DSERR_UNSUPPORTED;
218 }
219
220 static HRESULT WINAPI IDsDriverPropertySetImpl_QuerySupport(
221     PIDSDRIVERPROPERTYSET iface,
222     REFGUID PropertySetId,
223     ULONG PropertyId,
224     PULONG pSupport )
225 {
226     IDsDriverPropertySetImpl *This = (IDsDriverPropertySetImpl *)iface;
227     FIXME("(%p,%s,%x,%p)\n",This,debugstr_guid(PropertySetId),PropertyId,pSupport);
228     return DSERR_UNSUPPORTED;
229 }
230
231 static const IDsDriverPropertySetVtbl dsdpsvt =
232 {
233     IDsDriverPropertySetImpl_QueryInterface,
234     IDsDriverPropertySetImpl_AddRef,
235     IDsDriverPropertySetImpl_Release,
236     IDsDriverPropertySetImpl_Get,
237     IDsDriverPropertySetImpl_Set,
238     IDsDriverPropertySetImpl_QuerySupport,
239 };
240
241 /*======================================================================*
242  *                  Low level DSOUND notify implementation              *
243  *======================================================================*/
244
245 static HRESULT WINAPI IDsDriverNotifyImpl_QueryInterface(
246     PIDSDRIVERNOTIFY iface,
247     REFIID riid,
248     LPVOID *ppobj)
249 {
250     IDsDriverNotifyImpl *This = (IDsDriverNotifyImpl *)iface;
251     TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
252
253     if ( IsEqualGUID(riid, &IID_IUnknown) ||
254          IsEqualGUID(riid, &IID_IDsDriverNotify) ) {
255         IDsDriverNotify_AddRef(iface);
256         *ppobj = This;
257         return DS_OK;
258     }
259
260     FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
261
262     *ppobj = 0;
263     return E_NOINTERFACE;
264 }
265
266 static ULONG WINAPI IDsDriverNotifyImpl_AddRef(PIDSDRIVERNOTIFY iface)
267 {
268     IDsDriverNotifyImpl *This = (IDsDriverNotifyImpl *)iface;
269     ULONG refCount = InterlockedIncrement(&This->ref);
270
271     TRACE("(%p) ref was %d\n", This, refCount - 1);
272
273     return refCount;
274 }
275
276 static ULONG WINAPI IDsDriverNotifyImpl_Release(PIDSDRIVERNOTIFY iface)
277 {
278     IDsDriverNotifyImpl *This = (IDsDriverNotifyImpl *)iface;
279     ULONG refCount = InterlockedDecrement(&This->ref);
280
281     TRACE("(%p) ref was %d\n", This, refCount + 1);
282
283     if (!refCount) {
284         IDsDriverBuffer_Release((PIDSDRIVERBUFFER)This->buffer);
285         HeapFree(GetProcessHeap(), 0, This->notifies);
286         HeapFree(GetProcessHeap(),0,This);
287         TRACE("(%p) released\n",This);
288     }
289     return refCount;
290 }
291
292 static HRESULT WINAPI IDsDriverNotifyImpl_SetNotificationPositions(
293     PIDSDRIVERNOTIFY iface,
294     DWORD howmuch,
295     LPCDSBPOSITIONNOTIFY notify)
296 {
297     IDsDriverNotifyImpl *This = (IDsDriverNotifyImpl *)iface;
298     TRACE("(%p,0x%08x,%p)\n",This,howmuch,notify);
299
300     if (!notify) {
301         WARN("invalid parameter\n");
302         return DSERR_INVALIDPARAM;
303     }
304
305     if (TRACE_ON(wave)) {
306         int i;
307         for (i=0;i<howmuch;i++)
308             TRACE("notify at %d to 0x%08x\n",
309                 notify[i].dwOffset,(DWORD)notify[i].hEventNotify);
310     }
311
312     /* Make an internal copy of the caller-supplied array.
313      * Replace the existing copy if one is already present. */
314     if (This->notifies)
315         This->notifies = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
316         This->notifies, howmuch * sizeof(DSBPOSITIONNOTIFY));
317     else
318         This->notifies = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
319         howmuch * sizeof(DSBPOSITIONNOTIFY));
320
321     memcpy(This->notifies, notify, howmuch * sizeof(DSBPOSITIONNOTIFY));
322     This->nrofnotifies = howmuch;
323
324     return S_OK;
325 }
326
327 static const IDsDriverNotifyVtbl dsdnvt =
328 {
329     IDsDriverNotifyImpl_QueryInterface,
330     IDsDriverNotifyImpl_AddRef,
331     IDsDriverNotifyImpl_Release,
332     IDsDriverNotifyImpl_SetNotificationPositions,
333 };
334
335 /*======================================================================*
336  *                  Low level DSOUND implementation                     *
337  *======================================================================*/
338
339 static HRESULT DSDB_MapBuffer(IDsDriverBufferImpl *dsdb)
340 {
341     TRACE("(%p), format=%dx%dx%d\n", dsdb, dsdb->wfex.Format.nSamplesPerSec,
342           dsdb->wfex.Format.wBitsPerSample, dsdb->wfex.Format.nChannels);
343     if (!dsdb->mapping) {
344         dsdb->mapping = mmap(NULL, dsdb->maplen, PROT_WRITE, MAP_SHARED,
345                              dsdb->fd, 0);
346         if (dsdb->mapping == (LPBYTE)-1) {
347             ERR("Could not map sound device for direct access (%s)\n", strerror(errno));
348             ERR("Please run winecfg, open \"Audio\" page and set\n"
349                 "\"Hardware Acceleration\" to \"Emulation\".\n");
350             return DSERR_GENERIC;
351         }
352         TRACE("The sound device has been mapped for direct access at %p, size=%d\n", dsdb->mapping, dsdb->maplen);
353
354         /* for some reason, es1371 and sblive! sometimes have junk in here.
355          * clear it, or we get junk noise */
356         /* some libc implementations are buggy: their memset reads from the buffer...
357          * to work around it, we have to zero the block by hand. We don't do the expected:
358          * memset(dsdb->mapping,0, dsdb->maplen);
359          */
360         {
361             unsigned char*      p1 = dsdb->mapping;
362             unsigned            len = dsdb->maplen;
363             unsigned char       silence = (dsdb->wfex.Format.wBitsPerSample == 8) ? 128 : 0;
364             unsigned long       ulsilence = (dsdb->wfex.Format.wBitsPerSample == 8) ? 0x80808080 : 0;
365
366             if (len >= 16) /* so we can have at least a 4 long area to store... */
367             {
368                 /* the mmap:ed value is (at least) dword aligned
369                  * so, start filling the complete unsigned long:s
370                  */
371                 int             b = len >> 2;
372                 unsigned long*  p4 = (unsigned long*)p1;
373
374                 while (b--) *p4++ = ulsilence;
375                 /* prepare for filling the rest */
376                 len &= 3;
377                 p1 = (unsigned char*)p4;
378             }
379             /* in all cases, fill the remaining bytes */
380             while (len-- != 0) *p1++ = silence;
381         }
382     }
383     return DS_OK;
384 }
385
386 static HRESULT DSDB_UnmapBuffer(IDsDriverBufferImpl *dsdb)
387 {
388     TRACE("(%p)\n",dsdb);
389     if (dsdb->mapping) {
390         if (munmap(dsdb->mapping, dsdb->maplen) < 0) {
391             ERR("(%p): Could not unmap sound device (%s)\n", dsdb, strerror(errno));
392             return DSERR_GENERIC;
393         }
394         dsdb->mapping = NULL;
395         TRACE("(%p): sound device unmapped\n", dsdb);
396     }
397     return DS_OK;
398 }
399
400 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
401 {
402     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
403     TRACE("(%p,%s,%p)\n",iface,debugstr_guid(riid),*ppobj);
404
405     if ( IsEqualGUID(riid, &IID_IUnknown) ||
406          IsEqualGUID(riid, &IID_IDsDriverBuffer) ) {
407         IDsDriverBuffer_AddRef(iface);
408         *ppobj = (LPVOID)This;
409         return DS_OK;
410     }
411
412     if ( IsEqualGUID( &IID_IDsDriverNotify, riid ) ) {
413         if (!This->notify)
414             IDsDriverNotifyImpl_Create(This, &(This->notify));
415         if (This->notify) {
416             IDsDriverNotify_AddRef((PIDSDRIVERNOTIFY)This->notify);
417             *ppobj = (LPVOID)This->notify;
418             return DS_OK;
419         }
420         *ppobj = 0;
421         return E_FAIL;
422     }
423
424     if ( IsEqualGUID( &IID_IDsDriverPropertySet, riid ) ) {
425         if (!This->property_set)
426             IDsDriverPropertySetImpl_Create(This, &(This->property_set));
427         if (This->property_set) {
428             IDsDriverPropertySet_AddRef((PIDSDRIVERPROPERTYSET)This->property_set);
429             *ppobj = (LPVOID)This->property_set;
430             return DS_OK;
431         }
432         *ppobj = 0;
433         return E_FAIL;
434     }
435
436     FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
437
438     *ppobj = 0;
439
440     return E_NOINTERFACE;
441 }
442
443 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
444 {
445     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
446     ULONG refCount = InterlockedIncrement(&This->ref);
447
448     TRACE("(%p) ref was %d\n", This, refCount - 1);
449
450     return refCount;
451 }
452
453 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
454 {
455     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
456     ULONG refCount = InterlockedDecrement(&This->ref);
457
458     TRACE("(%p) ref was %d\n", This, refCount + 1);
459
460     if (refCount)
461         return refCount;
462
463     if (This == This->drv->primary)
464         This->drv->primary = NULL;
465     else {
466         int i;
467         for (i = 0; i < This->drv->nrofsecondaries; i++)
468             if (This->drv->secondaries[i] == This)
469                 break;
470         if (i < This->drv->nrofsecondaries) {
471             /* Put the last buffer of the list in the (now empty) position */
472             This->drv->secondaries[i] = This->drv->secondaries[This->drv->nrofsecondaries - 1];
473             This->drv->nrofsecondaries--;
474             This->drv->secondaries = HeapReAlloc(GetProcessHeap(),0,
475                 This->drv->secondaries,
476                 sizeof(PIDSDRIVERBUFFER)*This->drv->nrofsecondaries);
477             TRACE("(%p) buffer count is now %d\n", This, This->drv->nrofsecondaries);
478         }
479
480         WOutDev[This->drv->wDevID].ossdev->ds_caps.dwFreeHwMixingAllBuffers++;
481         WOutDev[This->drv->wDevID].ossdev->ds_caps.dwFreeHwMixingStreamingBuffers++;
482     }
483
484     DSDB_UnmapBuffer(This);
485     HeapFree(GetProcessHeap(),0,This);
486     TRACE("(%p) released\n",This);
487     return 0;
488 }
489
490 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
491                                                LPVOID*ppvAudio1,LPDWORD pdwLen1,
492                                                LPVOID*ppvAudio2,LPDWORD pdwLen2,
493                                                DWORD dwWritePosition,DWORD dwWriteLen,
494                                                DWORD dwFlags)
495 {
496     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
497     /* since we (GetDriverDesc flags) have specified DSDDESC_DONTNEEDPRIMARYLOCK,
498      * and that we don't support secondary buffers, this method will never be called */
499     TRACE("(%p): stub\n",iface);
500     return DSERR_UNSUPPORTED;
501 }
502
503 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
504                                                  LPVOID pvAudio1,DWORD dwLen1,
505                                                  LPVOID pvAudio2,DWORD dwLen2)
506 {
507     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
508     TRACE("(%p): stub\n",iface);
509     return DSERR_UNSUPPORTED;
510 }
511
512 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
513                                                     LPWAVEFORMATEX pwfx)
514 {
515     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
516
517     TRACE("(%p,%p)\n",iface,pwfx);
518     /* On our request (GetDriverDesc flags), DirectSound has by now used
519      * waveOutClose/waveOutOpen to set the format...
520      * unfortunately, this means our mmap() is now gone...
521      * so we need to somehow signal to our DirectSound implementation
522      * that it should completely recreate this HW buffer...
523      * this unexpected error code should do the trick... */
524     return DSERR_BUFFERLOST;
525 }
526
527 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
528 {
529     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
530     TRACE("(%p,%d): stub\n",iface,dwFreq);
531     return DSERR_UNSUPPORTED;
532 }
533
534 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
535 {
536     DWORD vol;
537     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
538     TRACE("(%p,%p)\n",This,pVolPan);
539
540     vol = pVolPan->dwTotalLeftAmpFactor | (pVolPan->dwTotalRightAmpFactor << 16);
541
542     if (wodSetVolume(This->drv->wDevID, vol) != MMSYSERR_NOERROR) {
543         WARN("wodSetVolume failed\n");
544         return DSERR_INVALIDPARAM;
545     }
546
547     return DS_OK;
548 }
549
550 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
551 {
552     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
553     TRACE("(%p,%d): stub\n",iface,dwNewPos);
554     return DSERR_UNSUPPORTED;
555 }
556
557 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
558                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
559 {
560     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
561     count_info info;
562     DWORD ptr;
563
564     TRACE("(%p)\n",iface);
565     if (WOutDev[This->drv->wDevID].state == WINE_WS_CLOSED) {
566         ERR("device not open, but accessing?\n");
567         return DSERR_UNINITIALIZED;
568     }
569     if (ioctl(This->fd, SNDCTL_DSP_GETOPTR, &info) < 0) {
570         ERR("ioctl(%s, SNDCTL_DSP_GETOPTR) failed (%s)\n",
571             WOutDev[This->drv->wDevID].ossdev->dev_name, strerror(errno));
572         return DSERR_GENERIC;
573     }
574     ptr = info.ptr & ~3; /* align the pointer, just in case */
575     if (lpdwPlay) *lpdwPlay = ptr;
576     if (lpdwWrite) {
577         /* add some safety margin (not strictly necessary, but...) */
578         if (WOutDev[This->drv->wDevID].ossdev->duplex_out_caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
579             *lpdwWrite = ptr + 32;
580         else
581             *lpdwWrite = ptr + WOutDev[This->drv->wDevID].dwFragmentSize;
582         while (*lpdwWrite > This->buflen)
583             *lpdwWrite -= This->buflen;
584     }
585     TRACE("playpos=%d, writepos=%d\n", lpdwPlay?*lpdwPlay:0, lpdwWrite?*lpdwWrite:0);
586     return DS_OK;
587 }
588
589 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
590 {
591     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
592     int enable;
593     TRACE("(%p,%x,%x,%x)\n",iface,dwRes1,dwRes2,dwFlags);
594     WOutDev[This->drv->wDevID].ossdev->bOutputEnabled = TRUE;
595     enable = getEnables(WOutDev[This->drv->wDevID].ossdev);
596     if (ioctl(This->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
597         if (errno == EINVAL) {
598             /* Don't give up yet. OSS trigger support is inconsistent. */
599             if (WOutDev[This->drv->wDevID].ossdev->open_count == 1) {
600                 /* try the opposite input enable */
601                 if (WOutDev[This->drv->wDevID].ossdev->bInputEnabled == FALSE)
602                     WOutDev[This->drv->wDevID].ossdev->bInputEnabled = TRUE;
603                 else
604                     WOutDev[This->drv->wDevID].ossdev->bInputEnabled = FALSE;
605                 /* try it again */
606                 enable = getEnables(WOutDev[This->drv->wDevID].ossdev);
607                 if (ioctl(This->fd, SNDCTL_DSP_SETTRIGGER, &enable) >= 0)
608                     return DS_OK;
609             }
610         }
611         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n",
612             WOutDev[This->drv->wDevID].ossdev->dev_name, strerror(errno));
613         WOutDev[This->drv->wDevID].ossdev->bOutputEnabled = FALSE;
614         return DSERR_GENERIC;
615     }
616     return DS_OK;
617 }
618
619 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
620 {
621     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
622     int enable;
623     TRACE("(%p)\n",iface);
624     /* no more playing */
625     WOutDev[This->drv->wDevID].ossdev->bOutputEnabled = FALSE;
626     enable = getEnables(WOutDev[This->drv->wDevID].ossdev);
627     if (ioctl(This->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
628         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", WOutDev[This->drv->wDevID].ossdev->dev_name, strerror(errno));
629         return DSERR_GENERIC;
630     }
631 #if 0
632     /* the play position must be reset to the beginning of the buffer */
633     if (ioctl(This->fd, SNDCTL_DSP_RESET, 0) < 0) {
634         ERR("ioctl(%s, SNDCTL_DSP_RESET) failed (%s)\n", WOutDev[This->drv->wDevID].ossdev->dev_name, strerror(errno));
635         return DSERR_GENERIC;
636     }
637 #endif
638     /* Most OSS drivers just can't stop the playback without closing the device...
639      * so we need to somehow signal to our DirectSound implementation
640      * that it should completely recreate this HW buffer...
641      * this unexpected error code should do the trick... */
642     /* FIXME: ...unless we are doing full duplex, then it's not nice to close the device */
643     if (WOutDev[This->drv->wDevID].ossdev->open_count == 1)
644         return DSERR_BUFFERLOST;
645
646     return DS_OK;
647 }
648
649 static const IDsDriverBufferVtbl dsdbvt =
650 {
651     IDsDriverBufferImpl_QueryInterface,
652     IDsDriverBufferImpl_AddRef,
653     IDsDriverBufferImpl_Release,
654     IDsDriverBufferImpl_Lock,
655     IDsDriverBufferImpl_Unlock,
656     IDsDriverBufferImpl_SetFormat,
657     IDsDriverBufferImpl_SetFrequency,
658     IDsDriverBufferImpl_SetVolumePan,
659     IDsDriverBufferImpl_SetPosition,
660     IDsDriverBufferImpl_GetPosition,
661     IDsDriverBufferImpl_Play,
662     IDsDriverBufferImpl_Stop
663 };
664
665 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
666 {
667     IDsDriverImpl *This = (IDsDriverImpl *)iface;
668     TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
669
670     if ( IsEqualGUID(riid, &IID_IUnknown) ||
671          IsEqualGUID(riid, &IID_IDsDriver) ) {
672         IDsDriver_AddRef(iface);
673         *ppobj = (LPVOID)This;
674         return DS_OK;
675     }
676
677     FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
678
679     *ppobj = 0;
680
681     return E_NOINTERFACE;
682 }
683
684 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
685 {
686     IDsDriverImpl *This = (IDsDriverImpl *)iface;
687     ULONG refCount = InterlockedIncrement(&This->ref);
688
689     TRACE("(%p) ref was %d\n", This, refCount - 1);
690
691     return refCount;
692 }
693
694 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
695 {
696     IDsDriverImpl *This = (IDsDriverImpl *)iface;
697     ULONG refCount = InterlockedDecrement(&This->ref);
698
699     TRACE("(%p) ref was %d\n", This, refCount + 1);
700
701     if (!refCount) {
702         HeapFree(GetProcessHeap(),0,This);
703         TRACE("(%p) released\n",This);
704     }
705     return refCount;
706 }
707
708 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface,
709                                                   PDSDRIVERDESC pDesc)
710 {
711     IDsDriverImpl *This = (IDsDriverImpl *)iface;
712     TRACE("(%p,%p)\n",iface,pDesc);
713
714     /* copy version from driver */
715     memcpy(pDesc, &(WOutDev[This->wDevID].ossdev->ds_desc), sizeof(DSDRIVERDESC));
716
717     pDesc->dwFlags |= DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
718         DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK |
719         DSDDESC_DONTNEEDSECONDARYLOCK;
720     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
721     pDesc->wVxdId               = 0;
722     pDesc->wReserved            = 0;
723     pDesc->ulDeviceNum          = This->wDevID;
724     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
725     pDesc->pvDirectDrawHeap     = NULL;
726     pDesc->dwMemStartAddress    = 0;
727     pDesc->dwMemEndAddress      = 0;
728     pDesc->dwMemAllocExtra      = 0;
729     pDesc->pvReserved1          = NULL;
730     pDesc->pvReserved2          = NULL;
731     return DS_OK;
732 }
733
734 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
735 {
736     IDsDriverImpl *This = (IDsDriverImpl *)iface;
737     int enable;
738     TRACE("(%p)\n",iface);
739
740     /* make sure the card doesn't start playing before we want it to */
741     WOutDev[This->wDevID].ossdev->bOutputEnabled = FALSE;
742     WOutDev[This->wDevID].ossdev->bInputEnabled = FALSE;
743     enable = getEnables(WOutDev[This->wDevID].ossdev);
744     if (ioctl(WOutDev[This->wDevID].ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
745         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n",WOutDev[This->wDevID].ossdev->dev_name, strerror(errno));
746         return DSERR_GENERIC;
747     }
748     return DS_OK;
749 }
750
751 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
752 {
753     IDsDriverImpl *This = (IDsDriverImpl *)iface;
754     TRACE("(%p)\n",iface);
755     if (This->primary) {
756         ERR("problem with DirectSound: primary not released\n");
757         return DSERR_GENERIC;
758     }
759     return DS_OK;
760 }
761
762 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
763 {
764     IDsDriverImpl *This = (IDsDriverImpl *)iface;
765     TRACE("(%p,%p)\n",iface,pCaps);
766     memcpy(pCaps, &(WOutDev[This->wDevID].ossdev->ds_caps), sizeof(DSDRIVERCAPS));
767     return DS_OK;
768 }
769
770 static HRESULT WINAPI DSD_CreatePrimaryBuffer(PIDSDRIVER iface,
771                                               LPWAVEFORMATEX pwfx,
772                                               DWORD dwFlags,
773                                               DWORD dwCardAddress,
774                                               LPDWORD pdwcbBufferSize,
775                                               LPBYTE *ppbBuffer,
776                                               LPVOID *ppvObj)
777 {
778     IDsDriverImpl *This = (IDsDriverImpl *)iface;
779     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
780     HRESULT err;
781     audio_buf_info info;
782     int enable = 0;
783     TRACE("(%p,%p,%x,%x,%p,%p,%p)\n",iface,pwfx,dwFlags,dwCardAddress,pdwcbBufferSize,ppbBuffer,ppvObj);
784
785     if (This->primary)
786         return DSERR_ALLOCATED;
787     if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
788         return DSERR_CONTROLUNAVAIL;
789
790     *ippdsdb = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDsDriverBufferImpl));
791     if (*ippdsdb == NULL)
792         return DSERR_OUTOFMEMORY;
793     (*ippdsdb)->lpVtbl  = &dsdbvt;
794     (*ippdsdb)->ref     = 1;
795     (*ippdsdb)->drv     = This;
796     copy_format(pwfx, &(*ippdsdb)->wfex);
797     (*ippdsdb)->fd      = WOutDev[This->wDevID].ossdev->fd;
798     (*ippdsdb)->dwFlags = dwFlags;
799
800     /* check how big the DMA buffer is now */
801     if (ioctl((*ippdsdb)->fd, SNDCTL_DSP_GETOSPACE, &info) < 0) {
802         ERR("ioctl(%s, SNDCTL_DSP_GETOSPACE) failed (%s)\n",
803             WOutDev[This->wDevID].ossdev->dev_name, strerror(errno));
804         HeapFree(GetProcessHeap(),0,*ippdsdb);
805         *ippdsdb = NULL;
806         return DSERR_GENERIC;
807     }
808     (*ippdsdb)->maplen = (*ippdsdb)->buflen = info.fragstotal * info.fragsize;
809
810     /* map the DMA buffer */
811     err = DSDB_MapBuffer(*ippdsdb);
812     if (err != DS_OK) {
813         HeapFree(GetProcessHeap(),0,*ippdsdb);
814         *ippdsdb = NULL;
815         return err;
816     }
817
818     /* primary buffer is ready to go */
819     *pdwcbBufferSize    = (*ippdsdb)->maplen;
820     *ppbBuffer          = (*ippdsdb)->mapping;
821
822     /* some drivers need some extra nudging after mapping */
823     WOutDev[This->wDevID].ossdev->bInputEnabled = FALSE;
824     WOutDev[This->wDevID].ossdev->bOutputEnabled = FALSE;
825     enable = getEnables(WOutDev[This->wDevID].ossdev);
826     if (ioctl((*ippdsdb)->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
827         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n",
828             WOutDev[This->wDevID].ossdev->dev_name, strerror(errno));
829         return DSERR_GENERIC;
830     }
831
832     This->primary = *ippdsdb;
833
834     return DS_OK;
835 }
836
837 static HRESULT WINAPI DSD_CreateSecondaryBuffer(PIDSDRIVER iface,
838                                                 LPWAVEFORMATEX pwfx,
839                                                 DWORD dwFlags,
840                                                 DWORD dwCardAddress,
841                                                 LPDWORD pdwcbBufferSize,
842                                                 LPBYTE *ppbBuffer,
843                                                 LPVOID *ppvObj)
844 {
845     IDsDriverImpl *This = (IDsDriverImpl *)iface;
846     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
847     FIXME("(%p,%p,%x,%x,%p,%p,%p): stub\n",This,pwfx,dwFlags,dwCardAddress,pdwcbBufferSize,ppbBuffer,ppvObj);
848
849     *ippdsdb = 0;
850     return DSERR_UNSUPPORTED;
851 }
852
853 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
854                                                       LPWAVEFORMATEX pwfx,
855                                                       DWORD dwFlags,
856                                                       DWORD dwCardAddress,
857                                                       LPDWORD pdwcbBufferSize,
858                                                       LPBYTE *ppbBuffer,
859                                                       LPVOID *ppvObj)
860 {
861     TRACE("(%p,%p,%x,%x,%p,%p,%p)\n",iface,pwfx,dwFlags,dwCardAddress,pdwcbBufferSize,ppbBuffer,ppvObj);
862
863     if (dwFlags & DSBCAPS_PRIMARYBUFFER)
864         return DSD_CreatePrimaryBuffer(iface,pwfx,dwFlags,dwCardAddress,pdwcbBufferSize,ppbBuffer,ppvObj);
865
866     return DSD_CreateSecondaryBuffer(iface,pwfx,dwFlags,dwCardAddress,pdwcbBufferSize,ppbBuffer,ppvObj);
867 }
868
869 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
870                                                          PIDSDRIVERBUFFER pBuffer,
871                                                          LPVOID *ppvObj)
872 {
873     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
874     TRACE("(%p,%p): stub\n",iface,pBuffer);
875     return DSERR_INVALIDCALL;
876 }
877
878 static const IDsDriverVtbl dsdvt =
879 {
880     IDsDriverImpl_QueryInterface,
881     IDsDriverImpl_AddRef,
882     IDsDriverImpl_Release,
883     IDsDriverImpl_GetDriverDesc,
884     IDsDriverImpl_Open,
885     IDsDriverImpl_Close,
886     IDsDriverImpl_GetCaps,
887     IDsDriverImpl_CreateSoundBuffer,
888     IDsDriverImpl_DuplicateSoundBuffer
889 };
890
891 static HRESULT WINAPI IDsDriverPropertySetImpl_Create(
892     IDsDriverBufferImpl * dsdb,
893     IDsDriverPropertySetImpl **pdsdps)
894 {
895     IDsDriverPropertySetImpl * dsdps;
896     TRACE("(%p,%p)\n",dsdb,pdsdps);
897
898     dsdps = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(dsdps));
899     if (dsdps == NULL) {
900         WARN("out of memory\n");
901         return DSERR_OUTOFMEMORY;
902     }
903
904     dsdps->ref = 0;
905     dsdps->lpVtbl = &dsdpsvt;
906     dsdps->buffer = dsdb;
907     dsdb->property_set = dsdps;
908     IDsDriverBuffer_AddRef((PIDSDRIVER)dsdb);
909
910     *pdsdps = dsdps;
911     return DS_OK;
912 }
913
914 static HRESULT WINAPI IDsDriverNotifyImpl_Create(
915     IDsDriverBufferImpl * dsdb,
916     IDsDriverNotifyImpl **pdsdn)
917 {
918     IDsDriverNotifyImpl * dsdn;
919     TRACE("(%p,%p)\n",dsdb,pdsdn);
920
921     dsdn = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(dsdn));
922
923     if (dsdn == NULL) {
924         WARN("out of memory\n");
925         return DSERR_OUTOFMEMORY;
926     }
927
928     dsdn->ref = 0;
929     dsdn->lpVtbl = &dsdnvt;
930     dsdn->buffer = dsdb;
931     dsdb->notify = dsdn;
932     IDsDriverBuffer_AddRef((PIDSDRIVER)dsdb);
933
934     *pdsdn = dsdn;
935     return DS_OK;
936 }
937
938 DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
939 {
940     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
941     TRACE("(%d,%p)\n",wDevID,drv);
942
943     /* the HAL isn't much better than the HEL if we can't do mmap() */
944     if (!(WOutDev[wDevID].ossdev->duplex_out_caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
945         ERR("DirectSound flag not set\n");
946         MESSAGE("This sound card's driver does not support direct access\n");
947         MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
948         return MMSYSERR_NOTSUPPORTED;
949     }
950
951     *idrv = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDsDriverImpl));
952     if (!*idrv)
953         return MMSYSERR_NOMEM;
954     (*idrv)->lpVtbl          = &dsdvt;
955     (*idrv)->ref             = 1;
956     (*idrv)->wDevID          = wDevID;
957     (*idrv)->primary         = NULL;
958     (*idrv)->nrofsecondaries = 0;
959     (*idrv)->secondaries     = NULL;
960
961     return MMSYSERR_NOERROR;
962 }
963
964 DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
965 {
966     TRACE("(%d,%p)\n",wDevID,desc);
967     memcpy(desc, &(WOutDev[wDevID].ossdev->ds_desc), sizeof(DSDRIVERDESC));
968     return MMSYSERR_NOERROR;
969 }
970
971 #endif /* HAVE_OSS */