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