gdi32: Add a stub for CancelDC.
[wine] / dlls / winealsa.drv / waveout.c
1 /*
2  * Sample Wine Driver for Advanced Linux Sound System (ALSA)
3  *      Based on version <final> of the ALSA API
4  *
5  * Copyright    2002 Eric Pouech
6  *              2002 Marco Pietrobono
7  *              2003 Christian Costa : WaveIn support
8  *              2006-2007 Maarten Lankhorst
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 /*======================================================================*
26  *                  Low level WAVE OUT implementation                   *
27  *======================================================================*/
28
29 #include "config.h"
30 #include "wine/port.h"
31
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <string.h>
36 #ifdef HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
39 #include <errno.h>
40 #include <limits.h>
41 #include <fcntl.h>
42 #ifdef HAVE_SYS_IOCTL_H
43 # include <sys/ioctl.h>
44 #endif
45 #ifdef HAVE_SYS_MMAN_H
46 # include <sys/mman.h>
47 #endif
48 #include "windef.h"
49 #include "winbase.h"
50 #include "wingdi.h"
51 #include "winerror.h"
52 #include "winuser.h"
53 #include "winnls.h"
54 #include "mmddk.h"
55
56 #include "alsa.h"
57
58 #include "wine/library.h"
59 #include "wine/unicode.h"
60 #include "wine/debug.h"
61
62 WINE_DEFAULT_DEBUG_CHANNEL(wave);
63
64 #ifdef HAVE_ALSA
65
66 WINE_WAVEDEV    *WOutDev;
67 DWORD            ALSA_WodNumMallocedDevs;
68 DWORD            ALSA_WodNumDevs;
69
70 /**************************************************************************
71  *                      wodNotifyClient                 [internal]
72  */
73 static DWORD wodNotifyClient(WINE_WAVEDEV* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
74 {
75     TRACE("wMsg = 0x%04x dwParm1 = %04X dwParam2 = %04X\n", wMsg, dwParam1, dwParam2);
76
77     switch (wMsg) {
78     case WOM_OPEN:
79     case WOM_CLOSE:
80     case WOM_DONE:
81         if (wwo->wFlags != DCB_NULL &&
82             !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags, (HDRVR)wwo->waveDesc.hWave,
83                             wMsg, wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
84             WARN("can't notify client !\n");
85             return MMSYSERR_ERROR;
86         }
87         break;
88     default:
89         FIXME("Unknown callback message %u\n", wMsg);
90         return MMSYSERR_INVALPARAM;
91     }
92     return MMSYSERR_NOERROR;
93 }
94
95 /**************************************************************************
96  *                              wodUpdatePlayedTotal    [internal]
97  *
98  */
99 static BOOL wodUpdatePlayedTotal(WINE_WAVEDEV* wwo, snd_pcm_status_t* ps)
100 {
101     snd_pcm_sframes_t delay = 0;
102     snd_pcm_state_t state;
103
104     state = snd_pcm_state(wwo->pcm);
105     snd_pcm_delay(wwo->pcm, &delay);
106
107     /* A delay < 0 indicates an underrun; for our purposes that's 0.  */
108     if ( (state != SND_PCM_STATE_RUNNING && state != SND_PCM_STATE_PREPARED) || (delay < 0))
109     {
110         WARN("Unexpected state (%d) or delay (%ld) while updating Total Played, resetting\n", state, delay);
111         delay=0;
112     }
113     wwo->dwPlayedTotal = wwo->dwWrittenTotal - snd_pcm_frames_to_bytes(wwo->pcm, delay);
114     return TRUE;
115 }
116
117 /**************************************************************************
118  *                              wodPlayer_BeginWaveHdr          [internal]
119  *
120  * Makes the specified lpWaveHdr the currently playing wave header.
121  * If the specified wave header is a begin loop and we're not already in
122  * a loop, setup the loop.
123  */
124 static void wodPlayer_BeginWaveHdr(WINE_WAVEDEV* wwo, LPWAVEHDR lpWaveHdr)
125 {
126     wwo->lpPlayPtr = lpWaveHdr;
127
128     if (!lpWaveHdr) return;
129
130     if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
131         if (wwo->lpLoopPtr) {
132             WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
133         } else {
134             TRACE("Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
135             wwo->lpLoopPtr = lpWaveHdr;
136             /* Windows does not touch WAVEHDR.dwLoops,
137              * so we need to make an internal copy */
138             wwo->dwLoops = lpWaveHdr->dwLoops;
139         }
140     }
141     wwo->dwPartialOffset = 0;
142 }
143
144 /**************************************************************************
145  *                              wodPlayer_PlayPtrNext           [internal]
146  *
147  * Advance the play pointer to the next waveheader, looping if required.
148  */
149 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEDEV* wwo)
150 {
151     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
152
153     wwo->dwPartialOffset = 0;
154     if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
155         /* We're at the end of a loop, loop if required */
156         if (--wwo->dwLoops > 0) {
157             wwo->lpPlayPtr = wwo->lpLoopPtr;
158         } else {
159             /* Handle overlapping loops correctly */
160             if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
161                 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
162                 /* shall we consider the END flag for the closing loop or for
163                  * the opening one or for both ???
164                  * code assumes for closing loop only
165                  */
166             } else {
167                 lpWaveHdr = lpWaveHdr->lpNext;
168             }
169             wwo->lpLoopPtr = NULL;
170             wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
171         }
172     } else {
173         /* We're not in a loop.  Advance to the next wave header */
174         wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
175     }
176
177     return lpWaveHdr;
178 }
179
180 /**************************************************************************
181  *                           wodPlayer_DSPWait                  [internal]
182  * Returns the number of milliseconds to wait for the DSP buffer to play a
183  * period
184  */
185 static DWORD wodPlayer_DSPWait(const WINE_WAVEDEV *wwo)
186 {
187     /* time for one period to be played */
188     unsigned int val=0;
189     int dir=0;
190     int err=0;
191     err = snd_pcm_hw_params_get_period_time(wwo->hw_params, &val, &dir);
192     return val / 1000;
193 }
194
195 /**************************************************************************
196  *                           wodPlayer_NotifyWait               [internal]
197  * Returns the number of milliseconds to wait before attempting to notify
198  * completion of the specified wavehdr.
199  * This is based on the number of bytes remaining to be written in the
200  * wave.
201  */
202 static DWORD wodPlayer_NotifyWait(const WINE_WAVEDEV* wwo, LPWAVEHDR lpWaveHdr)
203 {
204     DWORD dwMillis;
205
206     if (lpWaveHdr->reserved < wwo->dwPlayedTotal) {
207         dwMillis = 1;
208     } else {
209         dwMillis = (lpWaveHdr->reserved - wwo->dwPlayedTotal) * 1000 / wwo->format.Format.nAvgBytesPerSec;
210         if (!dwMillis) dwMillis = 1;
211     }
212
213     return dwMillis;
214 }
215
216
217 /**************************************************************************
218  *                           wodPlayer_WriteMaxFrags            [internal]
219  * Writes the maximum number of frames possible to the DSP and returns
220  * the number of frames written.
221  */
222 static int wodPlayer_WriteMaxFrags(WINE_WAVEDEV* wwo, DWORD* frames)
223 {
224     /* Only attempt to write to free frames */
225     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
226     DWORD dwLength = snd_pcm_bytes_to_frames(wwo->pcm, lpWaveHdr->dwBufferLength - wwo->dwPartialOffset);
227     int toWrite = min(dwLength, *frames);
228     int written;
229
230     TRACE("Writing wavehdr %p.%u[%u]\n", lpWaveHdr, wwo->dwPartialOffset, lpWaveHdr->dwBufferLength);
231
232     if (toWrite > 0) {
233         written = (wwo->write)(wwo->pcm, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
234         if ( written < 0) {
235             /* XRUN occurred. let's try to recover */
236             ALSA_XRUNRecovery(wwo, written);
237             written = (wwo->write)(wwo->pcm, lpWaveHdr->lpData + wwo->dwPartialOffset, toWrite);
238         }
239         if (written <= 0) {
240             /* still in error */
241             ERR("Error in writing wavehdr. Reason: %s\n", snd_strerror(written));
242             return written;
243         }
244     } else
245         written = 0;
246
247     wwo->dwPartialOffset += snd_pcm_frames_to_bytes(wwo->pcm, written);
248     if ( wwo->dwPartialOffset >= lpWaveHdr->dwBufferLength) {
249         /* this will be used to check if the given wave header has been fully played or not... */
250         wwo->dwPartialOffset = lpWaveHdr->dwBufferLength;
251         /* If we wrote all current wavehdr, skip to the next one */
252         wodPlayer_PlayPtrNext(wwo);
253     }
254     *frames -= written;
255     wwo->dwWrittenTotal += snd_pcm_frames_to_bytes(wwo->pcm, written);
256     TRACE("dwWrittenTotal=%u\n", wwo->dwWrittenTotal);
257
258     return written;
259 }
260
261
262 /**************************************************************************
263  *                              wodPlayer_NotifyCompletions     [internal]
264  *
265  * Notifies and remove from queue all wavehdrs which have been played to
266  * the speaker (ie. they have cleared the ALSA buffer).  If force is true,
267  * we notify all wavehdrs and remove them all from the queue even if they
268  * are unplayed or part of a loop.
269  */
270 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEDEV* wwo, BOOL force)
271 {
272     LPWAVEHDR           lpWaveHdr;
273
274     /* Start from lpQueuePtr and keep notifying until:
275      * - we hit an unwritten wavehdr
276      * - we hit the beginning of a running loop
277      * - we hit a wavehdr which hasn't finished playing
278      */
279 #if 0
280     while ((lpWaveHdr = wwo->lpQueuePtr) &&
281            (force ||
282             (lpWaveHdr != wwo->lpPlayPtr &&
283              lpWaveHdr != wwo->lpLoopPtr &&
284              lpWaveHdr->reserved <= wwo->dwPlayedTotal))) {
285
286         wwo->lpQueuePtr = lpWaveHdr->lpNext;
287
288         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
289         lpWaveHdr->dwFlags |= WHDR_DONE;
290
291         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
292     }
293 #else
294     for (;;)
295     {
296         lpWaveHdr = wwo->lpQueuePtr;
297         if (!lpWaveHdr) {TRACE("Empty queue\n"); break;}
298         if (!force)
299         {
300             if (lpWaveHdr == wwo->lpPlayPtr) {TRACE("play %p\n", lpWaveHdr); break;}
301             if (lpWaveHdr == wwo->lpLoopPtr) {TRACE("loop %p\n", lpWaveHdr); break;}
302             if (lpWaveHdr->reserved > wwo->dwPlayedTotal) {TRACE("still playing %p (%u/%u)\n", lpWaveHdr, lpWaveHdr->reserved, wwo->dwPlayedTotal);break;}
303         }
304         wwo->lpQueuePtr = lpWaveHdr->lpNext;
305
306         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
307         lpWaveHdr->dwFlags |= WHDR_DONE;
308
309         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
310     }
311 #endif
312     return  (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
313         wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
314 }
315
316
317 /**************************************************************************
318  *                              wodPlayer_Reset                 [internal]
319  *
320  * wodPlayer helper. Resets current output stream.
321  */
322 static  void    wodPlayer_Reset(WINE_WAVEDEV* wwo, BOOL reset)
323 {
324     int                         err;
325     TRACE("(%p)\n", wwo);
326
327     /* flush all possible output */
328     snd_pcm_drain(wwo->pcm);
329
330     wodUpdatePlayedTotal(wwo, NULL);
331     /* updates current notify list */
332     wodPlayer_NotifyCompletions(wwo, FALSE);
333
334     if ( (err = snd_pcm_drop(wwo->pcm)) < 0) {
335         FIXME("flush: %s\n", snd_strerror(err));
336         wwo->hThread = 0;
337         wwo->state = WINE_WS_STOPPED;
338         ExitThread(-1);
339     }
340     if ( (err = snd_pcm_prepare(wwo->pcm)) < 0 )
341         ERR("pcm prepare failed: %s\n", snd_strerror(err));
342
343     if (reset) {
344         enum win_wm_message     msg;
345         DWORD                   param;
346         HANDLE                  ev;
347
348         /* remove any buffer */
349         wodPlayer_NotifyCompletions(wwo, TRUE);
350
351         wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
352         wwo->state = WINE_WS_STOPPED;
353         wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
354         /* Clear partial wavehdr */
355         wwo->dwPartialOffset = 0;
356
357         /* remove any existing message in the ring */
358         EnterCriticalSection(&wwo->msgRing.msg_crst);
359         /* return all pending headers in queue */
360         while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
361         {
362             if (msg != WINE_WM_HEADER)
363             {
364                 FIXME("shouldn't have headers left\n");
365                 SetEvent(ev);
366                 continue;
367             }
368             ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
369             ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
370
371                 wodNotifyClient(wwo, WOM_DONE, param, 0);
372         }
373         ALSA_ResetRingMessage(&wwo->msgRing);
374         LeaveCriticalSection(&wwo->msgRing.msg_crst);
375     } else {
376         if (wwo->lpLoopPtr) {
377             /* complicated case, not handled yet (could imply modifying the loop counter */
378             FIXME("Pausing while in loop isn't correctly handled yet, except strange results\n");
379             wwo->lpPlayPtr = wwo->lpLoopPtr;
380             wwo->dwPartialOffset = 0;
381             wwo->dwWrittenTotal = wwo->dwPlayedTotal; /* this is wrong !!! */
382         } else {
383             LPWAVEHDR   ptr;
384             DWORD       sz = wwo->dwPartialOffset;
385
386             /* reset all the data as if we had written only up to lpPlayedTotal bytes */
387             /* compute the max size playable from lpQueuePtr */
388             for (ptr = wwo->lpQueuePtr; ptr != wwo->lpPlayPtr; ptr = ptr->lpNext) {
389                 sz += ptr->dwBufferLength;
390             }
391             /* because the reset lpPlayPtr will be lpQueuePtr */
392             if (wwo->dwWrittenTotal > wwo->dwPlayedTotal + sz) ERR("grin\n");
393             wwo->dwPartialOffset = sz - (wwo->dwWrittenTotal - wwo->dwPlayedTotal);
394             wwo->dwWrittenTotal = wwo->dwPlayedTotal;
395             wwo->lpPlayPtr = wwo->lpQueuePtr;
396         }
397         wwo->state = WINE_WS_PAUSED;
398     }
399 }
400
401 /**************************************************************************
402  *                    wodPlayer_ProcessMessages                 [internal]
403  */
404 static void wodPlayer_ProcessMessages(WINE_WAVEDEV* wwo)
405 {
406     LPWAVEHDR           lpWaveHdr;
407     enum win_wm_message msg;
408     DWORD               param;
409     HANDLE              ev;
410     int                 err;
411
412     while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
413      TRACE("Received %s %x\n", ALSA_getCmdString(msg), param);
414
415         switch (msg) {
416         case WINE_WM_PAUSING:
417             if ( snd_pcm_state(wwo->pcm) == SND_PCM_STATE_RUNNING )
418              {
419                 if ( snd_pcm_hw_params_can_pause(wwo->hw_params) )
420                 {
421                     err = snd_pcm_pause(wwo->pcm, 1);
422                     if ( err < 0 )
423                         ERR("pcm_pause failed: %s\n", snd_strerror(err));
424                     wwo->state = WINE_WS_PAUSED;
425                 }
426                 else
427                 {
428                     wodPlayer_Reset(wwo,FALSE);
429                 }
430              }
431             SetEvent(ev);
432             break;
433         case WINE_WM_RESTARTING:
434             if (wwo->state == WINE_WS_PAUSED)
435             {
436                 if ( snd_pcm_state(wwo->pcm) == SND_PCM_STATE_PAUSED )
437                  {
438                     err = snd_pcm_pause(wwo->pcm, 0);
439                     if ( err < 0 )
440                         ERR("pcm_pause failed: %s\n", snd_strerror(err));
441                  }
442                 wwo->state = WINE_WS_PLAYING;
443             }
444             SetEvent(ev);
445             break;
446         case WINE_WM_HEADER:
447             lpWaveHdr = (LPWAVEHDR)param;
448
449             /* insert buffer at the end of queue */
450             {
451                 LPWAVEHDR*      wh;
452                 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
453                 *wh = lpWaveHdr;
454             }
455             if (!wwo->lpPlayPtr)
456                 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
457             if (wwo->state == WINE_WS_STOPPED)
458                 wwo->state = WINE_WS_PLAYING;
459             break;
460         case WINE_WM_RESETTING:
461             wodPlayer_Reset(wwo,TRUE);
462             SetEvent(ev);
463             break;
464         case WINE_WM_UPDATE:
465             wodUpdatePlayedTotal(wwo, NULL);
466             SetEvent(ev);
467             break;
468         case WINE_WM_BREAKLOOP:
469             if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
470                 /* ensure exit at end of current loop */
471                 wwo->dwLoops = 1;
472             }
473             SetEvent(ev);
474             break;
475         case WINE_WM_CLOSING:
476             /* sanity check: this should not happen since the device must have been reset before */
477             if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
478             wwo->hThread = 0;
479             wwo->state = WINE_WS_CLOSED;
480             SetEvent(ev);
481             ExitThread(0);
482             /* shouldn't go here */
483         default:
484             FIXME("unknown message %d\n", msg);
485             break;
486         }
487     }
488 }
489
490 /**************************************************************************
491  *                           wodPlayer_FeedDSP                  [internal]
492  * Feed as much sound data as we can into the DSP and return the number of
493  * milliseconds before it will be necessary to feed the DSP again.
494  */
495 static DWORD wodPlayer_FeedDSP(WINE_WAVEDEV* wwo)
496 {
497     DWORD               availInQ;
498
499     wodUpdatePlayedTotal(wwo, NULL);
500     availInQ = snd_pcm_avail_update(wwo->pcm);
501
502 #if 0
503     /* input queue empty and output buffer with less than one fragment to play */
504     if (!wwo->lpPlayPtr && wwo->dwBufferSize < availInQ + wwo->dwFragmentSize) {
505         TRACE("Run out of wavehdr:s...\n");
506         return INFINITE;
507     }
508 #endif
509     /* no more room... no need to try to feed */
510     if (availInQ > 0) {
511         /* Feed from partial wavehdr */
512         if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0) {
513             wodPlayer_WriteMaxFrags(wwo, &availInQ);
514         }
515
516         /* Feed wavehdrs until we run out of wavehdrs or DSP space */
517         if (wwo->dwPartialOffset == 0 && wwo->lpPlayPtr) {
518             do {
519                 TRACE("Setting time to elapse for %p to %u\n",
520                       wwo->lpPlayPtr, wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength);
521                 /* note the value that dwPlayedTotal will return when this wave finishes playing */
522                 wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
523             } while (wodPlayer_WriteMaxFrags(wwo, &availInQ) && wwo->lpPlayPtr && availInQ > 0);
524         }
525     }
526
527     return wodPlayer_DSPWait(wwo);
528 }
529
530 /**************************************************************************
531  *                              wodPlayer                       [internal]
532  */
533 static  DWORD   CALLBACK        wodPlayer(LPVOID pmt)
534 {
535     WORD          uDevID = (DWORD)pmt;
536     WINE_WAVEDEV* wwo = (WINE_WAVEDEV*)&WOutDev[uDevID];
537     DWORD         dwNextFeedTime = INFINITE;   /* Time before DSP needs feeding */
538     DWORD         dwNextNotifyTime = INFINITE; /* Time before next wave completion */
539     DWORD         dwSleepTime;
540
541     wwo->state = WINE_WS_STOPPED;
542     SetEvent(wwo->hStartUpEvent);
543
544     for (;;) {
545         /** Wait for the shortest time before an action is required.  If there
546          *  are no pending actions, wait forever for a command.
547          */
548         dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
549         TRACE("waiting %ums (%u,%u)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
550         ALSA_WaitRingMessage(&wwo->msgRing, dwSleepTime);
551         wodPlayer_ProcessMessages(wwo);
552         if (wwo->state == WINE_WS_PLAYING) {
553             dwNextFeedTime = wodPlayer_FeedDSP(wwo);
554             dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
555             if (dwNextFeedTime == INFINITE) {
556                 /* FeedDSP ran out of data, but before giving up, */
557                 /* check that a notification didn't give us more */
558                 wodPlayer_ProcessMessages(wwo);
559                 if (wwo->lpPlayPtr) {
560                     TRACE("recovering\n");
561                     dwNextFeedTime = wodPlayer_FeedDSP(wwo);
562                 }
563             }
564         } else {
565             dwNextFeedTime = dwNextNotifyTime = INFINITE;
566         }
567     }
568 }
569
570 /**************************************************************************
571  *                      wodGetDevCaps                           [internal]
572  */
573 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
574 {
575     TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
576
577     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
578
579     if (wDevID >= ALSA_WodNumDevs) {
580         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
581         return MMSYSERR_BADDEVICEID;
582     }
583
584     memcpy(lpCaps, &WOutDev[wDevID].outcaps, min(dwSize, sizeof(*lpCaps)));
585     return MMSYSERR_NOERROR;
586 }
587
588 /**************************************************************************
589  *                              wodOpen                         [internal]
590  */
591 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
592 {
593     WINE_WAVEDEV*               wwo;
594     snd_pcm_t *                 pcm = NULL;
595     snd_hctl_t *                hctl = NULL;
596     snd_pcm_hw_params_t *       hw_params = NULL;
597     snd_pcm_sw_params_t *       sw_params;
598     snd_pcm_access_t            access;
599     snd_pcm_format_t            format = -1;
600     unsigned int                rate;
601     unsigned int                buffer_time = 500000;
602     unsigned int                period_time = 10000;
603     snd_pcm_uframes_t           buffer_size;
604     snd_pcm_uframes_t           period_size;
605     int                         flags;
606     int                         err=0;
607     int                         dir=0;
608     DWORD                       retcode = 0;
609
610     snd_pcm_sw_params_alloca(&sw_params);
611
612     TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
613     if (lpDesc == NULL) {
614         WARN("Invalid Parameter !\n");
615         return MMSYSERR_INVALPARAM;
616     }
617     if (wDevID >= ALSA_WodNumDevs) {
618         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
619         return MMSYSERR_BADDEVICEID;
620     }
621
622     /* only PCM format is supported so far... */
623     if (!ALSA_supportedFormat(lpDesc->lpFormat)) {
624         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
625              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
626              lpDesc->lpFormat->nSamplesPerSec);
627         return WAVERR_BADFORMAT;
628     }
629
630     if (dwFlags & WAVE_FORMAT_QUERY) {
631         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
632              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
633              lpDesc->lpFormat->nSamplesPerSec);
634         return MMSYSERR_NOERROR;
635     }
636
637     wwo = &WOutDev[wDevID];
638
639     if (wwo->pcm != NULL) {
640         WARN("%d already allocated\n", wDevID);
641         return MMSYSERR_ALLOCATED;
642     }
643
644     if ((dwFlags & WAVE_DIRECTSOUND) && !(wwo->outcaps.dwSupport & WAVECAPS_DIRECTSOUND))
645         /* not supported, ignore it */
646         dwFlags &= ~WAVE_DIRECTSOUND;
647
648     flags = SND_PCM_NONBLOCK;
649
650     /* FIXME - why is this ifdefed? */
651 #if 0
652     if ( dwFlags & WAVE_DIRECTSOUND )
653         flags |= SND_PCM_ASYNC;
654 #endif
655
656     if ( (err = snd_pcm_open(&pcm, wwo->pcmname, SND_PCM_STREAM_PLAYBACK, flags)) < 0)
657     {
658         ERR("Error open: %s\n", snd_strerror(err));
659         return MMSYSERR_NOTENABLED;
660     }
661
662     if (wwo->ctlname)
663     {
664         err = snd_hctl_open(&hctl, wwo->ctlname, 0);
665         if (err >= 0)
666         {
667             snd_hctl_load(hctl);
668         }
669         else
670         {
671             WARN("Could not open hctl for [%s]: %s\n", wwo->ctlname, snd_strerror(err));
672             hctl = NULL;
673         }
674     }
675
676     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
677
678     memcpy(&wwo->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
679     ALSA_copyFormat(lpDesc->lpFormat, &wwo->format);
680
681     TRACE("Requested this format: %dx%dx%d %s\n",
682           wwo->format.Format.nSamplesPerSec,
683           wwo->format.Format.wBitsPerSample,
684           wwo->format.Format.nChannels,
685           ALSA_getFormat(wwo->format.Format.wFormatTag));
686
687     if (wwo->format.Format.wBitsPerSample == 0) {
688         WARN("Resetting zeroed wBitsPerSample\n");
689         wwo->format.Format.wBitsPerSample = 8 *
690             (wwo->format.Format.nAvgBytesPerSec /
691              wwo->format.Format.nSamplesPerSec) /
692             wwo->format.Format.nChannels;
693     }
694
695 #define EXIT_ON_ERROR(f,e,txt) do \
696 { \
697     int err; \
698     if ( (err = (f) ) < 0) \
699     { \
700         WARN(txt ": %s\n", snd_strerror(err)); \
701         retcode=e; \
702         goto errexit; \
703     } \
704 } while(0)
705
706     snd_pcm_hw_params_malloc(&hw_params);
707     if (! hw_params)
708     {
709         retcode = MMSYSERR_NOMEM;
710         goto errexit;
711     }
712     snd_pcm_hw_params_any(pcm, hw_params);
713
714     access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
715     if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
716         WARN("mmap not available. switching to standard write.\n");
717         access = SND_PCM_ACCESS_RW_INTERLEAVED;
718         EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
719         wwo->write = snd_pcm_writei;
720     }
721     else
722         wwo->write = snd_pcm_mmap_writei;
723
724     if ((err = snd_pcm_hw_params_set_channels(pcm, hw_params, wwo->format.Format.nChannels)) < 0) {
725         WARN("unable to set required channels: %d\n", wwo->format.Format.nChannels);
726         if (dwFlags & WAVE_DIRECTSOUND) {
727             if (wwo->format.Format.nChannels > 2)
728                 wwo->format.Format.nChannels = 2;
729             else if (wwo->format.Format.nChannels == 2)
730                 wwo->format.Format.nChannels = 1;
731             else if (wwo->format.Format.nChannels == 1)
732                 wwo->format.Format.nChannels = 2;
733             /* recalculate block align and bytes per second */
734             wwo->format.Format.nBlockAlign = (wwo->format.Format.wBitsPerSample * wwo->format.Format.nChannels) / 8;
735             wwo->format.Format.nAvgBytesPerSec = wwo->format.Format.nSamplesPerSec * wwo->format.Format.nBlockAlign;
736             WARN("changed number of channels from %d to %d\n", lpDesc->lpFormat->nChannels, wwo->format.Format.nChannels);
737         }
738         EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwo->format.Format.nChannels ), WAVERR_BADFORMAT, "unable to set required channels" );
739     }
740
741     if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
742         ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
743         IsEqualGUID(&wwo->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
744         format = (wwo->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
745                  (wwo->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
746                  (wwo->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
747                  (wwo->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
748     } else if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
749         IsEqualGUID(&wwo->format.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)){
750         format = (wwo->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_FLOAT_LE : -1;
751     } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
752         FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
753         retcode = WAVERR_BADFORMAT;
754         goto errexit;
755     } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
756         FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
757         retcode = WAVERR_BADFORMAT;
758         goto errexit;
759     } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
760         FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
761         retcode = WAVERR_BADFORMAT;
762         goto errexit;
763     } else {
764         ERR("invalid format: %0x04x\n", wwo->format.Format.wFormatTag);
765         retcode = WAVERR_BADFORMAT;
766         goto errexit;
767     }
768
769     if ((err = snd_pcm_hw_params_set_format(pcm, hw_params, format)) < 0) {
770         WARN("unable to set required format: %s\n", snd_pcm_format_name(format));
771         if (dwFlags & WAVE_DIRECTSOUND) {
772             if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
773                ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
774                IsEqualGUID(&wwo->format.SubFormat, & KSDATAFORMAT_SUBTYPE_PCM))) {
775                 if (wwo->format.Format.wBitsPerSample != 16) {
776                     wwo->format.Format.wBitsPerSample = 16;
777                     format = SND_PCM_FORMAT_S16_LE;
778                 } else {
779                     wwo->format.Format.wBitsPerSample = 8;
780                     format = SND_PCM_FORMAT_U8;
781                 }
782                 /* recalculate block align and bytes per second */
783                 wwo->format.Format.nBlockAlign = (wwo->format.Format.wBitsPerSample * wwo->format.Format.nChannels) / 8;
784                 wwo->format.Format.nAvgBytesPerSec = wwo->format.Format.nSamplesPerSec * wwo->format.Format.nBlockAlign;
785                 WARN("changed bits per sample from %d to %d\n", lpDesc->lpFormat->wBitsPerSample, wwo->format.Format.wBitsPerSample);
786             }
787         }
788         EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), WAVERR_BADFORMAT, "unable to set required format" );
789     }
790
791     rate = wwo->format.Format.nSamplesPerSec;
792     dir=0;
793     err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
794     if (err < 0) {
795         WARN("Rate %d Hz not available for playback: %s\n", wwo->format.Format.nSamplesPerSec, snd_strerror(rate));
796         retcode = WAVERR_BADFORMAT;
797         goto errexit;
798     }
799     if (!ALSA_NearMatch(rate, wwo->format.Format.nSamplesPerSec)) {
800         if (dwFlags & WAVE_DIRECTSOUND) {
801             WARN("changed sample rate from %d Hz to %d Hz\n", wwo->format.Format.nSamplesPerSec, rate);
802             wwo->format.Format.nSamplesPerSec = rate;
803             /* recalculate bytes per second */
804             wwo->format.Format.nAvgBytesPerSec = wwo->format.Format.nSamplesPerSec * wwo->format.Format.nBlockAlign;
805         } else {
806             WARN("Rate doesn't match (requested %d Hz, got %d Hz)\n", wwo->format.Format.nSamplesPerSec, rate);
807             retcode = WAVERR_BADFORMAT;
808             goto errexit;
809         }
810     }
811
812     /* give the new format back to direct sound */
813     if (dwFlags & WAVE_DIRECTSOUND) {
814         lpDesc->lpFormat->wFormatTag = wwo->format.Format.wFormatTag;
815         lpDesc->lpFormat->nChannels = wwo->format.Format.nChannels;
816         lpDesc->lpFormat->nSamplesPerSec = wwo->format.Format.nSamplesPerSec;
817         lpDesc->lpFormat->wBitsPerSample = wwo->format.Format.wBitsPerSample;
818         lpDesc->lpFormat->nBlockAlign = wwo->format.Format.nBlockAlign;
819         lpDesc->lpFormat->nAvgBytesPerSec = wwo->format.Format.nAvgBytesPerSec;
820     }
821
822     TRACE("Got this format: %dx%dx%d %s\n",
823           wwo->format.Format.nSamplesPerSec,
824           wwo->format.Format.wBitsPerSample,
825           wwo->format.Format.nChannels,
826           ALSA_getFormat(wwo->format.Format.wFormatTag));
827
828     dir=0;
829     EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
830     dir=0;
831     EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
832
833     EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
834
835     err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
836     err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
837
838     snd_pcm_sw_params_current(pcm, sw_params);
839     EXIT_ON_ERROR( snd_pcm_sw_params_set_start_threshold(pcm, sw_params, dwFlags & WAVE_DIRECTSOUND ? INT_MAX : 1 ), MMSYSERR_ERROR, "unable to set start threshold");
840     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
841     EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
842     EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
843     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
844     EXIT_ON_ERROR( snd_pcm_sw_params_set_xrun_mode(pcm, sw_params, SND_PCM_XRUN_NONE), MMSYSERR_ERROR, "unable to set xrun mode");
845     EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
846 #undef EXIT_ON_ERROR
847
848     snd_pcm_prepare(pcm);
849
850     if (TRACE_ON(wave))
851         ALSA_TraceParameters(hw_params, sw_params, FALSE);
852
853     /* now, we can save all required data for later use... */
854
855     wwo->dwBufferSize = snd_pcm_frames_to_bytes(pcm, buffer_size);
856     wwo->lpQueuePtr = wwo->lpPlayPtr = wwo->lpLoopPtr = NULL;
857     wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
858     wwo->dwPartialOffset = 0;
859
860     ALSA_InitRingMessage(&wwo->msgRing);
861
862     if (!(dwFlags & WAVE_DIRECTSOUND)) {
863         wwo->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
864         wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
865         if (wwo->hThread)
866             SetThreadPriority(wwo->hThread, THREAD_PRIORITY_TIME_CRITICAL);
867         else
868         {
869             ERR("Thread creation for the wodPlayer failed!\n");
870             CloseHandle(wwo->hStartUpEvent);
871             retcode = MMSYSERR_NOMEM;
872             goto errexit;
873         }
874         WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
875         CloseHandle(wwo->hStartUpEvent);
876     } else {
877         wwo->hThread = INVALID_HANDLE_VALUE;
878         wwo->dwThreadID = 0;
879     }
880     wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
881
882     TRACE("handle=%p\n", pcm);
883     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%u, nSamplesPerSec=%u, nChannels=%u nBlockAlign=%u!\n",
884           wwo->format.Format.wBitsPerSample, wwo->format.Format.nAvgBytesPerSec,
885           wwo->format.Format.nSamplesPerSec, wwo->format.Format.nChannels,
886           wwo->format.Format.nBlockAlign);
887
888     wwo->pcm = pcm;
889     wwo->hctl = hctl;
890     if ( wwo->hw_params )
891         snd_pcm_hw_params_free(wwo->hw_params);
892     wwo->hw_params = hw_params;
893
894     return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
895
896 errexit:
897     if (pcm)
898         snd_pcm_close(pcm);
899
900     if (hctl)
901     {
902         snd_hctl_free(hctl);
903         snd_hctl_close(hctl);
904     }
905
906     if ( hw_params )
907         snd_pcm_hw_params_free(hw_params);
908
909     if (wwo->msgRing.ring_buffer_size > 0)
910         ALSA_DestroyRingMessage(&wwo->msgRing);
911
912     return retcode;
913 }
914
915
916 /**************************************************************************
917  *                              wodClose                        [internal]
918  */
919 static DWORD wodClose(WORD wDevID)
920 {
921     DWORD               ret = MMSYSERR_NOERROR;
922     WINE_WAVEDEV*       wwo;
923
924     TRACE("(%u);\n", wDevID);
925
926     if (wDevID >= ALSA_WodNumDevs) {
927         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
928         return MMSYSERR_BADDEVICEID;
929     }
930
931     if (WOutDev[wDevID].pcm == NULL) {
932         WARN("Requested to close already closed device %d!\n", wDevID);
933         return MMSYSERR_BADDEVICEID;
934     }
935
936     wwo = &WOutDev[wDevID];
937     if (wwo->lpQueuePtr) {
938         WARN("buffers still playing !\n");
939         ret = WAVERR_STILLPLAYING;
940     } else {
941         if (wwo->hThread != INVALID_HANDLE_VALUE) {
942             ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
943         }
944         ALSA_DestroyRingMessage(&wwo->msgRing);
945
946         if (wwo->hw_params)
947             snd_pcm_hw_params_free(wwo->hw_params);
948         wwo->hw_params = NULL;
949
950         if (wwo->pcm)
951             snd_pcm_close(wwo->pcm);
952         wwo->pcm = NULL;
953
954         if (wwo->hctl)
955         {
956             snd_hctl_free(wwo->hctl);
957             snd_hctl_close(wwo->hctl);
958         }
959         wwo->hctl = NULL;
960
961         ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
962     }
963
964     return ret;
965 }
966
967
968 /**************************************************************************
969  *                              wodWrite                        [internal]
970  *
971  */
972 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
973 {
974     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
975
976     if (wDevID >= ALSA_WodNumDevs) {
977         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
978         return MMSYSERR_BADDEVICEID;
979     }
980
981     if (WOutDev[wDevID].pcm == NULL) {
982         WARN("Requested to write to closed device %d!\n", wDevID);
983         return MMSYSERR_BADDEVICEID;
984     }
985
986     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
987         return WAVERR_UNPREPARED;
988
989     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
990         return WAVERR_STILLPLAYING;
991
992     lpWaveHdr->dwFlags &= ~WHDR_DONE;
993     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
994     lpWaveHdr->lpNext = 0;
995
996     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
997
998     return MMSYSERR_NOERROR;
999 }
1000
1001 /**************************************************************************
1002  *                      wodPause                                [internal]
1003  */
1004 static DWORD wodPause(WORD wDevID)
1005 {
1006     TRACE("(%u);!\n", wDevID);
1007
1008     if (wDevID >= ALSA_WodNumDevs) {
1009         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
1010         return MMSYSERR_BADDEVICEID;
1011     }
1012
1013     if (WOutDev[wDevID].pcm == NULL) {
1014         WARN("Requested to pause closed device %d!\n", wDevID);
1015         return MMSYSERR_BADDEVICEID;
1016     }
1017
1018     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1019
1020     return MMSYSERR_NOERROR;
1021 }
1022
1023 /**************************************************************************
1024  *                      wodRestart                              [internal]
1025  */
1026 static DWORD wodRestart(WORD wDevID)
1027 {
1028     TRACE("(%u);\n", wDevID);
1029
1030     if (wDevID >= ALSA_WodNumDevs) {
1031         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
1032         return MMSYSERR_BADDEVICEID;
1033     }
1034
1035     if (WOutDev[wDevID].pcm == NULL) {
1036         WARN("Requested to restart closed device %d!\n", wDevID);
1037         return MMSYSERR_BADDEVICEID;
1038     }
1039
1040     if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1041         ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1042     }
1043
1044     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1045     /* FIXME: Myst crashes with this ... hmm -MM
1046        return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1047     */
1048
1049     return MMSYSERR_NOERROR;
1050 }
1051
1052 /**************************************************************************
1053  *                      wodReset                                [internal]
1054  */
1055 static DWORD wodReset(WORD wDevID)
1056 {
1057     TRACE("(%u);\n", wDevID);
1058
1059     if (wDevID >= ALSA_WodNumDevs) {
1060         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
1061         return MMSYSERR_BADDEVICEID;
1062     }
1063
1064     if (WOutDev[wDevID].pcm == NULL) {
1065         WARN("Requested to reset closed device %d!\n", wDevID);
1066         return MMSYSERR_BADDEVICEID;
1067     }
1068
1069     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1070
1071     return MMSYSERR_NOERROR;
1072 }
1073
1074 /**************************************************************************
1075  *                              wodGetPosition                  [internal]
1076  */
1077 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1078 {
1079     WINE_WAVEDEV*       wwo;
1080
1081     TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
1082
1083     if (wDevID >= ALSA_WodNumDevs) {
1084         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
1085         return MMSYSERR_BADDEVICEID;
1086     }
1087
1088     if (WOutDev[wDevID].pcm == NULL) {
1089         WARN("Requested to get position of closed device %d!\n", wDevID);
1090         return MMSYSERR_BADDEVICEID;
1091     }
1092
1093     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1094
1095     wwo = &WOutDev[wDevID];
1096     ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1097
1098     return ALSA_bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->format);
1099 }
1100
1101 /**************************************************************************
1102  *                              wodBreakLoop                    [internal]
1103  */
1104 static DWORD wodBreakLoop(WORD wDevID)
1105 {
1106     TRACE("(%u);\n", wDevID);
1107
1108     if (wDevID >= ALSA_WodNumDevs) {
1109         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
1110         return MMSYSERR_BADDEVICEID;
1111     }
1112
1113     if (WOutDev[wDevID].pcm == NULL) {
1114         WARN("Requested to breakloop of closed device %d!\n", wDevID);
1115         return MMSYSERR_BADDEVICEID;
1116     }
1117
1118     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
1119     return MMSYSERR_NOERROR;
1120 }
1121
1122 /**************************************************************************
1123  *                              wodGetVolume                    [internal]
1124  */
1125 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1126 {
1127     WORD               wleft, wright;
1128     WINE_WAVEDEV*      wwo;
1129     int                min, max;
1130     int                left, right;
1131     DWORD              rc;
1132
1133     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1134     if (wDevID >= ALSA_WodNumDevs) {
1135         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
1136         return MMSYSERR_BADDEVICEID;
1137     }
1138
1139     if (lpdwVol == NULL)
1140         return MMSYSERR_NOTENABLED;
1141
1142     wwo = &WOutDev[wDevID];
1143
1144     if (lpdwVol == NULL)
1145         return MMSYSERR_NOTENABLED;
1146
1147     rc = ALSA_CheckSetVolume(wwo->hctl, &left, &right, &min, &max, NULL, NULL, NULL);
1148     if (rc == MMSYSERR_NOERROR)
1149     {
1150 #define VOLUME_ALSA_TO_WIN(x) (  ( (((x)-min) * 65535) + (max-min)/2 ) /(max-min))
1151         wleft = VOLUME_ALSA_TO_WIN(left);
1152         wright = VOLUME_ALSA_TO_WIN(right);
1153 #undef VOLUME_ALSA_TO_WIN
1154         TRACE("left=%d,right=%d,converted to windows left %d, right %d\n", left, right, wleft, wright);
1155         *lpdwVol = MAKELONG( wleft, wright );
1156     }
1157     else
1158         TRACE("CheckSetVolume failed; rc %d\n", rc);
1159
1160     return rc;
1161 }
1162
1163 /**************************************************************************
1164  *                              wodSetVolume                    [internal]
1165  */
1166 DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1167 {
1168     WORD               wleft, wright;
1169     WINE_WAVEDEV*      wwo;
1170     int                min, max;
1171     int                left, right;
1172     DWORD              rc;
1173
1174     TRACE("(%u, %08X);\n", wDevID, dwParam);
1175     if (wDevID >= ALSA_WodNumDevs) {
1176         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
1177         return MMSYSERR_BADDEVICEID;
1178     }
1179
1180     wwo = &WOutDev[wDevID];
1181
1182     rc = ALSA_CheckSetVolume(wwo->hctl, NULL, NULL, &min, &max, NULL, NULL, NULL);
1183     if (rc == MMSYSERR_NOERROR)
1184     {
1185         wleft  = LOWORD(dwParam);
1186         wright = HIWORD(dwParam);
1187 #define VOLUME_WIN_TO_ALSA(x) ( (  ( ((x) * (max-min)) + 32767) / 65535) + min )
1188         left = VOLUME_WIN_TO_ALSA(wleft);
1189         right = VOLUME_WIN_TO_ALSA(wright);
1190 #undef VOLUME_WIN_TO_ALSA
1191         rc = ALSA_CheckSetVolume(wwo->hctl, NULL, NULL, NULL, NULL, NULL, &left, &right);
1192         if (rc == MMSYSERR_NOERROR)
1193             TRACE("set volume:  wleft=%d, wright=%d, converted to alsa left %d, right %d\n", wleft, wright, left, right);
1194         else
1195             TRACE("SetVolume failed; rc %d\n", rc);
1196     }
1197
1198     return rc;
1199 }
1200
1201 /**************************************************************************
1202  *                              wodGetNumDevs                   [internal]
1203  */
1204 static  DWORD   wodGetNumDevs(void)
1205 {
1206     return ALSA_WodNumDevs;
1207 }
1208
1209 /**************************************************************************
1210  *                              wodDevInterfaceSize             [internal]
1211  */
1212 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1213 {
1214     TRACE("(%u, %p)\n", wDevID, dwParam1);
1215
1216     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1217                                     NULL, 0 ) * sizeof(WCHAR);
1218     return MMSYSERR_NOERROR;
1219 }
1220
1221 /**************************************************************************
1222  *                              wodDevInterface                 [internal]
1223  */
1224 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1225 {
1226     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1227                                         NULL, 0 ) * sizeof(WCHAR))
1228     {
1229         MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1230                             dwParam1, dwParam2 / sizeof(WCHAR));
1231         return MMSYSERR_NOERROR;
1232     }
1233     return MMSYSERR_INVALPARAM;
1234 }
1235
1236 /**************************************************************************
1237  *                              wodMessage (WINEALSA.@)
1238  */
1239 DWORD WINAPI ALSA_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1240                              DWORD dwParam1, DWORD dwParam2)
1241 {
1242     TRACE("(%u, %s, %08X, %08X, %08X);\n",
1243           wDevID, ALSA_getMessage(wMsg), dwUser, dwParam1, dwParam2);
1244
1245     switch (wMsg) {
1246     case DRVM_INIT:
1247     case DRVM_EXIT:
1248     case DRVM_ENABLE:
1249     case DRVM_DISABLE:
1250         /* FIXME: Pretend this is supported */
1251         return 0;
1252     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1253     case WODM_CLOSE:            return wodClose         (wDevID);
1254     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSW)dwParam1,      dwParam2);
1255     case WODM_GETNUMDEVS:       return wodGetNumDevs    ();
1256     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1257     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1258     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1259     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1260     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1261     case WODM_PAUSE:            return wodPause         (wDevID);
1262     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
1263     case WODM_BREAKLOOP:        return wodBreakLoop     (wDevID);
1264     case WODM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
1265     case WODM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
1266     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
1267     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
1268     case WODM_RESTART:          return wodRestart       (wDevID);
1269     case WODM_RESET:            return wodReset         (wDevID);
1270     case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
1271     case DRV_QUERYDEVICEINTERFACE:     return wodDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
1272     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate      (wDevID, (PIDSDRIVER*)dwParam1);
1273     case DRV_QUERYDSOUNDDESC:   return wodDsDesc        (wDevID, (PDSDRIVERDESC)dwParam1);
1274
1275     default:
1276         FIXME("unknown message %d!\n", wMsg);
1277     }
1278     return MMSYSERR_NOTSUPPORTED;
1279 }
1280
1281 #else /* HAVE_ALSA */
1282
1283 /**************************************************************************
1284  *                              wodMessage (WINEALSA.@)
1285  */
1286 DWORD WINAPI ALSA_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
1287                              DWORD dwParam1, DWORD dwParam2)
1288 {
1289     FIXME("(%u, %04X, %08X, %08X, %08X):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
1290     return MMSYSERR_NOTENABLED;
1291 }
1292
1293 #endif /* HAVE_ALSA */