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