Implement A->W call for GetNamedSecurityInfo.
[wine] / dlls / winmm / winealsa / audio_05.c
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
2 /*
3  * Sample Wine Driver for Advanced Linux Sound System (ALSA)
4  *      Based on version 0.5 of the ALSA API
5  *
6  * Copyright    2002 Eric Pouech
7  *              2002 David Hammerton
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
26 #include <stdlib.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <string.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include <errno.h>
34 #include <fcntl.h>
35 #ifdef HAVE_SYS_IOCTL_H
36 # include <sys/ioctl.h>
37 #endif
38 #ifdef HAVE_SYS_MMAN_H
39 # include <sys/mman.h>
40 #endif
41 #include "windef.h"
42 #include "winbase.h"
43 #include "wingdi.h"
44 #include "winerror.h"
45 #include "winuser.h"
46 #include "mmddk.h"
47 #include "dsound.h"
48 #include "dsdriver.h"
49 #include "alsa.h"
50 #include "wine/debug.h"
51
52 WINE_DEFAULT_DEBUG_CHANNEL(wave);
53
54
55 #if defined(HAVE_ALSA) && (SND_LIB_MAJOR == 0) && (SND_LIB_MINOR == 5)
56
57 #define MAX_WAVEOUTDRV  (1)
58 #define MAX_WAVEINDRV   (1)
59
60 /* state diagram for waveOut writing:
61  *
62  * +---------+-------------+---------------+---------------------------------+
63  * |  state  |  function   |     event     |            new state            |
64  * +---------+-------------+---------------+---------------------------------+
65  * |         | open()      |               | STOPPED                         |
66  * | PAUSED  | write()     |               | PAUSED                          |
67  * | STOPPED | write()     | <thrd create> | PLAYING                         |
68  * | PLAYING | write()     | HEADER        | PLAYING                         |
69  * | (other) | write()     | <error>       |                                 |
70  * | (any)   | pause()     | PAUSING       | PAUSED                          |
71  * | PAUSED  | restart()   | RESTARTING    | PLAYING (if no thrd => STOPPED) |
72  * | (any)   | reset()     | RESETTING     | STOPPED                         |
73  * | (any)   | close()     | CLOSING       | CLOSED                          |
74  * +---------+-------------+---------------+---------------------------------+
75  */
76
77 /* states of the playing device */
78 #define WINE_WS_PLAYING         0
79 #define WINE_WS_PAUSED          1
80 #define WINE_WS_STOPPED         2
81 #define WINE_WS_CLOSED          3
82
83 /* events to be send to device */
84 enum win_wm_message {
85     WINE_WM_PAUSING = WM_USER + 1, WINE_WM_RESTARTING, WINE_WM_RESETTING, WINE_WM_HEADER,
86     WINE_WM_UPDATE, WINE_WM_BREAKLOOP, WINE_WM_CLOSING
87 };
88
89 typedef struct {
90     enum win_wm_message         msg;    /* message identifier */
91     DWORD                       param;  /* parameter for this message */
92     HANDLE                      hEvent; /* if message is synchronous, handle of event for synchro */
93 } ALSA_MSG;
94
95 /* implement an in-process message ring for better performance
96  * (compared to passing thru the server)
97  * this ring will be used by the input (resp output) record (resp playback) routine
98  */
99 typedef struct {
100     /* FIXME: this could be made a dynamically growing array (if needed) */
101 #define ALSA_RING_BUFFER_SIZE   30
102     ALSA_MSG                    messages[ALSA_RING_BUFFER_SIZE];
103     int                         msg_tosave;
104     int                         msg_toget;
105     HANDLE                      msg_event;
106     CRITICAL_SECTION            msg_crst;
107 } ALSA_MSG_RING;
108
109 typedef struct {
110     /* Windows information */
111     volatile int                state;                  /* one of the WINE_WS_ manifest constants */
112     WAVEOPENDESC                waveDesc;
113     WORD                        wFlags;
114     PCMWAVEFORMAT               format;
115     WAVEOUTCAPSA                caps;
116
117     /* ALSA information */
118     snd_pcm_t*                  handle;                 /* handle to ALSA device */
119     DWORD                       dwFragmentSize;         /* size of ALSA buffer fragment */
120     DWORD                       dwBufferSize;           /* size of whole ALSA buffer in bytes */
121     LPWAVEHDR                   lpQueuePtr;             /* start of queued WAVEHDRs (waiting to be notified) */
122     LPWAVEHDR                   lpPlayPtr;              /* start of not yet fully played buffers */
123     DWORD                       dwPartialOffset;        /* Offset of not yet written bytes in lpPlayPtr */
124
125     LPWAVEHDR                   lpLoopPtr;              /* pointer of first buffer in loop, if any */
126     DWORD                       dwLoops;                /* private copy of loop counter */
127
128     DWORD                       dwPlayedTotal;          /* number of bytes actually played since opening */
129     DWORD                       dwWrittenTotal;         /* number of bytes written to ALSA buffer since opening */
130
131     /* synchronization stuff */
132     HANDLE                      hStartUpEvent;
133     HANDLE                      hThread;
134     DWORD                       dwThreadID;
135     ALSA_MSG_RING               msgRing;
136
137     /* DirectSound stuff */
138     void*                       mmap_buffer;
139     snd_pcm_mmap_control_t*     mmap_control;
140     unsigned                    mmap_block_size;
141     unsigned                    mmap_block_number;
142 } WINE_WAVEOUT;
143
144 static WINE_WAVEOUT     WOutDev   [MAX_WAVEOUTDRV];
145 static DWORD            ALSA_WodNumDevs;
146
147 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
148
149 /* These strings used only for tracing */
150 static const char *wodPlayerCmdString[] = {
151     "WINE_WM_PAUSING",
152     "WINE_WM_RESTARTING",
153     "WINE_WM_RESETTING",
154     "WINE_WM_HEADER",
155     "WINE_WM_UPDATE",
156     "WINE_WM_BREAKLOOP",
157     "WINE_WM_CLOSING",
158 };
159
160 /*======================================================================*
161  *                  Low level WAVE implementation                       *
162  *======================================================================*/
163
164 /******************************************************************
165  *              ALSA_WaveInit
166  *
167  * Initialize internal structures from ALSA information
168  */
169 LONG ALSA_WaveInit(void)
170 {
171     snd_pcm_t*                  h;
172     snd_pcm_info_t              info;
173     snd_pcm_channel_info_t      chn_info;
174
175     TRACE("There are %d cards\n", snd_cards());
176
177     ALSA_WodNumDevs = 0;
178     if (snd_pcm_open(&h, 0, 0, SND_PCM_OPEN_DUPLEX|SND_PCM_OPEN_NONBLOCK))
179     {
180         ERR("Error open: %s\n", snd_strerror(errno));
181         return -1;
182     }
183     if (snd_pcm_info(h, &info))
184     {
185         ERR("Error info: %s\n", snd_strerror(errno));
186         return -1;
187     }
188     ALSA_WodNumDevs++;
189     TRACE("type=%u, flags=%s%s%s name=%s #pb=%d cp=%d\n",
190           info.type, (info.flags & SND_PCM_INFO_PLAYBACK) ? "playback " : "",
191           (info.flags & SND_PCM_INFO_PLAYBACK) ? "capture " : "",
192           (info.flags & SND_PCM_INFO_DUPLEX) ? "duplex " : "",
193           info.name, info.playback, info.capture);
194     memset(&chn_info, 0, sizeof(chn_info));
195     if (snd_pcm_channel_info(h, &chn_info))
196     {
197         ERR("Error chn info: %s\n", snd_strerror(errno));
198         return -1;
199     }
200 #define X(f,s) ((chn_info.flags & (f)) ? #s " " : "")
201 #define Y(f,s) ((chn_info.rates & (f)) ? #s " " : "")
202     TRACE("subdevice=%d name=%s chn=%d mode=%d\n"
203           "\tflags=%s%s%s%s%s%s%s%s%s%s%s\n"
204           "\tfmts=%u rates=%s%s%s%s%s%s%s%s%s%s%s%s%s\n"
205           "\trates=[%d,%d] voices=[%d,%d] buf_size=%d fg_size=[%d,%d] fg_align=%u\n",
206           chn_info.subdevice, chn_info.subname, chn_info.channel,
207           chn_info.mode,
208           X(SND_PCM_CHNINFO_MMAP,MMAP),
209           X(SND_PCM_CHNINFO_STREAM,STREAM),
210           X(SND_PCM_CHNINFO_BLOCK,BLOCK),
211           X(SND_PCM_CHNINFO_BATCH,BATCH),
212           X(SND_PCM_CHNINFO_INTERLEAVE,INTERLEAVE),
213           X(SND_PCM_CHNINFO_NONINTERLEAVE,NONINTERLEAVE),
214           X(SND_PCM_CHNINFO_BLOCK_TRANSFER,BLOCK_TRANSFER),
215           X(SND_PCM_CHNINFO_OVERRANGE,OVERRANGE),
216           X(SND_PCM_CHNINFO_MMAP_VALID,MMAP_VALID),
217           X(SND_PCM_CHNINFO_PAUSE,PAUSE),
218           X(SND_PCM_CHNINFO_GLOBAL_PARAMS,GLOBAL_PARAMS),
219           chn_info.formats,
220           Y(SND_PCM_RATE_CONTINUOUS,CONTINUOUS),
221           Y(SND_PCM_RATE_KNOT,KNOT),
222           Y(SND_PCM_RATE_8000,8000),
223           Y(SND_PCM_RATE_11025,11025),
224           Y(SND_PCM_RATE_16000,16000),
225           Y(SND_PCM_RATE_22050,22050),
226           Y(SND_PCM_RATE_32000,32000),
227           Y(SND_PCM_RATE_44100,44100),
228           Y(SND_PCM_RATE_48000,48000),
229           Y(SND_PCM_RATE_88200,88200),
230           Y(SND_PCM_RATE_96000,96000),
231           Y(SND_PCM_RATE_176400,176400),
232           Y(SND_PCM_RATE_192000,192000),
233           chn_info.min_rate, chn_info.max_rate,
234           chn_info.min_voices, chn_info.max_voices,
235           chn_info.buffer_size,
236           chn_info.min_fragment_size, chn_info.max_fragment_size,
237           chn_info.fragment_align);
238 #undef X
239 #undef Y
240
241     /* FIXME: use better values */
242     WOutDev[0].caps.wMid = 0x0002;
243     WOutDev[0].caps.wPid = 0x0104;
244     strcpy(WOutDev[0].caps.szPname, "SB16 Wave Out");
245     WOutDev[0].caps.vDriverVersion = 0x0100;
246     WOutDev[0].caps.dwFormats = 0x00000000;
247     WOutDev[0].caps.dwSupport = WAVECAPS_VOLUME;
248 #define X(r,v) \
249     if (chn_info.rates & SND_PCM_RATE_##r) \
250     { \
251         if (chn_info.formats & SND_PCM_FMT_U8) \
252         { \
253             if (chn_info.min_voices <= 1 && 1 <= chn_info.max_voices) \
254                 WOutDev[0].caps.dwFormats |= WAVE_FORMAT_##v##S08; \
255             if (chn_info.min_voices <= 2 && 2 <= chn_info.max_voices) \
256                 WOutDev[0].caps.dwFormats |= WAVE_FORMAT_##v##S08; \
257         } \
258         if (chn_info.formats & SND_PCM_FMT_S16_LE) \
259         { \
260             if (chn_info.min_voices <= 1 && 1 <= chn_info.max_voices) \
261                 WOutDev[0].caps.dwFormats |= WAVE_FORMAT_##v##S16; \
262             if (chn_info.min_voices <= 2 && 2 <= chn_info.max_voices) \
263                 WOutDev[0].caps.dwFormats |= WAVE_FORMAT_##v##S16; \
264         } \
265     }
266     X(11025,1);
267     X(22050,2);
268     X(44100,4);
269 #undef X
270     if (chn_info.min_voices > 1) FIXME("-\n");
271     WOutDev[0].caps.wChannels = (chn_info.max_voices >= 2) ? 2 : 1;
272     if (chn_info.min_voices <= 2 && 2 <= chn_info.max_voices)
273         WOutDev[0].caps.dwSupport |= WAVECAPS_LRVOLUME;
274
275     /* FIXME: always true ? */
276     WOutDev[0].caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
277
278     /* FIXME: is test sufficient ? */
279     if (chn_info.flags & SND_PCM_CHNINFO_MMAP)
280         WOutDev[0].caps.dwSupport |= WAVECAPS_DIRECTSOUND;
281
282     TRACE("Configured with dwFmts=%08lx dwSupport=%08lx\n",
283           WOutDev[0].caps.dwFormats, WOutDev[0].caps.dwSupport);
284
285     snd_pcm_close(h);
286
287     return 0;
288 }
289
290 /******************************************************************
291  *              ALSA_InitRingMessage
292  *
293  * Initialize the ring of messages for passing between driver's caller and playback/record
294  * thread
295  */
296 static int ALSA_InitRingMessage(ALSA_MSG_RING* omr)
297 {
298     omr->msg_toget = 0;
299     omr->msg_tosave = 0;
300     omr->msg_event = CreateEventA(NULL, FALSE, FALSE, NULL);
301     memset(omr->messages, 0, sizeof(ALSA_MSG) * ALSA_RING_BUFFER_SIZE);
302     InitializeCriticalSection(&omr->msg_crst);
303     return 0;
304 }
305
306 /******************************************************************
307  *              ALSA_DestroyRingMessage
308  *
309  */
310 static int ALSA_DestroyRingMessage(ALSA_MSG_RING* omr)
311 {
312     CloseHandle(omr->msg_event);
313     DeleteCriticalSection(&omr->msg_crst);
314     return 0;
315 }
316
317 /******************************************************************
318  *              ALSA_AddRingMessage
319  *
320  * Inserts a new message into the ring (should be called from DriverProc derivated routines)
321  */
322 static int ALSA_AddRingMessage(ALSA_MSG_RING* omr, enum win_wm_message msg, DWORD param, BOOL wait)
323 {
324     HANDLE      hEvent = INVALID_HANDLE_VALUE;
325
326     EnterCriticalSection(&omr->msg_crst);
327     if ((omr->msg_toget == ((omr->msg_tosave + 1) % ALSA_RING_BUFFER_SIZE))) /* buffer overflow ? */
328     {
329         ERR("buffer overflow !?\n");
330         LeaveCriticalSection(&omr->msg_crst);
331         return 0;
332     }
333     if (wait)
334     {
335         hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
336         if (hEvent == INVALID_HANDLE_VALUE)
337         {
338             ERR("can't create event !?\n");
339             LeaveCriticalSection(&omr->msg_crst);
340             return 0;
341         }
342         if (omr->msg_toget != omr->msg_tosave && omr->messages[omr->msg_toget].msg != WINE_WM_HEADER)
343             FIXME("two fast messages in the queue!!!!\n");
344
345         /* fast messages have to be added at the start of the queue */
346         omr->msg_toget = (omr->msg_toget + ALSA_RING_BUFFER_SIZE - 1) % ALSA_RING_BUFFER_SIZE;
347
348         omr->messages[omr->msg_toget].msg = msg;
349         omr->messages[omr->msg_toget].param = param;
350         omr->messages[omr->msg_toget].hEvent = hEvent;
351     }
352     else
353     {
354         omr->messages[omr->msg_tosave].msg = msg;
355         omr->messages[omr->msg_tosave].param = param;
356         omr->messages[omr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
357         omr->msg_tosave = (omr->msg_tosave + 1) % ALSA_RING_BUFFER_SIZE;
358     }
359     LeaveCriticalSection(&omr->msg_crst);
360     /* signal a new message */
361     SetEvent(omr->msg_event);
362     if (wait)
363     {
364         /* wait for playback/record thread to have processed the message */
365         WaitForSingleObject(hEvent, INFINITE);
366         CloseHandle(hEvent);
367     }
368     return 1;
369 }
370
371 /******************************************************************
372  *              ALSA_RetrieveRingMessage
373  *
374  * Get a message from the ring. Should be called by the playback/record thread.
375  */
376 static int ALSA_RetrieveRingMessage(ALSA_MSG_RING* omr,
377                                    enum win_wm_message *msg, DWORD *param, HANDLE *hEvent)
378 {
379     EnterCriticalSection(&omr->msg_crst);
380
381     if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
382     {
383         LeaveCriticalSection(&omr->msg_crst);
384         return 0;
385     }
386
387     *msg = omr->messages[omr->msg_toget].msg;
388     omr->messages[omr->msg_toget].msg = 0;
389     *param = omr->messages[omr->msg_toget].param;
390     *hEvent = omr->messages[omr->msg_toget].hEvent;
391     omr->msg_toget = (omr->msg_toget + 1) % ALSA_RING_BUFFER_SIZE;
392     LeaveCriticalSection(&omr->msg_crst);
393     return 1;
394 }
395
396 /*======================================================================*
397  *                  Low level WAVE OUT implementation                   *
398  *======================================================================*/
399
400 /**************************************************************************
401  *                      wodNotifyClient                 [internal]
402  */
403 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
404 {
405     TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
406
407     switch (wMsg) {
408     case WOM_OPEN:
409     case WOM_CLOSE:
410     case WOM_DONE:
411         if (wwo->wFlags != DCB_NULL &&
412             !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags, wwo->waveDesc.hWave,
413                             wMsg, wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
414             WARN("can't notify client !\n");
415             return MMSYSERR_ERROR;
416         }
417         break;
418     default:
419         FIXME("Unknown callback message %u\n", wMsg);
420         return MMSYSERR_INVALPARAM;
421     }
422     return MMSYSERR_NOERROR;
423 }
424
425 /**************************************************************************
426  *                              wodUpdatePlayedTotal    [internal]
427  *
428  */
429 static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo, snd_pcm_channel_status_t* ps)
430 {
431     snd_pcm_channel_status_t    s;
432     snd_pcm_channel_status_t*   status = (ps) ? ps : &s;
433
434     if (snd_pcm_channel_status(wwo->handle, status))
435     {
436         ERR("Can't get channel status: %s\n", snd_strerror(errno));
437         return FALSE;
438     }
439     wwo->dwPlayedTotal = wwo->dwWrittenTotal - (wwo->dwBufferSize - status->count);
440     if (wwo->dwPlayedTotal != status->scount)
441     {
442         FIXME("Ooch: %u played by ALSA, %lu counted by driver\n",
443               status->scount, wwo->dwPlayedTotal);
444         if (wwo->dwPlayedTotal & 0x8000000) wwo->dwPlayedTotal = 0;
445     }
446     return TRUE;
447 }
448
449 /**************************************************************************
450  *                              wodPlayer_BeginWaveHdr          [internal]
451  *
452  * Makes the specified lpWaveHdr the currently playing wave header.
453  * If the specified wave header is a begin loop and we're not already in
454  * a loop, setup the loop.
455  */
456 static void wodPlayer_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
457 {
458     wwo->lpPlayPtr = lpWaveHdr;
459
460     if (!lpWaveHdr) return;
461
462     if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
463         if (wwo->lpLoopPtr) {
464             WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
465         } else {
466             TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
467             wwo->lpLoopPtr = lpWaveHdr;
468             /* Windows does not touch WAVEHDR.dwLoops,
469              * so we need to make an internal copy */
470             wwo->dwLoops = lpWaveHdr->dwLoops;
471         }
472     }
473     wwo->dwPartialOffset = 0;
474 }
475
476 /**************************************************************************
477  *                              wodPlayer_PlayPtrNext           [internal]
478  *
479  * Advance the play pointer to the next waveheader, looping if required.
480  */
481 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEOUT* wwo)
482 {
483     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
484
485     wwo->dwPartialOffset = 0;
486     if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
487         /* We're at the end of a loop, loop if required */
488         if (--wwo->dwLoops > 0) {
489             wwo->lpPlayPtr = wwo->lpLoopPtr;
490         } else {
491             /* Handle overlapping loops correctly */
492             if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
493                 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
494                 /* shall we consider the END flag for the closing loop or for
495                  * the opening one or for both ???
496                  * code assumes for closing loop only
497                  */
498             } else {
499                 lpWaveHdr = lpWaveHdr->lpNext;
500             }
501             wwo->lpLoopPtr = NULL;
502             wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
503         }
504     } else {
505         /* We're not in a loop.  Advance to the next wave header */
506         wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
507     }
508
509     return lpWaveHdr;
510 }
511
512 /**************************************************************************
513  *                           wodPlayer_DSPWait                  [internal]
514  * Returns the number of milliseconds to wait for the DSP buffer to write
515  * one fragment.
516  */
517 static DWORD wodPlayer_DSPWait(const WINE_WAVEOUT *wwo)
518 {
519     /* time for one fragment to be played */
520     return wwo->dwFragmentSize * 1000 / wwo->format.wf.nAvgBytesPerSec;
521 }
522
523 /**************************************************************************
524  *                           wodPlayer_NotifyWait               [internal]
525  * Returns the number of milliseconds to wait before attempting to notify
526  * completion of the specified wavehdr.
527  * This is based on the number of bytes remaining to be written in the
528  * wave.
529  */
530 static DWORD wodPlayer_NotifyWait(const WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
531 {
532     DWORD dwMillis;
533
534     if (lpWaveHdr->reserved < wwo->dwPlayedTotal) {
535         dwMillis = 1;
536     } else {
537         dwMillis = (lpWaveHdr->reserved - wwo->dwPlayedTotal) * 1000 / wwo->format.wf.nAvgBytesPerSec;
538         if (!dwMillis) dwMillis = 1;
539     }
540
541     return dwMillis;
542 }
543
544
545 /**************************************************************************
546  *                           wodPlayer_WriteMaxFrags            [internal]
547  * Writes the maximum number of bytes palsaible to the DSP and returns
548  * the number of bytes written.
549  */
550 static int wodPlayer_WriteMaxFrags(WINE_WAVEOUT* wwo, DWORD* bytes)
551 {
552     /* Only attempt to write to free bytes */
553     DWORD dwLength = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
554     int toWrite = min(dwLength, *bytes);
555     int written;
556
557     TRACE("Writing wavehdr %p.%lu[%lu]\n",
558           wwo->lpPlayPtr, wwo->dwPartialOffset, wwo->lpPlayPtr->dwBufferLength);
559     written = snd_pcm_write(wwo->handle, wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toWrite);
560     if (written <= 0)
561     {
562         ERR("Wrote: %d bytes (%s)\n", written, snd_strerror(errno));
563         return written;
564     }
565
566     if (written >= dwLength) {
567         /* If we wrote all current wavehdr, skip to the next one */
568         wodPlayer_PlayPtrNext(wwo);
569     } else {
570         /* Remove the amount written */
571         wwo->dwPartialOffset += written;
572     }
573     *bytes -= written;
574     wwo->dwWrittenTotal += written;
575
576     return written;
577 }
578
579
580 /**************************************************************************
581  *                              wodPlayer_NotifyCompletions     [internal]
582  *
583  * Notifies and remove from queue all wavehdrs which have been played to
584  * the speaker (ie. they have cleared the ALSA buffer).  If force is true,
585  * we notify all wavehdrs and remove them all from the queue even if they
586  * are unplayed or part of a loop.
587  */
588 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
589 {
590     LPWAVEHDR           lpWaveHdr;
591
592     /* Start from lpQueuePtr and keep notifying until:
593      * - we hit an unwritten wavehdr
594      * - we hit the beginning of a running loop
595      * - we hit a wavehdr which hasn't finished playing
596      */
597     while ((lpWaveHdr = wwo->lpQueuePtr) &&
598            (force ||
599             (lpWaveHdr != wwo->lpPlayPtr &&
600              lpWaveHdr != wwo->lpLoopPtr &&
601              lpWaveHdr->reserved <= wwo->dwPlayedTotal))) {
602
603         wwo->lpQueuePtr = lpWaveHdr->lpNext;
604
605         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
606         lpWaveHdr->dwFlags |= WHDR_DONE;
607
608         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
609     }
610     return  (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
611         wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
612 }
613
614 /**************************************************************************
615  *                              wodPlayer_Reset                 [internal]
616  *
617  * wodPlayer helper. Resets current output stream.
618  */
619 static  void    wodPlayer_Reset(WINE_WAVEOUT* wwo, BOOL reset)
620 {
621     wodUpdatePlayedTotal(wwo, NULL);
622     /* updates current notify list */
623     wodPlayer_NotifyCompletions(wwo, FALSE);
624
625     if (snd_pcm_playback_flush(wwo->handle) != 0) {
626         FIXME("flush: %s\n", snd_strerror(errno));
627         wwo->hThread = 0;
628         wwo->state = WINE_WS_STOPPED;
629         ExitThread(-1);
630     }
631
632     if (reset) {
633         enum win_wm_message     msg;
634         DWORD                   param;
635         HANDLE                  ev;
636
637         /* remove any buffer */
638         wodPlayer_NotifyCompletions(wwo, TRUE);
639
640         wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
641         wwo->state = WINE_WS_STOPPED;
642         wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
643         /* Clear partial wavehdr */
644         wwo->dwPartialOffset = 0;
645
646         /* remove any existing message in the ring */
647         EnterCriticalSection(&wwo->msgRing.msg_crst);
648         /* return all pending headers in queue */
649         while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
650         {
651             if (msg != WINE_WM_HEADER)
652             {
653                 FIXME("shouldn't have headers left\n");
654                 SetEvent(ev);
655                 continue;
656             }
657             ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
658             ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
659
660             wodNotifyClient(wwo, WOM_DONE, param, 0);
661         }
662         ResetEvent(wwo->msgRing.msg_event);
663         LeaveCriticalSection(&wwo->msgRing.msg_crst);
664     } else {
665         if (wwo->lpLoopPtr) {
666             /* complicated case, not handled yet (could imply modifying the loop counter */
667             FIXME("Pausing while in loop isn't correctly handled yet, except strange results\n");
668             wwo->lpPlayPtr = wwo->lpLoopPtr;
669             wwo->dwPartialOffset = 0;
670             wwo->dwWrittenTotal = wwo->dwPlayedTotal; /* this is wrong !!! */
671         } else {
672             LPWAVEHDR   ptr;
673             DWORD       sz = wwo->dwPartialOffset;
674
675             /* reset all the data as if we had written only up to lpPlayedTotal bytes */
676             /* compute the max size playable from lpQueuePtr */
677             for (ptr = wwo->lpQueuePtr; ptr != wwo->lpPlayPtr; ptr = ptr->lpNext) {
678                 sz += ptr->dwBufferLength;
679             }
680             /* because the reset lpPlayPtr will be lpQueuePtr */
681             if (wwo->dwWrittenTotal > wwo->dwPlayedTotal + sz) ERR("grin\n");
682             wwo->dwPartialOffset = sz - (wwo->dwWrittenTotal - wwo->dwPlayedTotal);
683             wwo->dwWrittenTotal = wwo->dwPlayedTotal;
684             wwo->lpPlayPtr = wwo->lpQueuePtr;
685         }
686         wwo->state = WINE_WS_PAUSED;
687     }
688 }
689
690 /**************************************************************************
691  *                    wodPlayer_ProcessMessages                 [internal]
692  */
693 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
694 {
695     LPWAVEHDR           lpWaveHdr;
696     enum win_wm_message msg;
697     DWORD               param;
698     HANDLE              ev;
699
700     while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
701         TRACE("Received %s %lx\n", wodPlayerCmdString[msg - WM_USER - 1], param);
702
703         switch (msg) {
704         case WINE_WM_PAUSING:
705             wodPlayer_Reset(wwo, FALSE);
706             SetEvent(ev);
707             break;
708         case WINE_WM_RESTARTING:
709             if (wwo->state == WINE_WS_PAUSED)
710             {
711                 snd_pcm_playback_prepare(wwo->handle);
712                 wwo->state = WINE_WS_PLAYING;
713             }
714             SetEvent(ev);
715             break;
716         case WINE_WM_HEADER:
717             lpWaveHdr = (LPWAVEHDR)param;
718
719             /* insert buffer at the end of queue */
720             {
721                 LPWAVEHDR*      wh;
722                 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
723                 *wh = lpWaveHdr;
724             }
725             if (!wwo->lpPlayPtr)
726                 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
727             if (wwo->state == WINE_WS_STOPPED)
728                 wwo->state = WINE_WS_PLAYING;
729             break;
730         case WINE_WM_RESETTING:
731             wodPlayer_Reset(wwo, TRUE);
732             SetEvent(ev);
733             break;
734         case WINE_WM_UPDATE:
735             wodUpdatePlayedTotal(wwo, NULL);
736             SetEvent(ev);
737             break;
738         case WINE_WM_BREAKLOOP:
739             if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
740                 /* ensure exit at end of current loop */
741                 wwo->dwLoops = 1;
742             }
743             SetEvent(ev);
744             break;
745         case WINE_WM_CLOSING:
746             /* sanity check: this should not happen since the device must have been reset before */
747             if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
748             wwo->hThread = 0;
749             wwo->state = WINE_WS_CLOSED;
750             SetEvent(ev);
751             ExitThread(0);
752             /* shouldn't go here */
753         default:
754             FIXME("unknown message %d\n", msg);
755             break;
756         }
757     }
758 }
759
760 /**************************************************************************
761  *                           wodPlayer_FeedDSP                  [internal]
762  * Feed as much sound data as we can into the DSP and return the number of
763  * milliseconds before it will be necessary to feed the DSP again.
764  */
765 static DWORD wodPlayer_FeedDSP(WINE_WAVEOUT* wwo)
766 {
767     snd_pcm_channel_status_t    status;
768     DWORD                       availInQ;
769
770     wodUpdatePlayedTotal(wwo, &status);
771     availInQ = status.free;
772
773 #if 0
774     TODO;
775     TRACE("fragments=%d/%d, fragsize=%d, bytes=%d\n",
776           dspspace.fragments, dspspace.fragstotal, dspspace.fragsize, dspspace.bytes);
777 #endif
778
779     /* input queue empty and output buffer with less than one fragment to play */
780     /* FIXME: we should be able to catch OVERRUN errors */
781     if (!wwo->lpPlayPtr && wwo->dwBufferSize < availInQ + 2 * wwo->dwFragmentSize) {
782         TRACE("Run out of wavehdr:s... flushing\n");
783         snd_pcm_playback_drain(wwo->handle);
784         wwo->dwPlayedTotal = wwo->dwWrittenTotal;
785         return INFINITE;
786     }
787
788     /* no more room... no need to try to feed */
789     if (status.free > 0) {
790         /* Feed from partial wavehdr */
791         if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0) {
792             wodPlayer_WriteMaxFrags(wwo, &availInQ);
793         }
794
795         /* Feed wavehdrs until we run out of wavehdrs or DSP space */
796         if (wwo->dwPartialOffset == 0) {
797             while (wwo->lpPlayPtr && availInQ > 0) {
798                 /* note the value that dwPlayedTotal will return when this wave finishes playing */
799                 wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
800                 wodPlayer_WriteMaxFrags(wwo, &availInQ);
801             }
802         }
803     }
804     return wodPlayer_DSPWait(wwo);
805 }
806
807
808 /**************************************************************************
809  *                              wodPlayer                       [internal]
810  */
811 static  DWORD   CALLBACK        wodPlayer(LPVOID pmt)
812 {
813     WORD          uDevID = (DWORD)pmt;
814     WINE_WAVEOUT* wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
815     DWORD         dwNextFeedTime = INFINITE;   /* Time before DSP needs feeding */
816     DWORD         dwNextNotifyTime = INFINITE; /* Time before next wave completion */
817     DWORD         dwSleepTime;
818
819     wwo->state = WINE_WS_STOPPED;
820     SetEvent(wwo->hStartUpEvent);
821
822     for (;;) {
823         /** Wait for the shortest time before an action is required.  If there
824          *  are no pending actions, wait forever for a command.
825          */
826         dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
827         TRACE("waiting %lums (%lu,%lu)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
828         WaitForSingleObject(wwo->msgRing.msg_event, dwSleepTime);
829         wodPlayer_ProcessMessages(wwo);
830         if (wwo->state == WINE_WS_PLAYING) {
831             dwNextFeedTime = wodPlayer_FeedDSP(wwo);
832             dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
833         } else {
834             dwNextFeedTime = dwNextNotifyTime = INFINITE;
835         }
836     }
837 }
838
839 /**************************************************************************
840  *                      wodGetDevCaps                           [internal]
841  */
842 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSA lpCaps, DWORD dwSize)
843 {
844     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
845
846     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
847
848     if (wDevID >= MAX_WAVEOUTDRV) {
849         TRACE("MAX_WAVOUTDRV reached !\n");
850         return MMSYSERR_BADDEVICEID;
851     }
852
853     memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
854     return MMSYSERR_NOERROR;
855 }
856
857 /**************************************************************************
858  *                              wodOpen                         [internal]
859  */
860 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
861 {
862     WINE_WAVEOUT*               wwo;
863     snd_pcm_channel_params_t    params;
864
865     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
866     if (lpDesc == NULL) {
867         WARN("Invalid Parameter !\n");
868         return MMSYSERR_INVALPARAM;
869     }
870     if (wDevID >= MAX_WAVEOUTDRV) {
871         TRACE("MAX_WAVOUTDRV reached !\n");
872         return MMSYSERR_BADDEVICEID;
873     }
874
875     /* only PCM format is supported so far... */
876     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
877         lpDesc->lpFormat->nChannels == 0 ||
878         lpDesc->lpFormat->nSamplesPerSec == 0) {
879         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
880              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
881              lpDesc->lpFormat->nSamplesPerSec);
882         return WAVERR_BADFORMAT;
883     }
884
885     if (dwFlags & WAVE_FORMAT_QUERY) {
886         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
887              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
888              lpDesc->lpFormat->nSamplesPerSec);
889         return MMSYSERR_NOERROR;
890     }
891
892     wwo = &WOutDev[wDevID];
893
894     if ((dwFlags & WAVE_DIRECTSOUND) && !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
895         /* not supported, ignore it */
896         dwFlags &= ~WAVE_DIRECTSOUND;
897
898     wwo->handle = 0;
899     if (snd_pcm_open(&wwo->handle, wDevID, 0, SND_PCM_OPEN_DUPLEX|SND_PCM_OPEN_NONBLOCK))
900     {
901         ERR("Error open: %s\n", snd_strerror(errno));
902         return MMSYSERR_NOTENABLED;
903     }
904
905     memset(&params, 0, sizeof(params));
906     params.channel = SND_PCM_CHANNEL_PLAYBACK;
907     params.start_mode = SND_PCM_START_DATA;
908     params.stop_mode = SND_PCM_STOP_STOP;
909     params.mode = SND_PCM_MODE_STREAM;
910     params.buf.stream.queue_size = 0x1000;
911     params.buf.stream.fill = SND_PCM_FILL_SILENCE;
912     params.buf.stream.max_fill = 0x800;
913
914     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
915
916     memcpy(&wwo->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
917     memcpy(&wwo->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
918
919     if (wwo->format.wBitsPerSample == 0) {
920         WARN("Resetting zeroed wBitsPerSample\n");
921         wwo->format.wBitsPerSample = 8 *
922             (wwo->format.wf.nAvgBytesPerSec /
923              wwo->format.wf.nSamplesPerSec) /
924             wwo->format.wf.nChannels;
925     }
926     params.format.interleave = 1;
927     params.format.format = (wwo->format.wBitsPerSample == 16) ?
928         SND_PCM_SFMT_S16_LE : SND_PCM_SFMT_U8;
929     params.format.rate = wwo->format.wf.nSamplesPerSec;
930     params.format.voices = (wwo->format.wf.nChannels > 1) ? 2 : 1;
931     params.format.special = 0;
932
933     if (snd_pcm_channel_params(wwo->handle, &params))
934     {
935         ERR("Can't set params: %s\n", snd_strerror(errno));
936         snd_pcm_close(wwo->handle);
937         wwo->handle = NULL;
938         return MMSYSERR_INVALPARAM;
939     }
940 #if 0
941     TODO;
942     if (params.format.rate != format != ((wwo->format.wBitsPerSample == 16) ? AFMT_S16_LE : AFMT_U8))
943         ERR("Can't set format to %d (%d)\n",
944             (wwo->format.wBitsPerSample == 16) ? AFMT_S16_LE : AFMT_U8, format);
945     if (dsp_stereo != (wwo->format.wf.nChannels > 1) ? 1 : 0)
946         ERR("Can't set stereo to %u (%d)\n",
947             (wwo->format.wf.nChannels > 1) ? 1 : 0, dsp_stereo);
948     if (!NEAR_MATCH(sample_rate, wwo->format.wf.nSamplesPerSec))
949         ERR("Can't set sample_rate to %lu (%d)\n",
950             wwo->format.wf.nSamplesPerSec, sample_rate);
951 #endif
952
953     snd_pcm_playback_prepare(wwo->handle);
954
955     /* Remember fragsize and total buffer size for future use */
956     wwo->dwBufferSize = params.buf.stream.queue_size;
957     /* FIXME: should get rid off fragment size */
958     wwo->dwFragmentSize = wwo->dwBufferSize >> 4; /* why not */
959     wwo->dwPlayedTotal = 0;
960     wwo->dwWrittenTotal = 0;
961     wwo->lpQueuePtr = wwo->lpPlayPtr = wwo->lpLoopPtr = NULL;
962
963     ALSA_InitRingMessage(&wwo->msgRing);
964
965     if (!(dwFlags & WAVE_DIRECTSOUND)) {
966         wwo->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
967         wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
968         WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
969         CloseHandle(wwo->hStartUpEvent);
970     } else {
971         wwo->hThread = INVALID_HANDLE_VALUE;
972         wwo->dwThreadID = 0;
973     }
974     wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
975
976     TRACE("handle=%08lx fragmentSize=%ld\n",
977           (DWORD)wwo->handle, wwo->dwFragmentSize);
978     if (wwo->dwFragmentSize % wwo->format.wf.nBlockAlign)
979         ERR("Fragment doesn't contain an integral number of data blocks\n");
980
981     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
982           wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec,
983           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
984           wwo->format.wf.nBlockAlign);
985
986     return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
987 }
988
989 /**************************************************************************
990  *                              wodClose                        [internal]
991  */
992 static DWORD wodClose(WORD wDevID)
993 {
994     DWORD               ret = MMSYSERR_NOERROR;
995     WINE_WAVEOUT*       wwo;
996
997     TRACE("(%u);\n", wDevID);
998
999     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].handle == NULL) {
1000         WARN("bad device ID !\n");
1001         return MMSYSERR_BADDEVICEID;
1002     }
1003
1004     wwo = &WOutDev[wDevID];
1005     if (wwo->lpQueuePtr) {
1006         WARN("buffers still playing !\n");
1007         ret = WAVERR_STILLPLAYING;
1008     } else {
1009         if (wwo->hThread != INVALID_HANDLE_VALUE) {
1010             ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1011         }
1012         if (wwo->mmap_buffer) {
1013             snd_pcm_munmap(wwo->handle, SND_PCM_CHANNEL_PLAYBACK);
1014             wwo->mmap_buffer = wwo->mmap_control = NULL;
1015         }
1016
1017         ALSA_DestroyRingMessage(&wwo->msgRing);
1018
1019         snd_pcm_close(wwo->handle);
1020         wwo->handle = NULL;
1021         wwo->dwFragmentSize = 0;
1022         ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1023     }
1024     return ret;
1025 }
1026
1027 /**************************************************************************
1028  *                              wodWrite                        [internal]
1029  *
1030  */
1031 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1032 {
1033     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1034
1035     /* first, do the sanity checks... */
1036     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].handle == NULL) {
1037         WARN("bad dev ID !\n");
1038         return MMSYSERR_BADDEVICEID;
1039     }
1040
1041     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1042         return WAVERR_UNPREPARED;
1043
1044     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1045         return WAVERR_STILLPLAYING;
1046
1047     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1048     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1049     lpWaveHdr->lpNext = 0;
1050
1051     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1052
1053     return MMSYSERR_NOERROR;
1054 }
1055
1056 /**************************************************************************
1057  *                              wodPrepare                      [internal]
1058  */
1059 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1060 {
1061     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1062
1063     if (wDevID >= MAX_WAVEOUTDRV) {
1064         WARN("bad device ID !\n");
1065         return MMSYSERR_BADDEVICEID;
1066     }
1067
1068     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1069         return WAVERR_STILLPLAYING;
1070
1071     lpWaveHdr->dwFlags |= WHDR_PREPARED;
1072     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1073     return MMSYSERR_NOERROR;
1074 }
1075
1076 /**************************************************************************
1077  *                              wodUnprepare                    [internal]
1078  */
1079 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1080 {
1081     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1082
1083     if (wDevID >= MAX_WAVEOUTDRV) {
1084         WARN("bad device ID !\n");
1085         return MMSYSERR_BADDEVICEID;
1086     }
1087
1088     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1089         return WAVERR_STILLPLAYING;
1090
1091     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1092     lpWaveHdr->dwFlags |= WHDR_DONE;
1093
1094     return MMSYSERR_NOERROR;
1095 }
1096
1097 /**************************************************************************
1098  *                      wodPause                                [internal]
1099  */
1100 static DWORD wodPause(WORD wDevID)
1101 {
1102     TRACE("(%u);!\n", wDevID);
1103
1104     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].handle == NULL) {
1105         WARN("bad device ID !\n");
1106         return MMSYSERR_BADDEVICEID;
1107     }
1108
1109     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1110
1111     return MMSYSERR_NOERROR;
1112 }
1113
1114 /**************************************************************************
1115  *                      wodRestart                              [internal]
1116  */
1117 static DWORD wodRestart(WORD wDevID)
1118 {
1119     TRACE("(%u);\n", wDevID);
1120
1121     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].handle == NULL) {
1122         WARN("bad device ID !\n");
1123         return MMSYSERR_BADDEVICEID;
1124     }
1125
1126     if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1127         ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1128     }
1129
1130     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1131     /* FIXME: Myst crashes with this ... hmm -MM
1132        return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1133     */
1134
1135     return MMSYSERR_NOERROR;
1136 }
1137
1138 /**************************************************************************
1139  *                      wodReset                                [internal]
1140  */
1141 static DWORD wodReset(WORD wDevID)
1142 {
1143     TRACE("(%u);\n", wDevID);
1144
1145     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].handle == NULL) {
1146         WARN("bad device ID !\n");
1147         return MMSYSERR_BADDEVICEID;
1148     }
1149
1150     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1151
1152     return MMSYSERR_NOERROR;
1153 }
1154
1155 /**************************************************************************
1156  *                              wodGetPosition                  [internal]
1157  */
1158 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1159 {
1160     int                 time;
1161     DWORD               val;
1162     WINE_WAVEOUT*       wwo;
1163
1164     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1165
1166     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].handle == NULL) {
1167         WARN("bad device ID !\n");
1168         return MMSYSERR_BADDEVICEID;
1169     }
1170
1171     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1172
1173     wwo = &WOutDev[wDevID];
1174     ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1175     val = wwo->dwPlayedTotal;
1176
1177     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
1178           lpTime->wType, wwo->format.wBitsPerSample,
1179           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
1180           wwo->format.wf.nAvgBytesPerSec);
1181     TRACE("dwPlayedTotal=%lu\n", val);
1182
1183     switch (lpTime->wType) {
1184     case TIME_BYTES:
1185         lpTime->u.cb = val;
1186         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
1187         break;
1188     case TIME_SAMPLES:
1189         lpTime->u.sample = val * 8 / wwo->format.wBitsPerSample /wwo->format.wf.nChannels;
1190         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
1191         break;
1192     case TIME_SMPTE:
1193         time = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1194         lpTime->u.smpte.hour = time / 108000;
1195         time -= lpTime->u.smpte.hour * 108000;
1196         lpTime->u.smpte.min = time / 1800;
1197         time -= lpTime->u.smpte.min * 1800;
1198         lpTime->u.smpte.sec = time / 30;
1199         time -= lpTime->u.smpte.sec * 30;
1200         lpTime->u.smpte.frame = time;
1201         lpTime->u.smpte.fps = 30;
1202         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
1203               lpTime->u.smpte.hour, lpTime->u.smpte.min,
1204               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
1205         break;
1206     default:
1207         FIXME("Format %d not supported ! use TIME_MS !\n", lpTime->wType);
1208         lpTime->wType = TIME_MS;
1209     case TIME_MS:
1210         lpTime->u.ms = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1211         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
1212         break;
1213     }
1214     return MMSYSERR_NOERROR;
1215 }
1216
1217 /**************************************************************************
1218  *                              wodBreakLoop                    [internal]
1219  */
1220 static DWORD wodBreakLoop(WORD wDevID)
1221 {
1222     TRACE("(%u);\n", wDevID);
1223
1224     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].handle == NULL) {
1225         WARN("bad device ID !\n");
1226         return MMSYSERR_BADDEVICEID;
1227     }
1228     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
1229     return MMSYSERR_NOERROR;
1230 }
1231
1232 /**************************************************************************
1233  *                              wodGetVolume                    [internal]
1234  */
1235 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1236 {
1237 #if 0
1238     int         mixer;
1239 #endif
1240     int         volume;
1241     DWORD       left, right;
1242
1243     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1244
1245     if (lpdwVol == NULL)
1246         return MMSYSERR_NOTENABLED;
1247 #if 0
1248     TODO;
1249     if ((mixer = open(MIXER_DEV, O_RDONLY|O_NDELAY)) < 0) {
1250         WARN("mixer device not available !\n");
1251         return MMSYSERR_NOTENABLED;
1252     }
1253     if (ioctl(mixer, SOUND_MIXER_READ_PCM, &volume) == -1) {
1254         WARN("unable to read mixer !\n");
1255         return MMSYSERR_NOTENABLED;
1256     }
1257     close(mixer);
1258 #else
1259     volume = 0x2020;
1260 #endif
1261     left = LOBYTE(volume);
1262     right = HIBYTE(volume);
1263     TRACE("left=%ld right=%ld !\n", left, right);
1264     *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) << 16);
1265     return MMSYSERR_NOERROR;
1266 }
1267
1268 /**************************************************************************
1269  *                              wodSetVolume                    [internal]
1270  */
1271 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1272 {
1273 #if 0
1274     int         mixer;
1275 #endif
1276     int         volume;
1277     DWORD       left, right;
1278
1279     TRACE("(%u, %08lX);\n", wDevID, dwParam);
1280
1281     left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
1282     right = (HIWORD(dwParam) * 100) / 0xFFFFl;
1283     volume = left + (right << 8);
1284
1285 #if 0
1286     TODO;
1287     if ((mixer = open(MIXER_DEV, O_WRONLY|O_NDELAY)) < 0) {
1288         WARN("mixer device not available !\n");
1289         return MMSYSERR_NOTENABLED;
1290     }
1291     if (ioctl(mixer, SOUND_MIXER_WRITE_PCM, &volume) == -1) {
1292         WARN("unable to set mixer !\n");
1293         return MMSYSERR_NOTENABLED;
1294     } else {
1295         TRACE("volume=%04x\n", (unsigned)volume);
1296     }
1297     close(mixer);
1298 #endif
1299     return MMSYSERR_NOERROR;
1300 }
1301
1302 /**************************************************************************
1303  *                              wodGetNumDevs                   [internal]
1304  */
1305 static  DWORD   wodGetNumDevs(void)
1306 {
1307     return ALSA_WodNumDevs;
1308 }
1309
1310 /**************************************************************************
1311  *                              wodMessage (WINEALSA.@)
1312  */
1313 DWORD WINAPI ALSA_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1314                              DWORD dwParam1, DWORD dwParam2)
1315 {
1316     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
1317           wDevID, wMsg, dwUser, dwParam1, dwParam2);
1318
1319     switch (wMsg) {
1320     case DRVM_INIT:
1321     case DRVM_EXIT:
1322     case DRVM_ENABLE:
1323     case DRVM_DISABLE:
1324         /* FIXME: Pretend this is supported */
1325         return 0;
1326     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1327     case WODM_CLOSE:            return wodClose         (wDevID);
1328     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1329     case WODM_PAUSE:            return wodPause         (wDevID);
1330     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
1331     case WODM_BREAKLOOP:        return wodBreakLoop     (wDevID);
1332     case WODM_PREPARE:          return wodPrepare       (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1333     case WODM_UNPREPARE:        return wodUnprepare     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1334     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSA)dwParam1,      dwParam2);
1335     case WODM_GETNUMDEVS:       return wodGetNumDevs    ();
1336     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1337     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1338     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1339     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1340     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
1341     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
1342     case WODM_RESTART:          return wodRestart       (wDevID);
1343     case WODM_RESET:            return wodReset         (wDevID);
1344
1345     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate(wDevID, (PIDSDRIVER*)dwParam1);
1346     default:
1347         FIXME("unknown message %d!\n", wMsg);
1348     }
1349     return MMSYSERR_NOTSUPPORTED;
1350 }
1351
1352 /*======================================================================*
1353  *                  Low level DSOUND implementation                     *
1354  *======================================================================*/
1355
1356 typedef struct IDsDriverImpl IDsDriverImpl;
1357 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1358
1359 struct IDsDriverImpl
1360 {
1361     /* IUnknown fields */
1362     ICOM_VFIELD(IDsDriver);
1363     DWORD               ref;
1364     /* IDsDriverImpl fields */
1365     UINT                wDevID;
1366     IDsDriverBufferImpl*primary;
1367 };
1368
1369 struct IDsDriverBufferImpl
1370 {
1371     /* IUnknown fields */
1372     ICOM_VFIELD(IDsDriverBuffer);
1373     DWORD               ref;
1374     /* IDsDriverBufferImpl fields */
1375     IDsDriverImpl*      drv;
1376     DWORD               buflen;
1377 };
1378
1379 static HRESULT DSDB_UnmapPrimary(IDsDriverBufferImpl *dsdb)
1380 {
1381     WINE_WAVEOUT *wwo = &(WOutDev[dsdb->drv->wDevID]);
1382     if (wwo->mmap_buffer) {
1383         if (snd_pcm_munmap(wwo->handle, SND_PCM_CHANNEL_PLAYBACK) < 0) {
1384             ERR("(%p): Could not unmap sound device (errno=%d)\n", dsdb, errno);
1385             return DSERR_GENERIC;
1386         }
1387         wwo->mmap_buffer = wwo->mmap_control = NULL;
1388         TRACE("(%p): sound device unmapped\n", dsdb);
1389     }
1390     return DS_OK;
1391 }
1392
1393 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
1394 {
1395     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1396     FIXME("(): stub!\n");
1397     return DSERR_UNSUPPORTED;
1398 }
1399
1400 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
1401 {
1402     ICOM_THIS(IDsDriverBufferImpl,iface);
1403     This->ref++;
1404     return This->ref;
1405 }
1406
1407 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
1408 {
1409     ICOM_THIS(IDsDriverBufferImpl,iface);
1410     if (--This->ref)
1411         return This->ref;
1412     if (This == This->drv->primary)
1413         This->drv->primary = NULL;
1414     DSDB_UnmapPrimary(This);
1415     HeapFree(GetProcessHeap(),0,This);
1416     return 0;
1417 }
1418
1419 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
1420                                                LPVOID*ppvAudio1,LPDWORD pdwLen1,
1421                                                LPVOID*ppvAudio2,LPDWORD pdwLen2,
1422                                                DWORD dwWritePosition,DWORD dwWriteLen,
1423                                                DWORD dwFlags)
1424 {
1425     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1426     /* FIXME: we need to implement it */
1427     TRACE("(%p)\n",iface);
1428     return DSERR_UNSUPPORTED;
1429 }
1430
1431 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
1432                                                  LPVOID pvAudio1,DWORD dwLen1,
1433                                                  LPVOID pvAudio2,DWORD dwLen2)
1434 {
1435     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1436     TRACE("(%p)\n",iface);
1437     return DSERR_UNSUPPORTED;
1438 }
1439
1440 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
1441                                                     LPWAVEFORMATEX pwfx)
1442 {
1443     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1444
1445     TRACE("(%p,%p)\n",iface,pwfx);
1446     /* On our request (GetDriverDesc flags), DirectSound has by now used
1447      * waveOutClose/waveOutOpen to set the format...
1448      * unfortunately, this means our mmap() is now gone...
1449      * so we need to somehow signal to our DirectSound implementation
1450      * that it should completely recreate this HW buffer...
1451      * this unexpected error code should do the trick... */
1452     return DSERR_BUFFERLOST;
1453 }
1454
1455 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
1456 {
1457     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1458     TRACE("(%p,%ld): stub\n",iface,dwFreq);
1459     return DSERR_UNSUPPORTED;
1460 }
1461
1462 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
1463 {
1464     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1465     FIXME("(%p,%p): stub!\n",iface,pVolPan);
1466     return DSERR_UNSUPPORTED;
1467 }
1468
1469 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
1470 {
1471     /* ICOM_THIS(IDsDriverImpl,iface); */
1472     TRACE("(%p,%ld): stub\n",iface,dwNewPos);
1473     return DSERR_UNSUPPORTED;
1474 }
1475
1476 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
1477                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
1478 {
1479 #if 0
1480     ICOM_THIS(IDsDriverBufferImpl,iface);
1481     TODO;
1482     count_info info;
1483     DWORD ptr;
1484
1485     TRACE("(%p)\n",iface);
1486     if (WOutDev[This->drv->wDevID].handle == NULL) {
1487         ERR("device not open, but accessing?\n");
1488         return DSERR_UNINITIALIZED;
1489     }
1490     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_GETOPTR, &info) < 0) {
1491         ERR("ioctl failed (%d)\n", errno);
1492         return DSERR_GENERIC;
1493     }
1494     ptr = info.ptr & ~3; /* align the pointer, just in case */
1495     if (lpdwPlay) *lpdwPlay = ptr;
1496     if (lpdwWrite) {
1497         /* add some safety margin (not strictly necessary, but...) */
1498         if (WOutDev[This->drv->wDevID].caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
1499             *lpdwWrite = ptr + 32;
1500         else
1501             *lpdwWrite = ptr + WOutDev[This->drv->wDevID].dwFragmentSize;
1502         while (*lpdwWrite > This->buflen)
1503             *lpdwWrite -= This->buflen;
1504
1505     }
1506 #endif
1507     TRACE("playpos=%ld, writepos=%ld\n", lpdwPlay?*lpdwPlay:0, lpdwWrite?*lpdwWrite:0);
1508     return DS_OK;
1509 }
1510
1511 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
1512 {
1513     ICOM_THIS(IDsDriverBufferImpl,iface);
1514
1515     TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
1516
1517     /* FIXME: error handling */
1518     snd_pcm_playback_go(WOutDev[This->drv->wDevID].handle);
1519
1520     return DS_OK;
1521 }
1522
1523 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
1524 {
1525     ICOM_THIS(IDsDriverBufferImpl,iface);
1526
1527     TRACE("(%p)\n",iface);
1528
1529     /* no more playing */
1530     /* FIXME: error handling */
1531     snd_pcm_playback_drain(WOutDev[This->drv->wDevID].handle);
1532
1533     /* Most ALSA drivers just can't stop the playback without closing the device...
1534      * so we need to somehow signal to our DirectSound implementation
1535      * that it should completely recreate this HW buffer...
1536      * this unexpected error code should do the trick... */
1537     return DSERR_BUFFERLOST;
1538 }
1539
1540 static ICOM_VTABLE(IDsDriverBuffer) dsdbvt =
1541 {
1542     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1543     IDsDriverBufferImpl_QueryInterface,
1544     IDsDriverBufferImpl_AddRef,
1545     IDsDriverBufferImpl_Release,
1546     IDsDriverBufferImpl_Lock,
1547     IDsDriverBufferImpl_Unlock,
1548     IDsDriverBufferImpl_SetFormat,
1549     IDsDriverBufferImpl_SetFrequency,
1550     IDsDriverBufferImpl_SetVolumePan,
1551     IDsDriverBufferImpl_SetPosition,
1552     IDsDriverBufferImpl_GetPosition,
1553     IDsDriverBufferImpl_Play,
1554     IDsDriverBufferImpl_Stop
1555 };
1556
1557 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
1558 {
1559     /* ICOM_THIS(IDsDriverImpl,iface); */
1560     FIXME("(%p): stub!\n",iface);
1561     return DSERR_UNSUPPORTED;
1562 }
1563
1564 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
1565 {
1566     ICOM_THIS(IDsDriverImpl,iface);
1567     This->ref++;
1568     return This->ref;
1569 }
1570
1571 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
1572 {
1573     ICOM_THIS(IDsDriverImpl,iface);
1574     if (--This->ref)
1575         return This->ref;
1576     HeapFree(GetProcessHeap(),0,This);
1577     return 0;
1578 }
1579
1580 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
1581 {
1582     ICOM_THIS(IDsDriverImpl,iface);
1583     TRACE("(%p,%p)\n",iface,pDesc);
1584     pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
1585         DSDDESC_USESYSTEMMEMORY;
1586     strcpy(pDesc->szDesc,"WineALSA DirectSound Driver");
1587     strcpy(pDesc->szDrvName,"winealsa.drv");
1588     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
1589     pDesc->wVxdId               = 0;
1590     pDesc->wReserved            = 0;
1591     pDesc->ulDeviceNum          = This->wDevID;
1592     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
1593     pDesc->pvDirectDrawHeap     = NULL;
1594     pDesc->dwMemStartAddress    = 0;
1595     pDesc->dwMemEndAddress      = 0;
1596     pDesc->dwMemAllocExtra      = 0;
1597     pDesc->pvReserved1          = NULL;
1598     pDesc->pvReserved2          = NULL;
1599     return DS_OK;
1600 }
1601
1602 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
1603 {
1604     ICOM_THIS(IDsDriverImpl,iface);
1605
1606     TRACE("(%p)\n",iface);
1607     /* FIXME: error handling */
1608     snd_pcm_channel_prepare(WOutDev[This->wDevID].handle, SND_PCM_CHANNEL_PLAYBACK);
1609
1610     return DS_OK;
1611 }
1612
1613 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
1614 {
1615     ICOM_THIS(IDsDriverImpl,iface);
1616     TRACE("(%p)\n",iface);
1617     if (This->primary) {
1618         ERR("problem with DirectSound: primary not released\n");
1619         return DSERR_GENERIC;
1620     }
1621     return DS_OK;
1622 }
1623
1624 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
1625 {
1626     /* ICOM_THIS(IDsDriverImpl,iface); */
1627     TRACE("(%p,%p)\n",iface,pCaps);
1628     memset(pCaps, 0, sizeof(*pCaps));
1629     /* FIXME: need to check actual capabilities */
1630     pCaps->dwFlags = DSCAPS_PRIMARYMONO | DSCAPS_PRIMARYSTEREO |
1631         DSCAPS_PRIMARY8BIT | DSCAPS_PRIMARY16BIT;
1632     pCaps->dwPrimaryBuffers = 1;
1633     /* the other fields only apply to secondary buffers, which we don't support
1634      * (unless we want to mess with wavetable synthesizers and MIDI) */
1635     return DS_OK;
1636 }
1637
1638 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
1639                                                       LPWAVEFORMATEX pwfx,
1640                                                       DWORD dwFlags, DWORD dwCardAddress,
1641                                                       LPDWORD pdwcbBufferSize,
1642                                                       LPBYTE *ppbBuffer,
1643                                                       LPVOID *ppvObj)
1644 {
1645     ICOM_THIS(IDsDriverImpl,iface);
1646     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
1647     WINE_WAVEOUT *wwo = &(WOutDev[This->wDevID]);
1648     struct snd_pcm_channel_setup setup;
1649
1650     TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
1651     /* we only support primary buffers */
1652     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
1653         return DSERR_UNSUPPORTED;
1654     if (This->primary)
1655         return DSERR_ALLOCATED;
1656     if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
1657         return DSERR_CONTROLUNAVAIL;
1658
1659     *ippdsdb = (IDsDriverBufferImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
1660     if (*ippdsdb == NULL)
1661         return DSERR_OUTOFMEMORY;
1662     (*ippdsdb)->lpVtbl  = &dsdbvt;
1663     (*ippdsdb)->ref     = 1;
1664     (*ippdsdb)->drv     = This;
1665
1666     if (!wwo->mmap_buffer) {
1667         if (snd_pcm_mmap(wwo->handle, SND_PCM_CHANNEL_PLAYBACK, &wwo->mmap_control, &wwo->mmap_buffer))
1668         {
1669             ERR("(%p): Could not map sound device for direct access (%s)\n", *ippdsdb, snd_strerror(errno));
1670             return DSERR_GENERIC;
1671         }
1672
1673         setup.mode = SND_PCM_MODE_BLOCK;
1674         setup.channel = SND_PCM_CHANNEL_PLAYBACK;
1675         if (snd_pcm_channel_setup(wwo->handle, &setup) < 0) {
1676             ERR("Unable to obtain setup\n");
1677             /* FIXME: resource cleanup */
1678             return DSERR_GENERIC;
1679         }
1680         wwo->mmap_block_size = setup.buf.block.frag_size;
1681         wwo->mmap_block_number = setup.buf.block.frags;
1682
1683         TRACE("(%p): sound device has been mapped for direct access at %p, size=%d\n",
1684               *ippdsdb, wwo->mmap_buffer, setup.buf.block.frags * setup.buf.block.frag_size);
1685 #if 0
1686         /* for some reason, es1371 and sblive! sometimes have junk in here.
1687          * clear it, or we get junk noise */
1688         /* some libc implementations are buggy: their memset reads from the buffer...
1689          * to work around it, we have to zero the block by hand. We don't do the expected:
1690          * memset(wwo->mapping, 0, wwo->maplen);
1691          */
1692         {
1693             char*       p1 = wwo->mapping;
1694             unsigned    len = wwo->maplen;
1695
1696             if (len >= 16) /* so we can have at least a 4 long area to store... */
1697             {
1698                 /* the mmap:ed value is (at least) dword aligned
1699                  * so, start filling the complete unsigned long:s
1700                  */
1701                 int             b = len >> 2;
1702                 unsigned long*  p4 = (unsigned long*)p1;
1703
1704                 while (b--) *p4++ = 0;
1705                 /* prepare for filling the rest */
1706                 len &= 3;
1707                 p1 = (unsigned char*)p4;
1708             }
1709             /* in all cases, fill the remaining bytes */
1710             while (len-- != 0) *p1++ = 0;
1711         }
1712 #endif
1713     }
1714
1715     /* primary buffer is ready to go */
1716     *pdwcbBufferSize    = wwo->mmap_block_size * wwo->mmap_block_number;
1717     *ppbBuffer          = wwo->mmap_buffer;
1718
1719     This->primary = *ippdsdb;
1720
1721     return DS_OK;
1722 }
1723
1724 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
1725                                                          PIDSDRIVERBUFFER pBuffer,
1726                                                          LPVOID *ppvObj)
1727 {
1728     /* ICOM_THIS(IDsDriverImpl,iface); */
1729     TRACE("(%p,%p): stub\n",iface,pBuffer);
1730     return DSERR_INVALIDCALL;
1731 }
1732
1733 static ICOM_VTABLE(IDsDriver) dsdvt =
1734 {
1735     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1736     IDsDriverImpl_QueryInterface,
1737     IDsDriverImpl_AddRef,
1738     IDsDriverImpl_Release,
1739     IDsDriverImpl_GetDriverDesc,
1740     IDsDriverImpl_Open,
1741     IDsDriverImpl_Close,
1742     IDsDriverImpl_GetCaps,
1743     IDsDriverImpl_CreateSoundBuffer,
1744     IDsDriverImpl_DuplicateSoundBuffer
1745 };
1746
1747 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1748 {
1749     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
1750
1751     /* the HAL isn't much better than the HEL if we can't do mmap() */
1752     if (!(WOutDev[wDevID].caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
1753         ERR("DirectSound flag not set\n");
1754         MESSAGE("This sound card's driver does not support direct access\n");
1755         MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
1756         return MMSYSERR_NOTSUPPORTED;
1757     }
1758
1759     *idrv = (IDsDriverImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
1760     if (!*idrv)
1761         return MMSYSERR_NOMEM;
1762     (*idrv)->lpVtbl     = &dsdvt;
1763     (*idrv)->ref        = 1;
1764
1765     (*idrv)->wDevID     = wDevID;
1766     (*idrv)->primary    = NULL;
1767     return MMSYSERR_NOERROR;
1768 }
1769
1770 /* we don't need a default wodMessage for audio when we don't have ALSA, the
1771  * audio.c file will provide it for us
1772  */
1773 #endif /* HAVE_ALSA && interface == 0.5 */