gdi32: Add a stub for CancelDC.
[wine] / dlls / winealsa.drv / wavein.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 IN 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 #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    *WInDev;
66 DWORD            ALSA_WidNumMallocedDevs;
67 DWORD            ALSA_WidNumDevs;
68
69 /**************************************************************************
70 *                       widNotifyClient                 [internal]
71 */
72 static DWORD widNotifyClient(WINE_WAVEDEV* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
73 {
74    TRACE("wMsg = 0x%04x dwParm1 = %04X dwParam2 = %04X\n", wMsg, dwParam1, dwParam2);
75
76    switch (wMsg) {
77    case WIM_OPEN:
78    case WIM_CLOSE:
79    case WIM_DATA:
80        if (wwi->wFlags != DCB_NULL &&
81            !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags, (HDRVR)wwi->waveDesc.hWave,
82                            wMsg, wwi->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  *                      widGetDevCaps                           [internal]
96  */
97 static DWORD widGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
98 {
99     TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
100
101     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
102
103     if (wDevID >= ALSA_WidNumDevs) {
104         TRACE("Requested device %d, but only %d are known!\n", wDevID, ALSA_WidNumDevs);
105         return MMSYSERR_BADDEVICEID;
106     }
107
108     memcpy(lpCaps, &WInDev[wDevID].incaps, min(dwSize, sizeof(*lpCaps)));
109     return MMSYSERR_NOERROR;
110 }
111
112 /**************************************************************************
113  *                              widRecorder_ReadHeaders         [internal]
114  */
115 static void widRecorder_ReadHeaders(WINE_WAVEDEV * wwi)
116 {
117     enum win_wm_message tmp_msg;
118     DWORD               tmp_param;
119     HANDLE              tmp_ev;
120     WAVEHDR*            lpWaveHdr;
121
122     while (ALSA_RetrieveRingMessage(&wwi->msgRing, &tmp_msg, &tmp_param, &tmp_ev)) {
123         if (tmp_msg == WINE_WM_HEADER) {
124             LPWAVEHDR*  wh;
125             lpWaveHdr = (LPWAVEHDR)tmp_param;
126             lpWaveHdr->lpNext = 0;
127
128             if (wwi->lpQueuePtr == 0)
129                 wwi->lpQueuePtr = lpWaveHdr;
130             else {
131                 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
132                 *wh = lpWaveHdr;
133             }
134         } else {
135             ERR("should only have headers left\n");
136         }
137     }
138 }
139
140 /**************************************************************************
141  *                              widRecorder                     [internal]
142  */
143 static  DWORD   CALLBACK        widRecorder(LPVOID pmt)
144 {
145     WORD                uDevID = (DWORD)pmt;
146     WINE_WAVEDEV*       wwi = (WINE_WAVEDEV*)&WInDev[uDevID];
147     WAVEHDR*            lpWaveHdr;
148     DWORD               dwSleepTime;
149     DWORD               bytesRead;
150     LPVOID              buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, wwi->dwPeriodSize);
151     char               *pOffset = buffer;
152     enum win_wm_message msg;
153     DWORD               param;
154     HANDLE              ev;
155     DWORD               frames_per_period;
156
157     wwi->state = WINE_WS_STOPPED;
158     wwi->dwTotalRecorded = 0;
159     wwi->lpQueuePtr = NULL;
160
161     SetEvent(wwi->hStartUpEvent);
162
163     /* make sleep time to be # of ms to output a period */
164     dwSleepTime = (1024/*wwi-dwPeriodSize => overrun!*/ * 1000) / wwi->format.Format.nAvgBytesPerSec;
165     frames_per_period = snd_pcm_bytes_to_frames(wwi->pcm, wwi->dwPeriodSize);
166     TRACE("sleeptime=%d ms\n", dwSleepTime);
167
168     for (;;) {
169         /* wait for dwSleepTime or an event in thread's queue */
170         /* FIXME: could improve wait time depending on queue state,
171          * ie, number of queued fragments
172          */
173         if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
174         {
175             int periods;
176             DWORD frames;
177             DWORD bytes;
178             DWORD read;
179
180             lpWaveHdr = wwi->lpQueuePtr;
181             /* read all the fragments accumulated so far */
182             frames = snd_pcm_avail_update(wwi->pcm);
183             bytes = snd_pcm_frames_to_bytes(wwi->pcm, frames);
184             TRACE("frames = %d  bytes = %d\n", frames, bytes);
185             periods = bytes / wwi->dwPeriodSize;
186             while ((periods > 0) && (wwi->lpQueuePtr))
187             {
188                 periods--;
189                 bytes = wwi->dwPeriodSize;
190                 TRACE("bytes = %d\n",bytes);
191                 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwPeriodSize)
192                 {
193                     /* directly read fragment in wavehdr */
194                     read = wwi->read(wwi->pcm, lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded, frames_per_period);
195                     bytesRead = snd_pcm_frames_to_bytes(wwi->pcm, read);
196
197                     TRACE("bytesRead=%d (direct)\n", bytesRead);
198                     if (bytesRead != (DWORD) -1)
199                     {
200                         /* update number of bytes recorded in current buffer and by this device */
201                         lpWaveHdr->dwBytesRecorded += bytesRead;
202                         wwi->dwTotalRecorded       += bytesRead;
203
204                         /* buffer is full. notify client */
205                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
206                         {
207                             /* must copy the value of next waveHdr, because we have no idea of what
208                              * will be done with the content of lpWaveHdr in callback
209                              */
210                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
211
212                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
213                             lpWaveHdr->dwFlags |=  WHDR_DONE;
214
215                             wwi->lpQueuePtr = lpNext;
216                             widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
217                             lpWaveHdr = lpNext;
218                         }
219                     } else {
220                         TRACE("read(%s, %p, %d) failed (%s)\n", wwi->pcmname,
221                             lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
222                             frames_per_period, strerror(errno));
223                     }
224                 }
225                 else
226                 {
227                     /* read the fragment in a local buffer */
228                     read = wwi->read(wwi->pcm, buffer, frames_per_period);
229                     bytesRead = snd_pcm_frames_to_bytes(wwi->pcm, read);
230                     pOffset = buffer;
231
232                     TRACE("bytesRead=%d (local)\n", bytesRead);
233
234                     if (bytesRead == (DWORD) -1) {
235                         TRACE("read(%s, %p, %d) failed (%s)\n", wwi->pcmname,
236                               buffer, frames_per_period, strerror(errno));
237                         continue;
238                     }
239
240                     /* copy data in client buffers */
241                     while (bytesRead != (DWORD) -1 && bytesRead > 0)
242                     {
243                         DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
244
245                         memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
246                                pOffset,
247                                dwToCopy);
248
249                         /* update number of bytes recorded in current buffer and by this device */
250                         lpWaveHdr->dwBytesRecorded += dwToCopy;
251                         wwi->dwTotalRecorded += dwToCopy;
252                         bytesRead -= dwToCopy;
253                         pOffset   += dwToCopy;
254
255                         /* client buffer is full. notify client */
256                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
257                         {
258                             /* must copy the value of next waveHdr, because we have no idea of what
259                              * will be done with the content of lpWaveHdr in callback
260                              */
261                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
262                             TRACE("lpNext=%p\n", lpNext);
263
264                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
265                             lpWaveHdr->dwFlags |=  WHDR_DONE;
266
267                             wwi->lpQueuePtr = lpNext;
268                             widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
269
270                             lpWaveHdr = lpNext;
271                             if (!lpNext && bytesRead) {
272                                 /* before we give up, check for more header messages */
273                                 while (ALSA_PeekRingMessage(&wwi->msgRing, &msg, &param, &ev))
274                                 {
275                                     if (msg == WINE_WM_HEADER) {
276                                         LPWAVEHDR hdr;
277                                         ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev);
278                                         hdr = ((LPWAVEHDR)param);
279                                         TRACE("msg = %s, hdr = %p, ev = %p\n", ALSA_getCmdString(msg), hdr, ev);
280                                         hdr->lpNext = 0;
281                                         if (lpWaveHdr == 0) {
282                                             /* new head of queue */
283                                             wwi->lpQueuePtr = lpWaveHdr = hdr;
284                                         } else {
285                                             /* insert buffer at the end of queue */
286                                             LPWAVEHDR*  wh;
287                                             for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
288                                             *wh = hdr;
289                                         }
290                                     } else
291                                         break;
292                                 }
293
294                                 if (lpWaveHdr == 0) {
295                                     /* no more buffer to copy data to, but we did read more.
296                                      * what hasn't been copied will be dropped
297                                      */
298                                     WARN("buffer under run! %u bytes dropped.\n", bytesRead);
299                                     wwi->lpQueuePtr = NULL;
300                                     break;
301                                 }
302                             }
303                         }
304                     }
305                 }
306             }
307         }
308
309         ALSA_WaitRingMessage(&wwi->msgRing, dwSleepTime);
310
311         while (ALSA_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev))
312         {
313             TRACE("msg=%s param=0x%x\n", ALSA_getCmdString(msg), param);
314             switch (msg) {
315             case WINE_WM_PAUSING:
316                 wwi->state = WINE_WS_PAUSED;
317                 /*FIXME("Device should stop recording\n");*/
318                 SetEvent(ev);
319                 break;
320             case WINE_WM_STARTING:
321                 wwi->state = WINE_WS_PLAYING;
322                 snd_pcm_start(wwi->pcm);
323                 SetEvent(ev);
324                 break;
325             case WINE_WM_HEADER:
326                 lpWaveHdr = (LPWAVEHDR)param;
327                 lpWaveHdr->lpNext = 0;
328
329                 /* insert buffer at the end of queue */
330                 {
331                     LPWAVEHDR*  wh;
332                     for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
333                     *wh = lpWaveHdr;
334                 }
335                 break;
336             case WINE_WM_STOPPING:
337                 if (wwi->state != WINE_WS_STOPPED)
338                 {
339                     snd_pcm_drain(wwi->pcm);
340
341                     /* read any headers in queue */
342                     widRecorder_ReadHeaders(wwi);
343
344                     /* return current buffer to app */
345                     lpWaveHdr = wwi->lpQueuePtr;
346                     if (lpWaveHdr)
347                     {
348                         LPWAVEHDR       lpNext = lpWaveHdr->lpNext;
349                         TRACE("stop %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
350                         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
351                         lpWaveHdr->dwFlags |= WHDR_DONE;
352                         wwi->lpQueuePtr = lpNext;
353                         widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
354                     }
355                 }
356                 wwi->state = WINE_WS_STOPPED;
357                 SetEvent(ev);
358                 break;
359             case WINE_WM_RESETTING:
360                 if (wwi->state != WINE_WS_STOPPED)
361                 {
362                     snd_pcm_drain(wwi->pcm);
363                 }
364                 wwi->state = WINE_WS_STOPPED;
365                 wwi->dwTotalRecorded = 0;
366
367                 /* read any headers in queue */
368                 widRecorder_ReadHeaders(wwi);
369
370                 /* return all buffers to the app */
371                 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
372                     TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
373                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
374                     lpWaveHdr->dwFlags |= WHDR_DONE;
375                     wwi->lpQueuePtr = lpWaveHdr->lpNext;
376                     widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
377                 }
378
379                 wwi->lpQueuePtr = NULL;
380                 SetEvent(ev);
381                 break;
382             case WINE_WM_CLOSING:
383                 wwi->hThread = 0;
384                 wwi->state = WINE_WS_CLOSED;
385                 SetEvent(ev);
386                 HeapFree(GetProcessHeap(), 0, buffer);
387                 ExitThread(0);
388                 /* shouldn't go here */
389             case WINE_WM_UPDATE:
390                 SetEvent(ev);
391                 break;
392
393             default:
394                 FIXME("unknown message %d\n", msg);
395                 break;
396             }
397         }
398     }
399     ExitThread(0);
400     /* just for not generating compilation warnings... should never be executed */
401     return 0;
402 }
403
404 /**************************************************************************
405  *                              widOpen                         [internal]
406  */
407 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
408 {
409     WINE_WAVEDEV*               wwi;
410     snd_pcm_hw_params_t *       hw_params;
411     snd_pcm_sw_params_t *       sw_params;
412     snd_pcm_access_t            access;
413     snd_pcm_format_t            format;
414     unsigned int                rate;
415     unsigned int                buffer_time = 500000;
416     unsigned int                period_time = 10000;
417     snd_pcm_uframes_t           buffer_size;
418     snd_pcm_uframes_t           period_size;
419     int                         flags;
420     snd_pcm_t *                 pcm;
421     int                         err;
422     int                         dir;
423
424     snd_pcm_hw_params_alloca(&hw_params);
425     snd_pcm_sw_params_alloca(&sw_params);
426
427     /* JPW TODO - review this code */
428     TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
429     if (lpDesc == NULL) {
430         WARN("Invalid Parameter !\n");
431         return MMSYSERR_INVALPARAM;
432     }
433     if (wDevID >= ALSA_WidNumDevs) {
434         TRACE("Requested device %d, but only %d are known!\n", wDevID, ALSA_WidNumDevs);
435         return MMSYSERR_BADDEVICEID;
436     }
437
438     /* only PCM format is supported so far... */
439     if (!ALSA_supportedFormat(lpDesc->lpFormat)) {
440         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
441              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
442              lpDesc->lpFormat->nSamplesPerSec);
443         return WAVERR_BADFORMAT;
444     }
445
446     if (dwFlags & WAVE_FORMAT_QUERY) {
447         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
448              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
449              lpDesc->lpFormat->nSamplesPerSec);
450         return MMSYSERR_NOERROR;
451     }
452
453     wwi = &WInDev[wDevID];
454
455     if (wwi->pcm != NULL) {
456         WARN("already allocated\n");
457         return MMSYSERR_ALLOCATED;
458     }
459
460     if ((dwFlags & WAVE_DIRECTSOUND) && !(wwi->dwSupport & WAVECAPS_DIRECTSOUND))
461         /* not supported, ignore it */
462         dwFlags &= ~WAVE_DIRECTSOUND;
463
464     wwi->pcm = 0;
465     flags = SND_PCM_NONBLOCK;
466 #if 0
467     if ( dwFlags & WAVE_DIRECTSOUND )
468         flags |= SND_PCM_ASYNC;
469 #endif
470
471     if ( (err=snd_pcm_open(&pcm, wwi->pcmname, SND_PCM_STREAM_CAPTURE, flags)) < 0 )
472     {
473         ERR("Error open: %s\n", snd_strerror(err));
474         return MMSYSERR_NOTENABLED;
475     }
476
477     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
478
479     memcpy(&wwi->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
480     ALSA_copyFormat(lpDesc->lpFormat, &wwi->format);
481
482     if (wwi->format.Format.wBitsPerSample == 0) {
483         WARN("Resetting zeroed wBitsPerSample\n");
484         wwi->format.Format.wBitsPerSample = 8 *
485             (wwi->format.Format.nAvgBytesPerSec /
486              wwi->format.Format.nSamplesPerSec) /
487             wwi->format.Format.nChannels;
488     }
489
490     snd_pcm_hw_params_any(pcm, hw_params);
491
492 #define EXIT_ON_ERROR(f,e,txt) do \
493 { \
494     int err; \
495     if ( (err = (f) ) < 0) \
496     { \
497         WARN(txt ": %s\n", snd_strerror(err)); \
498         snd_pcm_close(pcm); \
499         return e; \
500     } \
501 } while(0)
502
503     access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
504     if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
505         WARN("mmap not available. switching to standard write.\n");
506         access = SND_PCM_ACCESS_RW_INTERLEAVED;
507         EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
508         wwi->read = snd_pcm_readi;
509     }
510     else
511         wwi->read = snd_pcm_mmap_readi;
512
513     EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwi->format.Format.nChannels), WAVERR_BADFORMAT, "unable to set required channels");
514
515     if ((wwi->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
516         ((wwi->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
517         IsEqualGUID(&wwi->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
518         format = (wwi->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
519                  (wwi->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
520                  (wwi->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
521                  (wwi->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
522     } else if ((wwi->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
523         IsEqualGUID(&wwi->format.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)){
524         format = (wwi->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_FLOAT_LE : -1;
525     } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
526         FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
527         snd_pcm_close(pcm);
528         return WAVERR_BADFORMAT;
529     } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
530         FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
531         snd_pcm_close(pcm);
532         return WAVERR_BADFORMAT;
533     } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
534         FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
535         snd_pcm_close(pcm);
536         return WAVERR_BADFORMAT;
537     } else {
538         ERR("invalid format: %0x04x\n", wwi->format.Format.wFormatTag);
539         snd_pcm_close(pcm);
540         return WAVERR_BADFORMAT;
541     }
542
543     EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), WAVERR_BADFORMAT, "unable to set required format");
544
545     rate = wwi->format.Format.nSamplesPerSec;
546     dir = 0;
547     err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
548     if (err < 0) {
549         WARN("Rate %d Hz not available for playback: %s\n", wwi->format.Format.nSamplesPerSec, snd_strerror(rate));
550         snd_pcm_close(pcm);
551         return WAVERR_BADFORMAT;
552     }
553     if (!ALSA_NearMatch(rate, wwi->format.Format.nSamplesPerSec)) {
554         WARN("Rate doesn't match (requested %d Hz, got %d Hz)\n", wwi->format.Format.nSamplesPerSec, rate);
555         snd_pcm_close(pcm);
556         return WAVERR_BADFORMAT;
557     }
558
559     dir=0;
560     EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
561     dir=0;
562     EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
563
564     EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
565
566     dir=0;
567     err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
568     err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
569
570     snd_pcm_sw_params_current(pcm, sw_params);
571     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");
572     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
573     EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
574     EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
575     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
576     EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
577 #undef EXIT_ON_ERROR
578
579     snd_pcm_prepare(pcm);
580
581     if (TRACE_ON(wave))
582         ALSA_TraceParameters(hw_params, sw_params, FALSE);
583
584     /* now, we can save all required data for later use... */
585     if ( wwi->hw_params )
586         snd_pcm_hw_params_free(wwi->hw_params);
587     snd_pcm_hw_params_malloc(&(wwi->hw_params));
588     snd_pcm_hw_params_copy(wwi->hw_params, hw_params);
589
590     wwi->dwBufferSize = snd_pcm_frames_to_bytes(pcm, buffer_size);
591     wwi->lpQueuePtr = wwi->lpPlayPtr = wwi->lpLoopPtr = NULL;
592     wwi->pcm = pcm;
593
594     ALSA_InitRingMessage(&wwi->msgRing);
595
596     wwi->dwPeriodSize = period_size;
597     /*if (wwi->dwFragmentSize % wwi->format.Format.nBlockAlign)
598         ERR("Fragment doesn't contain an integral number of data blocks\n");
599     */
600     TRACE("dwPeriodSize=%u\n", wwi->dwPeriodSize);
601     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%u, nSamplesPerSec=%u, nChannels=%u nBlockAlign=%u!\n",
602           wwi->format.Format.wBitsPerSample, wwi->format.Format.nAvgBytesPerSec,
603           wwi->format.Format.nSamplesPerSec, wwi->format.Format.nChannels,
604           wwi->format.Format.nBlockAlign);
605
606     if (!(dwFlags & WAVE_DIRECTSOUND)) {
607         wwi->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
608         wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
609         if (wwi->hThread)
610             SetThreadPriority(wwi->hThread, THREAD_PRIORITY_TIME_CRITICAL);
611         WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
612         CloseHandle(wwi->hStartUpEvent);
613     } else {
614         wwi->hThread = INVALID_HANDLE_VALUE;
615         wwi->dwThreadID = 0;
616     }
617     wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
618
619     return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
620 }
621
622
623 /**************************************************************************
624  *                              widClose                        [internal]
625  */
626 static DWORD widClose(WORD wDevID)
627 {
628     DWORD               ret = MMSYSERR_NOERROR;
629     WINE_WAVEDEV*       wwi;
630
631     TRACE("(%u);\n", wDevID);
632
633     if (wDevID >= ALSA_WidNumDevs) {
634         TRACE("Requested device %d, but only %d are known!\n", wDevID, ALSA_WidNumDevs);
635         return MMSYSERR_BADDEVICEID;
636     }
637
638     if (WInDev[wDevID].pcm == NULL) {
639         WARN("Requested to close already closed device %d!\n", wDevID);
640         return MMSYSERR_BADDEVICEID;
641     }
642
643     wwi = &WInDev[wDevID];
644     if (wwi->lpQueuePtr) {
645         WARN("buffers still playing !\n");
646         ret = WAVERR_STILLPLAYING;
647     } else {
648         if (wwi->hThread != INVALID_HANDLE_VALUE) {
649             ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
650         }
651         ALSA_DestroyRingMessage(&wwi->msgRing);
652
653         snd_pcm_hw_params_free(wwi->hw_params);
654         wwi->hw_params = NULL;
655
656         snd_pcm_close(wwi->pcm);
657         wwi->pcm = NULL;
658
659         ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
660     }
661
662     return ret;
663 }
664
665 /**************************************************************************
666  *                              widAddBuffer                    [internal]
667  *
668  */
669 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
670 {
671     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
672
673     /* first, do the sanity checks... */
674     if (wDevID >= ALSA_WidNumDevs) {
675         TRACE("Requested device %d, but only %d are known!\n", wDevID, ALSA_WidNumDevs);
676         return MMSYSERR_BADDEVICEID;
677     }
678
679     if (WInDev[wDevID].pcm == NULL) {
680         WARN("Requested to add buffer to already closed device %d!\n", wDevID);
681         return MMSYSERR_BADDEVICEID;
682     }
683
684     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
685         return WAVERR_UNPREPARED;
686
687     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
688         return WAVERR_STILLPLAYING;
689
690     lpWaveHdr->dwFlags &= ~WHDR_DONE;
691     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
692     lpWaveHdr->lpNext = 0;
693
694     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
695
696     return MMSYSERR_NOERROR;
697 }
698
699 /**************************************************************************
700  *                              widStart                        [internal]
701  *
702  */
703 static DWORD widStart(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
704 {
705     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
706
707     /* first, do the sanity checks... */
708     if (wDevID >= ALSA_WidNumDevs) {
709         TRACE("Requested device %d, but only %d are known!\n", wDevID, ALSA_WidNumDevs);
710         return MMSYSERR_BADDEVICEID;
711     }
712
713     if (WInDev[wDevID].pcm == NULL) {
714         WARN("Requested to start closed device %d!\n", wDevID);
715         return MMSYSERR_BADDEVICEID;
716     }
717
718     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
719
720     return MMSYSERR_NOERROR;
721 }
722
723 /**************************************************************************
724  *                              widStop                 [internal]
725  *
726  */
727 static DWORD widStop(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
728 {
729     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
730
731     /* first, do the sanity checks... */
732     if (wDevID >= ALSA_WidNumDevs) {
733         TRACE("Requested device %d, but only %d are known!\n", wDevID, ALSA_WidNumDevs);
734         return MMSYSERR_BADDEVICEID;
735     }
736
737     if (WInDev[wDevID].pcm == NULL) {
738         WARN("Requested to stop closed device %d!\n", wDevID);
739         return MMSYSERR_BADDEVICEID;
740     }
741
742     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
743
744     return MMSYSERR_NOERROR;
745 }
746
747 /**************************************************************************
748  *                      widReset                                [internal]
749  */
750 static DWORD widReset(WORD wDevID)
751 {
752     TRACE("(%u);\n", wDevID);
753     if (wDevID >= ALSA_WidNumDevs) {
754         TRACE("Requested device %d, but only %d are known!\n", wDevID, ALSA_WidNumDevs);
755         return MMSYSERR_BADDEVICEID;
756     }
757
758     if (WInDev[wDevID].pcm == NULL) {
759         WARN("Requested to reset closed device %d!\n", wDevID);
760         return MMSYSERR_BADDEVICEID;
761     }
762
763     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
764     return MMSYSERR_NOERROR;
765 }
766
767 /**************************************************************************
768  *                              widGetPosition                  [internal]
769  */
770 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
771 {
772     WINE_WAVEDEV*       wwi;
773
774     TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
775
776     if (wDevID >= ALSA_WidNumDevs) {
777         TRACE("Requested device %d, but only %d are known!\n", wDevID, ALSA_WidNumDevs);
778         return MMSYSERR_BADDEVICEID;
779     }
780
781     if (WInDev[wDevID].state == WINE_WS_CLOSED) {
782         WARN("Requested position of closed device %d!\n", wDevID);
783         return MMSYSERR_BADDEVICEID;
784     }
785
786     if (lpTime == NULL) {
787         WARN("invalid parameter: lpTime = NULL\n");
788         return MMSYSERR_INVALPARAM;
789     }
790
791     wwi = &WInDev[wDevID];
792     ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_UPDATE, 0, TRUE);
793
794     return ALSA_bytes_to_mmtime(lpTime, wwi->dwTotalRecorded, &wwi->format);
795 }
796
797 /**************************************************************************
798  *                              widGetNumDevs                   [internal]
799  */
800 static  DWORD   widGetNumDevs(void)
801 {
802     return ALSA_WidNumDevs;
803 }
804
805 /**************************************************************************
806  *                              widDevInterfaceSize             [internal]
807  */
808 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
809 {
810     TRACE("(%u, %p)\n", wDevID, dwParam1);
811
812     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
813                                     NULL, 0 ) * sizeof(WCHAR);
814     return MMSYSERR_NOERROR;
815 }
816
817 /**************************************************************************
818  *                              widDevInterface                 [internal]
819  */
820 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
821 {
822     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
823                                         NULL, 0 ) * sizeof(WCHAR))
824     {
825         MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
826                             dwParam1, dwParam2 / sizeof(WCHAR));
827         return MMSYSERR_NOERROR;
828     }
829     return MMSYSERR_INVALPARAM;
830 }
831
832 /**************************************************************************
833  *                              widDsCreate                     [internal]
834  */
835 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
836 {
837     TRACE("(%d,%p)\n",wDevID,drv);
838
839     /* the HAL isn't much better than the HEL if we can't do mmap() */
840     FIXME("DirectSoundCapture not implemented\n");
841     FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
842     return MMSYSERR_NOTSUPPORTED;
843 }
844
845 /**************************************************************************
846  *                              widDsDesc                       [internal]
847  */
848 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
849 {
850     memcpy(desc, &(WInDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
851     return MMSYSERR_NOERROR;
852 }
853
854 /**************************************************************************
855  *                              widMessage (WINEALSA.@)
856  */
857 DWORD WINAPI ALSA_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
858                              DWORD dwParam1, DWORD dwParam2)
859 {
860     TRACE("(%u, %s, %08X, %08X, %08X);\n",
861           wDevID, ALSA_getMessage(wMsg), dwUser, dwParam1, dwParam2);
862
863     switch (wMsg) {
864     case DRVM_INIT:
865     case DRVM_EXIT:
866     case DRVM_ENABLE:
867     case DRVM_DISABLE:
868         /* FIXME: Pretend this is supported */
869         return 0;
870     case WIDM_OPEN:             return widOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
871     case WIDM_CLOSE:            return widClose         (wDevID);
872     case WIDM_ADDBUFFER:        return widAddBuffer     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
873     case WIDM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
874     case WIDM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
875     case WIDM_GETDEVCAPS:       return widGetDevCaps    (wDevID, (LPWAVEOUTCAPSW)dwParam1,      dwParam2);
876     case WIDM_GETNUMDEVS:       return widGetNumDevs    ();
877     case WIDM_GETPOS:           return widGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
878     case WIDM_RESET:            return widReset         (wDevID);
879     case WIDM_START:            return widStart (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
880     case WIDM_STOP:             return widStop  (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
881     case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
882     case DRV_QUERYDEVICEINTERFACE:     return widDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
883     case DRV_QUERYDSOUNDIFACE:  return widDsCreate   (wDevID, (PIDSCDRIVER*)dwParam1);
884     case DRV_QUERYDSOUNDDESC:   return widDsDesc     (wDevID, (PDSDRIVERDESC)dwParam1);
885     default:
886         FIXME("unknown message %d!\n", wMsg);
887     }
888     return MMSYSERR_NOTSUPPORTED;
889 }
890
891 #else /* HAVE_ALSA */
892
893 /**************************************************************************
894  *                              widMessage (WINEALSA.@)
895  */
896 DWORD WINAPI ALSA_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
897                              DWORD dwParam1, DWORD dwParam2)
898 {
899     FIXME("(%u, %04X, %08X, %08X, %08X):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
900     return MMSYSERR_NOTENABLED;
901 }
902
903 #endif /* HAVE_ALSA */