winealsa: Remove dead code.
[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     for (;;)
280     {
281         lpWaveHdr = wwo->lpQueuePtr;
282         if (!lpWaveHdr) {TRACE("Empty queue\n"); break;}
283         if (!force)
284         {
285             if (lpWaveHdr == wwo->lpPlayPtr) {TRACE("play %p\n", lpWaveHdr); break;}
286             if (lpWaveHdr == wwo->lpLoopPtr) {TRACE("loop %p\n", lpWaveHdr); break;}
287             if (lpWaveHdr->reserved > wwo->dwPlayedTotal) {TRACE("still playing %p (%u/%u)\n", lpWaveHdr, lpWaveHdr->reserved, wwo->dwPlayedTotal);break;}
288         }
289         wwo->lpQueuePtr = lpWaveHdr->lpNext;
290
291         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
292         lpWaveHdr->dwFlags |= WHDR_DONE;
293
294         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
295     }
296     return  (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
297         wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
298 }
299
300
301 /**************************************************************************
302  *                              wodPlayer_Reset                 [internal]
303  *
304  * wodPlayer helper. Resets current output stream.
305  */
306 static  void    wodPlayer_Reset(WINE_WAVEDEV* wwo, BOOL reset)
307 {
308     int                         err;
309     TRACE("(%p)\n", wwo);
310
311     /* flush all possible output */
312     snd_pcm_drain(wwo->pcm);
313
314     wodUpdatePlayedTotal(wwo, NULL);
315     /* updates current notify list */
316     wodPlayer_NotifyCompletions(wwo, FALSE);
317
318     if ( (err = snd_pcm_drop(wwo->pcm)) < 0) {
319         FIXME("flush: %s\n", snd_strerror(err));
320         wwo->hThread = 0;
321         wwo->state = WINE_WS_STOPPED;
322         ExitThread(-1);
323     }
324     if ( (err = snd_pcm_prepare(wwo->pcm)) < 0 )
325         ERR("pcm prepare failed: %s\n", snd_strerror(err));
326
327     if (reset) {
328         enum win_wm_message     msg;
329         DWORD                   param;
330         HANDLE                  ev;
331
332         /* remove any buffer */
333         wodPlayer_NotifyCompletions(wwo, TRUE);
334
335         wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
336         wwo->state = WINE_WS_STOPPED;
337         wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
338         /* Clear partial wavehdr */
339         wwo->dwPartialOffset = 0;
340
341         /* remove any existing message in the ring */
342         EnterCriticalSection(&wwo->msgRing.msg_crst);
343         /* return all pending headers in queue */
344         while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
345         {
346             if (msg != WINE_WM_HEADER)
347             {
348                 FIXME("shouldn't have headers left\n");
349                 SetEvent(ev);
350                 continue;
351             }
352             ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
353             ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
354
355                 wodNotifyClient(wwo, WOM_DONE, param, 0);
356         }
357         ALSA_ResetRingMessage(&wwo->msgRing);
358         LeaveCriticalSection(&wwo->msgRing.msg_crst);
359     } else {
360         if (wwo->lpLoopPtr) {
361             /* complicated case, not handled yet (could imply modifying the loop counter */
362             FIXME("Pausing while in loop isn't correctly handled yet, except strange results\n");
363             wwo->lpPlayPtr = wwo->lpLoopPtr;
364             wwo->dwPartialOffset = 0;
365             wwo->dwWrittenTotal = wwo->dwPlayedTotal; /* this is wrong !!! */
366         } else {
367             LPWAVEHDR   ptr;
368             DWORD       sz = wwo->dwPartialOffset;
369
370             /* reset all the data as if we had written only up to lpPlayedTotal bytes */
371             /* compute the max size playable from lpQueuePtr */
372             for (ptr = wwo->lpQueuePtr; ptr != wwo->lpPlayPtr; ptr = ptr->lpNext) {
373                 sz += ptr->dwBufferLength;
374             }
375             /* because the reset lpPlayPtr will be lpQueuePtr */
376             if (wwo->dwWrittenTotal > wwo->dwPlayedTotal + sz) ERR("grin\n");
377             wwo->dwPartialOffset = sz - (wwo->dwWrittenTotal - wwo->dwPlayedTotal);
378             wwo->dwWrittenTotal = wwo->dwPlayedTotal;
379             wwo->lpPlayPtr = wwo->lpQueuePtr;
380         }
381         wwo->state = WINE_WS_PAUSED;
382     }
383 }
384
385 /**************************************************************************
386  *                    wodPlayer_ProcessMessages                 [internal]
387  */
388 static void wodPlayer_ProcessMessages(WINE_WAVEDEV* wwo)
389 {
390     LPWAVEHDR           lpWaveHdr;
391     enum win_wm_message msg;
392     DWORD               param;
393     HANDLE              ev;
394     int                 err;
395
396     while (ALSA_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
397      TRACE("Received %s %x\n", ALSA_getCmdString(msg), param);
398
399         switch (msg) {
400         case WINE_WM_PAUSING:
401             if ( snd_pcm_state(wwo->pcm) == SND_PCM_STATE_RUNNING )
402              {
403                 if ( snd_pcm_hw_params_can_pause(wwo->hw_params) )
404                 {
405                     err = snd_pcm_pause(wwo->pcm, 1);
406                     if ( err < 0 )
407                         ERR("pcm_pause failed: %s\n", snd_strerror(err));
408                     wwo->state = WINE_WS_PAUSED;
409                 }
410                 else
411                 {
412                     wodPlayer_Reset(wwo,FALSE);
413                 }
414              }
415             SetEvent(ev);
416             break;
417         case WINE_WM_RESTARTING:
418             if (wwo->state == WINE_WS_PAUSED)
419             {
420                 if ( snd_pcm_state(wwo->pcm) == SND_PCM_STATE_PAUSED )
421                  {
422                     err = snd_pcm_pause(wwo->pcm, 0);
423                     if ( err < 0 )
424                         ERR("pcm_pause failed: %s\n", snd_strerror(err));
425                  }
426                 wwo->state = WINE_WS_PLAYING;
427             }
428             SetEvent(ev);
429             break;
430         case WINE_WM_HEADER:
431             lpWaveHdr = (LPWAVEHDR)param;
432
433             /* insert buffer at the end of queue */
434             {
435                 LPWAVEHDR*      wh;
436                 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
437                 *wh = lpWaveHdr;
438             }
439             if (!wwo->lpPlayPtr)
440                 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
441             if (wwo->state == WINE_WS_STOPPED)
442                 wwo->state = WINE_WS_PLAYING;
443             break;
444         case WINE_WM_RESETTING:
445             wodPlayer_Reset(wwo,TRUE);
446             SetEvent(ev);
447             break;
448         case WINE_WM_UPDATE:
449             wodUpdatePlayedTotal(wwo, NULL);
450             SetEvent(ev);
451             break;
452         case WINE_WM_BREAKLOOP:
453             if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
454                 /* ensure exit at end of current loop */
455                 wwo->dwLoops = 1;
456             }
457             SetEvent(ev);
458             break;
459         case WINE_WM_CLOSING:
460             /* sanity check: this should not happen since the device must have been reset before */
461             if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
462             wwo->hThread = 0;
463             wwo->state = WINE_WS_CLOSED;
464             SetEvent(ev);
465             ExitThread(0);
466             /* shouldn't go here */
467         default:
468             FIXME("unknown message %d\n", msg);
469             break;
470         }
471     }
472 }
473
474 /**************************************************************************
475  *                           wodPlayer_FeedDSP                  [internal]
476  * Feed as much sound data as we can into the DSP and return the number of
477  * milliseconds before it will be necessary to feed the DSP again.
478  */
479 static DWORD wodPlayer_FeedDSP(WINE_WAVEDEV* wwo)
480 {
481     DWORD               availInQ;
482
483     wodUpdatePlayedTotal(wwo, NULL);
484     availInQ = snd_pcm_avail_update(wwo->pcm);
485
486     /* no more room... no need to try to feed */
487     if (availInQ > 0) {
488         /* Feed from partial wavehdr */
489         if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0) {
490             wodPlayer_WriteMaxFrags(wwo, &availInQ);
491         }
492
493         /* Feed wavehdrs until we run out of wavehdrs or DSP space */
494         if (wwo->dwPartialOffset == 0 && wwo->lpPlayPtr) {
495             do {
496                 TRACE("Setting time to elapse for %p to %u\n",
497                       wwo->lpPlayPtr, wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength);
498                 /* note the value that dwPlayedTotal will return when this wave finishes playing */
499                 wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
500             } while (wodPlayer_WriteMaxFrags(wwo, &availInQ) && wwo->lpPlayPtr && availInQ > 0);
501         }
502     }
503
504     return wodPlayer_DSPWait(wwo);
505 }
506
507 /**************************************************************************
508  *                              wodPlayer                       [internal]
509  */
510 static  DWORD   CALLBACK        wodPlayer(LPVOID pmt)
511 {
512     WORD          uDevID = (DWORD)pmt;
513     WINE_WAVEDEV* wwo = (WINE_WAVEDEV*)&WOutDev[uDevID];
514     DWORD         dwNextFeedTime = INFINITE;   /* Time before DSP needs feeding */
515     DWORD         dwNextNotifyTime = INFINITE; /* Time before next wave completion */
516     DWORD         dwSleepTime;
517
518     wwo->state = WINE_WS_STOPPED;
519     SetEvent(wwo->hStartUpEvent);
520
521     for (;;) {
522         /** Wait for the shortest time before an action is required.  If there
523          *  are no pending actions, wait forever for a command.
524          */
525         dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
526         TRACE("waiting %ums (%u,%u)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
527         ALSA_WaitRingMessage(&wwo->msgRing, dwSleepTime);
528         wodPlayer_ProcessMessages(wwo);
529         if (wwo->state == WINE_WS_PLAYING) {
530             dwNextFeedTime = wodPlayer_FeedDSP(wwo);
531             dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
532             if (dwNextFeedTime == INFINITE) {
533                 /* FeedDSP ran out of data, but before giving up, */
534                 /* check that a notification didn't give us more */
535                 wodPlayer_ProcessMessages(wwo);
536                 if (wwo->lpPlayPtr) {
537                     TRACE("recovering\n");
538                     dwNextFeedTime = wodPlayer_FeedDSP(wwo);
539                 }
540             }
541         } else {
542             dwNextFeedTime = dwNextNotifyTime = INFINITE;
543         }
544     }
545 }
546
547 /**************************************************************************
548  *                      wodGetDevCaps                           [internal]
549  */
550 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
551 {
552     TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
553
554     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
555
556     if (wDevID >= ALSA_WodNumDevs) {
557         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
558         return MMSYSERR_BADDEVICEID;
559     }
560
561     memcpy(lpCaps, &WOutDev[wDevID].outcaps, min(dwSize, sizeof(*lpCaps)));
562     return MMSYSERR_NOERROR;
563 }
564
565 /**************************************************************************
566  *                              wodOpen                         [internal]
567  */
568 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
569 {
570     WINE_WAVEDEV*               wwo;
571     snd_pcm_t *                 pcm = NULL;
572     snd_hctl_t *                hctl = NULL;
573     snd_pcm_hw_params_t *       hw_params = NULL;
574     snd_pcm_sw_params_t *       sw_params;
575     snd_pcm_access_t            access;
576     snd_pcm_format_t            format = -1;
577     unsigned int                rate;
578     unsigned int                buffer_time = 500000;
579     unsigned int                period_time = 10000;
580     snd_pcm_uframes_t           buffer_size;
581     snd_pcm_uframes_t           period_size;
582     int                         flags;
583     int                         err=0;
584     int                         dir=0;
585     DWORD                       retcode = 0;
586
587     snd_pcm_sw_params_alloca(&sw_params);
588
589     TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
590     if (lpDesc == NULL) {
591         WARN("Invalid Parameter !\n");
592         return MMSYSERR_INVALPARAM;
593     }
594     if (wDevID >= ALSA_WodNumDevs) {
595         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
596         return MMSYSERR_BADDEVICEID;
597     }
598
599     /* only PCM format is supported so far... */
600     if (!ALSA_supportedFormat(lpDesc->lpFormat)) {
601         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
602              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
603              lpDesc->lpFormat->nSamplesPerSec);
604         return WAVERR_BADFORMAT;
605     }
606
607     if (dwFlags & WAVE_FORMAT_QUERY) {
608         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
609              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
610              lpDesc->lpFormat->nSamplesPerSec);
611         return MMSYSERR_NOERROR;
612     }
613
614     wwo = &WOutDev[wDevID];
615
616     if (wwo->pcm != NULL) {
617         WARN("%d already allocated\n", wDevID);
618         return MMSYSERR_ALLOCATED;
619     }
620
621     if ((dwFlags & WAVE_DIRECTSOUND) && !(wwo->outcaps.dwSupport & WAVECAPS_DIRECTSOUND))
622         /* not supported, ignore it */
623         dwFlags &= ~WAVE_DIRECTSOUND;
624
625     flags = SND_PCM_NONBLOCK;
626
627     if ( (err = snd_pcm_open(&pcm, wwo->pcmname, SND_PCM_STREAM_PLAYBACK, flags)) < 0)
628     {
629         ERR("Error open: %s\n", snd_strerror(err));
630         return MMSYSERR_NOTENABLED;
631     }
632
633     if (wwo->ctlname)
634     {
635         err = snd_hctl_open(&hctl, wwo->ctlname, 0);
636         if (err >= 0)
637         {
638             snd_hctl_load(hctl);
639         }
640         else
641         {
642             WARN("Could not open hctl for [%s]: %s\n", wwo->ctlname, snd_strerror(err));
643             hctl = NULL;
644         }
645     }
646
647     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
648
649     memcpy(&wwo->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
650     ALSA_copyFormat(lpDesc->lpFormat, &wwo->format);
651
652     TRACE("Requested this format: %dx%dx%d %s\n",
653           wwo->format.Format.nSamplesPerSec,
654           wwo->format.Format.wBitsPerSample,
655           wwo->format.Format.nChannels,
656           ALSA_getFormat(wwo->format.Format.wFormatTag));
657
658     if (wwo->format.Format.wBitsPerSample == 0) {
659         WARN("Resetting zeroed wBitsPerSample\n");
660         wwo->format.Format.wBitsPerSample = 8 *
661             (wwo->format.Format.nAvgBytesPerSec /
662              wwo->format.Format.nSamplesPerSec) /
663             wwo->format.Format.nChannels;
664     }
665
666 #define EXIT_ON_ERROR(f,e,txt) do \
667 { \
668     int err; \
669     if ( (err = (f) ) < 0) \
670     { \
671         WARN(txt ": %s\n", snd_strerror(err)); \
672         retcode=e; \
673         goto errexit; \
674     } \
675 } while(0)
676
677     snd_pcm_hw_params_malloc(&hw_params);
678     if (! hw_params)
679     {
680         retcode = MMSYSERR_NOMEM;
681         goto errexit;
682     }
683     snd_pcm_hw_params_any(pcm, hw_params);
684
685     access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
686     if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
687         WARN("mmap not available. switching to standard write.\n");
688         access = SND_PCM_ACCESS_RW_INTERLEAVED;
689         EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
690         wwo->write = snd_pcm_writei;
691     }
692     else
693         wwo->write = snd_pcm_mmap_writei;
694
695     if ((err = snd_pcm_hw_params_set_channels(pcm, hw_params, wwo->format.Format.nChannels)) < 0) {
696         WARN("unable to set required channels: %d\n", wwo->format.Format.nChannels);
697         if (dwFlags & WAVE_DIRECTSOUND) {
698             if (wwo->format.Format.nChannels > 2)
699                 wwo->format.Format.nChannels = 2;
700             else if (wwo->format.Format.nChannels == 2)
701                 wwo->format.Format.nChannels = 1;
702             else if (wwo->format.Format.nChannels == 1)
703                 wwo->format.Format.nChannels = 2;
704             /* recalculate block align and bytes per second */
705             wwo->format.Format.nBlockAlign = (wwo->format.Format.wBitsPerSample * wwo->format.Format.nChannels) / 8;
706             wwo->format.Format.nAvgBytesPerSec = wwo->format.Format.nSamplesPerSec * wwo->format.Format.nBlockAlign;
707             WARN("changed number of channels from %d to %d\n", lpDesc->lpFormat->nChannels, wwo->format.Format.nChannels);
708         }
709         EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwo->format.Format.nChannels ), WAVERR_BADFORMAT, "unable to set required channels" );
710     }
711
712     if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
713         ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
714         IsEqualGUID(&wwo->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
715         format = (wwo->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
716                  (wwo->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
717                  (wwo->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
718                  (wwo->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
719     } else if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
720         IsEqualGUID(&wwo->format.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)){
721         format = (wwo->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_FLOAT_LE : -1;
722     } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
723         FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
724         retcode = WAVERR_BADFORMAT;
725         goto errexit;
726     } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
727         FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
728         retcode = WAVERR_BADFORMAT;
729         goto errexit;
730     } else if (wwo->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
731         FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
732         retcode = WAVERR_BADFORMAT;
733         goto errexit;
734     } else {
735         ERR("invalid format: %0x04x\n", wwo->format.Format.wFormatTag);
736         retcode = WAVERR_BADFORMAT;
737         goto errexit;
738     }
739
740     if ((err = snd_pcm_hw_params_set_format(pcm, hw_params, format)) < 0) {
741         WARN("unable to set required format: %s\n", snd_pcm_format_name(format));
742         if (dwFlags & WAVE_DIRECTSOUND) {
743             if ((wwo->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
744                ((wwo->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
745                IsEqualGUID(&wwo->format.SubFormat, & KSDATAFORMAT_SUBTYPE_PCM))) {
746                 if (wwo->format.Format.wBitsPerSample != 16) {
747                     wwo->format.Format.wBitsPerSample = 16;
748                     format = SND_PCM_FORMAT_S16_LE;
749                 } else {
750                     wwo->format.Format.wBitsPerSample = 8;
751                     format = SND_PCM_FORMAT_U8;
752                 }
753                 /* recalculate block align and bytes per second */
754                 wwo->format.Format.nBlockAlign = (wwo->format.Format.wBitsPerSample * wwo->format.Format.nChannels) / 8;
755                 wwo->format.Format.nAvgBytesPerSec = wwo->format.Format.nSamplesPerSec * wwo->format.Format.nBlockAlign;
756                 WARN("changed bits per sample from %d to %d\n", lpDesc->lpFormat->wBitsPerSample, wwo->format.Format.wBitsPerSample);
757             }
758         }
759         EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), WAVERR_BADFORMAT, "unable to set required format" );
760     }
761
762     rate = wwo->format.Format.nSamplesPerSec;
763     dir=0;
764     err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
765     if (err < 0) {
766         WARN("Rate %d Hz not available for playback: %s\n", wwo->format.Format.nSamplesPerSec, snd_strerror(rate));
767         retcode = WAVERR_BADFORMAT;
768         goto errexit;
769     }
770     if (!ALSA_NearMatch(rate, wwo->format.Format.nSamplesPerSec)) {
771         if (dwFlags & WAVE_DIRECTSOUND) {
772             WARN("changed sample rate from %d Hz to %d Hz\n", wwo->format.Format.nSamplesPerSec, rate);
773             wwo->format.Format.nSamplesPerSec = rate;
774             /* recalculate bytes per second */
775             wwo->format.Format.nAvgBytesPerSec = wwo->format.Format.nSamplesPerSec * wwo->format.Format.nBlockAlign;
776         } else {
777             WARN("Rate doesn't match (requested %d Hz, got %d Hz)\n", wwo->format.Format.nSamplesPerSec, rate);
778             retcode = WAVERR_BADFORMAT;
779             goto errexit;
780         }
781     }
782
783     /* give the new format back to direct sound */
784     if (dwFlags & WAVE_DIRECTSOUND) {
785         lpDesc->lpFormat->wFormatTag = wwo->format.Format.wFormatTag;
786         lpDesc->lpFormat->nChannels = wwo->format.Format.nChannels;
787         lpDesc->lpFormat->nSamplesPerSec = wwo->format.Format.nSamplesPerSec;
788         lpDesc->lpFormat->wBitsPerSample = wwo->format.Format.wBitsPerSample;
789         lpDesc->lpFormat->nBlockAlign = wwo->format.Format.nBlockAlign;
790         lpDesc->lpFormat->nAvgBytesPerSec = wwo->format.Format.nAvgBytesPerSec;
791     }
792
793     TRACE("Got this format: %dx%dx%d %s\n",
794           wwo->format.Format.nSamplesPerSec,
795           wwo->format.Format.wBitsPerSample,
796           wwo->format.Format.nChannels,
797           ALSA_getFormat(wwo->format.Format.wFormatTag));
798
799     dir=0;
800     EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
801     dir=0;
802     EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
803
804     EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
805
806     err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
807     err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
808
809     snd_pcm_sw_params_current(pcm, sw_params);
810     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");
811     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
812     EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
813     EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
814     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
815     EXIT_ON_ERROR( snd_pcm_sw_params_set_xrun_mode(pcm, sw_params, SND_PCM_XRUN_NONE), MMSYSERR_ERROR, "unable to set xrun mode");
816     EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
817 #undef EXIT_ON_ERROR
818
819     snd_pcm_prepare(pcm);
820
821     if (TRACE_ON(wave))
822         ALSA_TraceParameters(hw_params, sw_params, FALSE);
823
824     /* now, we can save all required data for later use... */
825
826     wwo->dwBufferSize = snd_pcm_frames_to_bytes(pcm, buffer_size);
827     wwo->lpQueuePtr = wwo->lpPlayPtr = wwo->lpLoopPtr = NULL;
828     wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
829     wwo->dwPartialOffset = 0;
830
831     ALSA_InitRingMessage(&wwo->msgRing);
832
833     if (!(dwFlags & WAVE_DIRECTSOUND)) {
834         wwo->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
835         wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
836         if (wwo->hThread)
837             SetThreadPriority(wwo->hThread, THREAD_PRIORITY_TIME_CRITICAL);
838         else
839         {
840             ERR("Thread creation for the wodPlayer failed!\n");
841             CloseHandle(wwo->hStartUpEvent);
842             retcode = MMSYSERR_NOMEM;
843             goto errexit;
844         }
845         WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
846         CloseHandle(wwo->hStartUpEvent);
847     } else {
848         wwo->hThread = INVALID_HANDLE_VALUE;
849         wwo->dwThreadID = 0;
850     }
851     wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
852
853     TRACE("handle=%p\n", pcm);
854     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%u, nSamplesPerSec=%u, nChannels=%u nBlockAlign=%u!\n",
855           wwo->format.Format.wBitsPerSample, wwo->format.Format.nAvgBytesPerSec,
856           wwo->format.Format.nSamplesPerSec, wwo->format.Format.nChannels,
857           wwo->format.Format.nBlockAlign);
858
859     wwo->pcm = pcm;
860     wwo->hctl = hctl;
861     if ( wwo->hw_params )
862         snd_pcm_hw_params_free(wwo->hw_params);
863     wwo->hw_params = hw_params;
864
865     return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
866
867 errexit:
868     if (pcm)
869         snd_pcm_close(pcm);
870
871     if (hctl)
872     {
873         snd_hctl_free(hctl);
874         snd_hctl_close(hctl);
875     }
876
877     if ( hw_params )
878         snd_pcm_hw_params_free(hw_params);
879
880     if (wwo->msgRing.ring_buffer_size > 0)
881         ALSA_DestroyRingMessage(&wwo->msgRing);
882
883     return retcode;
884 }
885
886
887 /**************************************************************************
888  *                              wodClose                        [internal]
889  */
890 static DWORD wodClose(WORD wDevID)
891 {
892     DWORD               ret = MMSYSERR_NOERROR;
893     WINE_WAVEDEV*       wwo;
894
895     TRACE("(%u);\n", wDevID);
896
897     if (wDevID >= ALSA_WodNumDevs) {
898         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
899         return MMSYSERR_BADDEVICEID;
900     }
901
902     if (WOutDev[wDevID].pcm == NULL) {
903         WARN("Requested to close already closed device %d!\n", wDevID);
904         return MMSYSERR_BADDEVICEID;
905     }
906
907     wwo = &WOutDev[wDevID];
908     if (wwo->lpQueuePtr) {
909         WARN("buffers still playing !\n");
910         ret = WAVERR_STILLPLAYING;
911     } else {
912         if (wwo->hThread != INVALID_HANDLE_VALUE) {
913             ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
914         }
915         ALSA_DestroyRingMessage(&wwo->msgRing);
916
917         if (wwo->hw_params)
918             snd_pcm_hw_params_free(wwo->hw_params);
919         wwo->hw_params = NULL;
920
921         if (wwo->pcm)
922             snd_pcm_close(wwo->pcm);
923         wwo->pcm = NULL;
924
925         if (wwo->hctl)
926         {
927             snd_hctl_free(wwo->hctl);
928             snd_hctl_close(wwo->hctl);
929         }
930         wwo->hctl = NULL;
931
932         ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
933     }
934
935     return ret;
936 }
937
938
939 /**************************************************************************
940  *                              wodWrite                        [internal]
941  *
942  */
943 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
944 {
945     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
946
947     if (wDevID >= ALSA_WodNumDevs) {
948         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
949         return MMSYSERR_BADDEVICEID;
950     }
951
952     if (WOutDev[wDevID].pcm == NULL) {
953         WARN("Requested to write to closed device %d!\n", wDevID);
954         return MMSYSERR_BADDEVICEID;
955     }
956
957     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
958         return WAVERR_UNPREPARED;
959
960     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
961         return WAVERR_STILLPLAYING;
962
963     lpWaveHdr->dwFlags &= ~WHDR_DONE;
964     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
965     lpWaveHdr->lpNext = 0;
966
967     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
968
969     return MMSYSERR_NOERROR;
970 }
971
972 /**************************************************************************
973  *                      wodPause                                [internal]
974  */
975 static DWORD wodPause(WORD wDevID)
976 {
977     TRACE("(%u);!\n", wDevID);
978
979     if (wDevID >= ALSA_WodNumDevs) {
980         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
981         return MMSYSERR_BADDEVICEID;
982     }
983
984     if (WOutDev[wDevID].pcm == NULL) {
985         WARN("Requested to pause closed device %d!\n", wDevID);
986         return MMSYSERR_BADDEVICEID;
987     }
988
989     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
990
991     return MMSYSERR_NOERROR;
992 }
993
994 /**************************************************************************
995  *                      wodRestart                              [internal]
996  */
997 static DWORD wodRestart(WORD wDevID)
998 {
999     TRACE("(%u);\n", wDevID);
1000
1001     if (wDevID >= ALSA_WodNumDevs) {
1002         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
1003         return MMSYSERR_BADDEVICEID;
1004     }
1005
1006     if (WOutDev[wDevID].pcm == NULL) {
1007         WARN("Requested to restart closed device %d!\n", wDevID);
1008         return MMSYSERR_BADDEVICEID;
1009     }
1010
1011     if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1012         ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1013     }
1014
1015     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1016     /* FIXME: Myst crashes with this ... hmm -MM
1017        return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1018     */
1019
1020     return MMSYSERR_NOERROR;
1021 }
1022
1023 /**************************************************************************
1024  *                      wodReset                                [internal]
1025  */
1026 static DWORD wodReset(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 reset closed device %d!\n", wDevID);
1037         return MMSYSERR_BADDEVICEID;
1038     }
1039
1040     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1041
1042     return MMSYSERR_NOERROR;
1043 }
1044
1045 /**************************************************************************
1046  *                              wodGetPosition                  [internal]
1047  */
1048 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1049 {
1050     WINE_WAVEDEV*       wwo;
1051
1052     TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
1053
1054     if (wDevID >= ALSA_WodNumDevs) {
1055         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
1056         return MMSYSERR_BADDEVICEID;
1057     }
1058
1059     if (WOutDev[wDevID].pcm == NULL) {
1060         WARN("Requested to get position of closed device %d!\n", wDevID);
1061         return MMSYSERR_BADDEVICEID;
1062     }
1063
1064     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1065
1066     wwo = &WOutDev[wDevID];
1067     ALSA_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1068
1069     return ALSA_bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->format);
1070 }
1071
1072 /**************************************************************************
1073  *                              wodBreakLoop                    [internal]
1074  */
1075 static DWORD wodBreakLoop(WORD wDevID)
1076 {
1077     TRACE("(%u);\n", wDevID);
1078
1079     if (wDevID >= ALSA_WodNumDevs) {
1080         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
1081         return MMSYSERR_BADDEVICEID;
1082     }
1083
1084     if (WOutDev[wDevID].pcm == NULL) {
1085         WARN("Requested to breakloop of closed device %d!\n", wDevID);
1086         return MMSYSERR_BADDEVICEID;
1087     }
1088
1089     ALSA_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
1090     return MMSYSERR_NOERROR;
1091 }
1092
1093 /**************************************************************************
1094  *                              wodGetVolume                    [internal]
1095  */
1096 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1097 {
1098     WORD               wleft, wright;
1099     WINE_WAVEDEV*      wwo;
1100     int                min, max;
1101     int                left, right;
1102     DWORD              rc;
1103
1104     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1105     if (wDevID >= ALSA_WodNumDevs) {
1106         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
1107         return MMSYSERR_BADDEVICEID;
1108     }
1109
1110     if (lpdwVol == NULL)
1111         return MMSYSERR_NOTENABLED;
1112
1113     wwo = &WOutDev[wDevID];
1114
1115     if (lpdwVol == NULL)
1116         return MMSYSERR_NOTENABLED;
1117
1118     rc = ALSA_CheckSetVolume(wwo->hctl, &left, &right, &min, &max, NULL, NULL, NULL);
1119     if (rc == MMSYSERR_NOERROR)
1120     {
1121 #define VOLUME_ALSA_TO_WIN(x) (  ( (((x)-min) * 65535) + (max-min)/2 ) /(max-min))
1122         wleft = VOLUME_ALSA_TO_WIN(left);
1123         wright = VOLUME_ALSA_TO_WIN(right);
1124 #undef VOLUME_ALSA_TO_WIN
1125         TRACE("left=%d,right=%d,converted to windows left %d, right %d\n", left, right, wleft, wright);
1126         *lpdwVol = MAKELONG( wleft, wright );
1127     }
1128     else
1129         TRACE("CheckSetVolume failed; rc %d\n", rc);
1130
1131     return rc;
1132 }
1133
1134 /**************************************************************************
1135  *                              wodSetVolume                    [internal]
1136  */
1137 DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1138 {
1139     WORD               wleft, wright;
1140     WINE_WAVEDEV*      wwo;
1141     int                min, max;
1142     int                left, right;
1143     DWORD              rc;
1144
1145     TRACE("(%u, %08X);\n", wDevID, dwParam);
1146     if (wDevID >= ALSA_WodNumDevs) {
1147         TRACE("Asked for device %d, but only %d known!\n", wDevID, ALSA_WodNumDevs);
1148         return MMSYSERR_BADDEVICEID;
1149     }
1150
1151     wwo = &WOutDev[wDevID];
1152
1153     rc = ALSA_CheckSetVolume(wwo->hctl, NULL, NULL, &min, &max, NULL, NULL, NULL);
1154     if (rc == MMSYSERR_NOERROR)
1155     {
1156         wleft  = LOWORD(dwParam);
1157         wright = HIWORD(dwParam);
1158 #define VOLUME_WIN_TO_ALSA(x) ( (  ( ((x) * (max-min)) + 32767) / 65535) + min )
1159         left = VOLUME_WIN_TO_ALSA(wleft);
1160         right = VOLUME_WIN_TO_ALSA(wright);
1161 #undef VOLUME_WIN_TO_ALSA
1162         rc = ALSA_CheckSetVolume(wwo->hctl, NULL, NULL, NULL, NULL, NULL, &left, &right);
1163         if (rc == MMSYSERR_NOERROR)
1164             TRACE("set volume:  wleft=%d, wright=%d, converted to alsa left %d, right %d\n", wleft, wright, left, right);
1165         else
1166             TRACE("SetVolume failed; rc %d\n", rc);
1167     }
1168
1169     return rc;
1170 }
1171
1172 /**************************************************************************
1173  *                              wodGetNumDevs                   [internal]
1174  */
1175 static  DWORD   wodGetNumDevs(void)
1176 {
1177     return ALSA_WodNumDevs;
1178 }
1179
1180 /**************************************************************************
1181  *                              wodDevInterfaceSize             [internal]
1182  */
1183 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1184 {
1185     TRACE("(%u, %p)\n", wDevID, dwParam1);
1186
1187     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1188                                     NULL, 0 ) * sizeof(WCHAR);
1189     return MMSYSERR_NOERROR;
1190 }
1191
1192 /**************************************************************************
1193  *                              wodDevInterface                 [internal]
1194  */
1195 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1196 {
1197     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1198                                         NULL, 0 ) * sizeof(WCHAR))
1199     {
1200         MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1201                             dwParam1, dwParam2 / sizeof(WCHAR));
1202         return MMSYSERR_NOERROR;
1203     }
1204     return MMSYSERR_INVALPARAM;
1205 }
1206
1207 /**************************************************************************
1208  *                              wodMessage (WINEALSA.@)
1209  */
1210 DWORD WINAPI ALSA_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1211                              DWORD dwParam1, DWORD dwParam2)
1212 {
1213     TRACE("(%u, %s, %08X, %08X, %08X);\n",
1214           wDevID, ALSA_getMessage(wMsg), dwUser, dwParam1, dwParam2);
1215
1216     switch (wMsg) {
1217     case DRVM_INIT:
1218     case DRVM_EXIT:
1219     case DRVM_ENABLE:
1220     case DRVM_DISABLE:
1221         /* FIXME: Pretend this is supported */
1222         return 0;
1223     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1224     case WODM_CLOSE:            return wodClose         (wDevID);
1225     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSW)dwParam1,      dwParam2);
1226     case WODM_GETNUMDEVS:       return wodGetNumDevs    ();
1227     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1228     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1229     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1230     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1231     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1232     case WODM_PAUSE:            return wodPause         (wDevID);
1233     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
1234     case WODM_BREAKLOOP:        return wodBreakLoop     (wDevID);
1235     case WODM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
1236     case WODM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
1237     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
1238     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
1239     case WODM_RESTART:          return wodRestart       (wDevID);
1240     case WODM_RESET:            return wodReset         (wDevID);
1241     case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
1242     case DRV_QUERYDEVICEINTERFACE:     return wodDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
1243     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate      (wDevID, (PIDSDRIVER*)dwParam1);
1244     case DRV_QUERYDSOUNDDESC:   return wodDsDesc        (wDevID, (PDSDRIVERDESC)dwParam1);
1245
1246     default:
1247         FIXME("unknown message %d!\n", wMsg);
1248     }
1249     return MMSYSERR_NOTSUPPORTED;
1250 }
1251
1252 #else /* HAVE_ALSA */
1253
1254 /**************************************************************************
1255  *                              wodMessage (WINEALSA.@)
1256  */
1257 DWORD WINAPI ALSA_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
1258                              DWORD dwParam1, DWORD dwParam2)
1259 {
1260     FIXME("(%u, %04X, %08X, %08X, %08X):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
1261     return MMSYSERR_NOTENABLED;
1262 }
1263
1264 #endif /* HAVE_ALSA */