quartz: Exclude unused headers.
[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
467     if ( (err=snd_pcm_open(&pcm, wwi->pcmname, SND_PCM_STREAM_CAPTURE, flags)) < 0 )
468     {
469         ERR("Error open: %s\n", snd_strerror(err));
470         return MMSYSERR_NOTENABLED;
471     }
472
473     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
474
475     memcpy(&wwi->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
476     ALSA_copyFormat(lpDesc->lpFormat, &wwi->format);
477
478     if (wwi->format.Format.wBitsPerSample == 0) {
479         WARN("Resetting zeroed wBitsPerSample\n");
480         wwi->format.Format.wBitsPerSample = 8 *
481             (wwi->format.Format.nAvgBytesPerSec /
482              wwi->format.Format.nSamplesPerSec) /
483             wwi->format.Format.nChannels;
484     }
485
486     snd_pcm_hw_params_any(pcm, hw_params);
487
488 #define EXIT_ON_ERROR(f,e,txt) do \
489 { \
490     int err; \
491     if ( (err = (f) ) < 0) \
492     { \
493         WARN(txt ": %s\n", snd_strerror(err)); \
494         snd_pcm_close(pcm); \
495         return e; \
496     } \
497 } while(0)
498
499     access = SND_PCM_ACCESS_MMAP_INTERLEAVED;
500     if ( ( err = snd_pcm_hw_params_set_access(pcm, hw_params, access ) ) < 0) {
501         WARN("mmap not available. switching to standard write.\n");
502         access = SND_PCM_ACCESS_RW_INTERLEAVED;
503         EXIT_ON_ERROR( snd_pcm_hw_params_set_access(pcm, hw_params, access ), MMSYSERR_INVALPARAM, "unable to set access for playback");
504         wwi->read = snd_pcm_readi;
505     }
506     else
507         wwi->read = snd_pcm_mmap_readi;
508
509     EXIT_ON_ERROR( snd_pcm_hw_params_set_channels(pcm, hw_params, wwi->format.Format.nChannels), WAVERR_BADFORMAT, "unable to set required channels");
510
511     if ((wwi->format.Format.wFormatTag == WAVE_FORMAT_PCM) ||
512         ((wwi->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
513         IsEqualGUID(&wwi->format.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) {
514         format = (wwi->format.Format.wBitsPerSample == 8) ? SND_PCM_FORMAT_U8 :
515                  (wwi->format.Format.wBitsPerSample == 16) ? SND_PCM_FORMAT_S16_LE :
516                  (wwi->format.Format.wBitsPerSample == 24) ? SND_PCM_FORMAT_S24_LE :
517                  (wwi->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_S32_LE : -1;
518     } else if ((wwi->format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
519         IsEqualGUID(&wwi->format.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)){
520         format = (wwi->format.Format.wBitsPerSample == 32) ? SND_PCM_FORMAT_FLOAT_LE : -1;
521     } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_MULAW) {
522         FIXME("unimplemented format: WAVE_FORMAT_MULAW\n");
523         snd_pcm_close(pcm);
524         return WAVERR_BADFORMAT;
525     } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ALAW) {
526         FIXME("unimplemented format: WAVE_FORMAT_ALAW\n");
527         snd_pcm_close(pcm);
528         return WAVERR_BADFORMAT;
529     } else if (wwi->format.Format.wFormatTag == WAVE_FORMAT_ADPCM) {
530         FIXME("unimplemented format: WAVE_FORMAT_ADPCM\n");
531         snd_pcm_close(pcm);
532         return WAVERR_BADFORMAT;
533     } else {
534         ERR("invalid format: %0x04x\n", wwi->format.Format.wFormatTag);
535         snd_pcm_close(pcm);
536         return WAVERR_BADFORMAT;
537     }
538
539     EXIT_ON_ERROR( snd_pcm_hw_params_set_format(pcm, hw_params, format), WAVERR_BADFORMAT, "unable to set required format");
540
541     rate = wwi->format.Format.nSamplesPerSec;
542     dir = 0;
543     err = snd_pcm_hw_params_set_rate_near(pcm, hw_params, &rate, &dir);
544     if (err < 0) {
545         WARN("Rate %d Hz not available for playback: %s\n", wwi->format.Format.nSamplesPerSec, snd_strerror(rate));
546         snd_pcm_close(pcm);
547         return WAVERR_BADFORMAT;
548     }
549     if (!ALSA_NearMatch(rate, wwi->format.Format.nSamplesPerSec)) {
550         WARN("Rate doesn't match (requested %d Hz, got %d Hz)\n", wwi->format.Format.nSamplesPerSec, rate);
551         snd_pcm_close(pcm);
552         return WAVERR_BADFORMAT;
553     }
554
555     dir=0;
556     EXIT_ON_ERROR( snd_pcm_hw_params_set_buffer_time_near(pcm, hw_params, &buffer_time, &dir), MMSYSERR_INVALPARAM, "unable to set buffer time");
557     dir=0;
558     EXIT_ON_ERROR( snd_pcm_hw_params_set_period_time_near(pcm, hw_params, &period_time, &dir), MMSYSERR_INVALPARAM, "unable to set period time");
559
560     EXIT_ON_ERROR( snd_pcm_hw_params(pcm, hw_params), MMSYSERR_INVALPARAM, "unable to set hw params for playback");
561
562     dir=0;
563     err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
564     err = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
565
566     snd_pcm_sw_params_current(pcm, sw_params);
567     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");
568     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_size(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence size");
569     EXIT_ON_ERROR( snd_pcm_sw_params_set_avail_min(pcm, sw_params, period_size), MMSYSERR_ERROR, "unable to set avail min");
570     EXIT_ON_ERROR( snd_pcm_sw_params_set_xfer_align(pcm, sw_params, 1), MMSYSERR_ERROR, "unable to set xfer align");
571     EXIT_ON_ERROR( snd_pcm_sw_params_set_silence_threshold(pcm, sw_params, 0), MMSYSERR_ERROR, "unable to set silence threshold");
572     EXIT_ON_ERROR( snd_pcm_sw_params(pcm, sw_params), MMSYSERR_ERROR, "unable to set sw params for playback");
573 #undef EXIT_ON_ERROR
574
575     snd_pcm_prepare(pcm);
576
577     if (TRACE_ON(wave))
578         ALSA_TraceParameters(hw_params, sw_params, FALSE);
579
580     /* now, we can save all required data for later use... */
581     if ( wwi->hw_params )
582         snd_pcm_hw_params_free(wwi->hw_params);
583     snd_pcm_hw_params_malloc(&(wwi->hw_params));
584     snd_pcm_hw_params_copy(wwi->hw_params, hw_params);
585
586     wwi->dwBufferSize = snd_pcm_frames_to_bytes(pcm, buffer_size);
587     wwi->lpQueuePtr = wwi->lpPlayPtr = wwi->lpLoopPtr = NULL;
588     wwi->pcm = pcm;
589
590     ALSA_InitRingMessage(&wwi->msgRing);
591
592     wwi->dwPeriodSize = period_size;
593     /*if (wwi->dwFragmentSize % wwi->format.Format.nBlockAlign)
594         ERR("Fragment doesn't contain an integral number of data blocks\n");
595     */
596     TRACE("dwPeriodSize=%u\n", wwi->dwPeriodSize);
597     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%u, nSamplesPerSec=%u, nChannels=%u nBlockAlign=%u!\n",
598           wwi->format.Format.wBitsPerSample, wwi->format.Format.nAvgBytesPerSec,
599           wwi->format.Format.nSamplesPerSec, wwi->format.Format.nChannels,
600           wwi->format.Format.nBlockAlign);
601
602     if (!(dwFlags & WAVE_DIRECTSOUND)) {
603         wwi->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
604         wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
605         if (wwi->hThread)
606             SetThreadPriority(wwi->hThread, THREAD_PRIORITY_TIME_CRITICAL);
607         WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
608         CloseHandle(wwi->hStartUpEvent);
609     } else {
610         wwi->hThread = INVALID_HANDLE_VALUE;
611         wwi->dwThreadID = 0;
612     }
613     wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
614
615     return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
616 }
617
618
619 /**************************************************************************
620  *                              widClose                        [internal]
621  */
622 static DWORD widClose(WORD wDevID)
623 {
624     DWORD               ret = MMSYSERR_NOERROR;
625     WINE_WAVEDEV*       wwi;
626
627     TRACE("(%u);\n", wDevID);
628
629     if (wDevID >= ALSA_WidNumDevs) {
630         TRACE("Requested device %d, but only %d are known!\n", wDevID, ALSA_WidNumDevs);
631         return MMSYSERR_BADDEVICEID;
632     }
633
634     if (WInDev[wDevID].pcm == NULL) {
635         WARN("Requested to close already closed device %d!\n", wDevID);
636         return MMSYSERR_BADDEVICEID;
637     }
638
639     wwi = &WInDev[wDevID];
640     if (wwi->lpQueuePtr) {
641         WARN("buffers still playing !\n");
642         ret = WAVERR_STILLPLAYING;
643     } else {
644         if (wwi->hThread != INVALID_HANDLE_VALUE) {
645             ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
646         }
647         ALSA_DestroyRingMessage(&wwi->msgRing);
648
649         snd_pcm_hw_params_free(wwi->hw_params);
650         wwi->hw_params = NULL;
651
652         snd_pcm_close(wwi->pcm);
653         wwi->pcm = NULL;
654
655         ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
656     }
657
658     return ret;
659 }
660
661 /**************************************************************************
662  *                              widAddBuffer                    [internal]
663  *
664  */
665 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
666 {
667     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
668
669     /* first, do the sanity checks... */
670     if (wDevID >= ALSA_WidNumDevs) {
671         TRACE("Requested device %d, but only %d are known!\n", wDevID, ALSA_WidNumDevs);
672         return MMSYSERR_BADDEVICEID;
673     }
674
675     if (WInDev[wDevID].pcm == NULL) {
676         WARN("Requested to add buffer to already closed device %d!\n", wDevID);
677         return MMSYSERR_BADDEVICEID;
678     }
679
680     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
681         return WAVERR_UNPREPARED;
682
683     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
684         return WAVERR_STILLPLAYING;
685
686     lpWaveHdr->dwFlags &= ~WHDR_DONE;
687     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
688     lpWaveHdr->lpNext = 0;
689
690     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
691
692     return MMSYSERR_NOERROR;
693 }
694
695 /**************************************************************************
696  *                              widStart                        [internal]
697  *
698  */
699 static DWORD widStart(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
700 {
701     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
702
703     /* first, do the sanity checks... */
704     if (wDevID >= ALSA_WidNumDevs) {
705         TRACE("Requested device %d, but only %d are known!\n", wDevID, ALSA_WidNumDevs);
706         return MMSYSERR_BADDEVICEID;
707     }
708
709     if (WInDev[wDevID].pcm == NULL) {
710         WARN("Requested to start closed device %d!\n", wDevID);
711         return MMSYSERR_BADDEVICEID;
712     }
713
714     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
715
716     return MMSYSERR_NOERROR;
717 }
718
719 /**************************************************************************
720  *                              widStop                 [internal]
721  *
722  */
723 static DWORD widStop(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
724 {
725     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
726
727     /* first, do the sanity checks... */
728     if (wDevID >= ALSA_WidNumDevs) {
729         TRACE("Requested device %d, but only %d are known!\n", wDevID, ALSA_WidNumDevs);
730         return MMSYSERR_BADDEVICEID;
731     }
732
733     if (WInDev[wDevID].pcm == NULL) {
734         WARN("Requested to stop closed device %d!\n", wDevID);
735         return MMSYSERR_BADDEVICEID;
736     }
737
738     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
739
740     return MMSYSERR_NOERROR;
741 }
742
743 /**************************************************************************
744  *                      widReset                                [internal]
745  */
746 static DWORD widReset(WORD wDevID)
747 {
748     TRACE("(%u);\n", wDevID);
749     if (wDevID >= ALSA_WidNumDevs) {
750         TRACE("Requested device %d, but only %d are known!\n", wDevID, ALSA_WidNumDevs);
751         return MMSYSERR_BADDEVICEID;
752     }
753
754     if (WInDev[wDevID].pcm == NULL) {
755         WARN("Requested to reset closed device %d!\n", wDevID);
756         return MMSYSERR_BADDEVICEID;
757     }
758
759     ALSA_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
760     return MMSYSERR_NOERROR;
761 }
762
763 /**************************************************************************
764  *                              widGetPosition                  [internal]
765  */
766 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
767 {
768     WINE_WAVEDEV*       wwi;
769
770     TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
771
772     if (wDevID >= ALSA_WidNumDevs) {
773         TRACE("Requested device %d, but only %d are known!\n", wDevID, ALSA_WidNumDevs);
774         return MMSYSERR_BADDEVICEID;
775     }
776
777     if (WInDev[wDevID].state == WINE_WS_CLOSED) {
778         WARN("Requested position of closed device %d!\n", wDevID);
779         return MMSYSERR_BADDEVICEID;
780     }
781
782     if (lpTime == NULL) {
783         WARN("invalid parameter: lpTime = NULL\n");
784         return MMSYSERR_INVALPARAM;
785     }
786
787     wwi = &WInDev[wDevID];
788     ALSA_AddRingMessage(&wwi->msgRing, WINE_WM_UPDATE, 0, TRUE);
789
790     return ALSA_bytes_to_mmtime(lpTime, wwi->dwTotalRecorded, &wwi->format);
791 }
792
793 /**************************************************************************
794  *                              widGetNumDevs                   [internal]
795  */
796 static  DWORD   widGetNumDevs(void)
797 {
798     return ALSA_WidNumDevs;
799 }
800
801 /**************************************************************************
802  *                              widDevInterfaceSize             [internal]
803  */
804 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
805 {
806     TRACE("(%u, %p)\n", wDevID, dwParam1);
807
808     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
809                                     NULL, 0 ) * sizeof(WCHAR);
810     return MMSYSERR_NOERROR;
811 }
812
813 /**************************************************************************
814  *                              widDevInterface                 [internal]
815  */
816 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
817 {
818     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
819                                         NULL, 0 ) * sizeof(WCHAR))
820     {
821         MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
822                             dwParam1, dwParam2 / sizeof(WCHAR));
823         return MMSYSERR_NOERROR;
824     }
825     return MMSYSERR_INVALPARAM;
826 }
827
828 /**************************************************************************
829  *                              widDsCreate                     [internal]
830  */
831 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
832 {
833     TRACE("(%d,%p)\n",wDevID,drv);
834
835     /* the HAL isn't much better than the HEL if we can't do mmap() */
836     FIXME("DirectSoundCapture not implemented\n");
837     FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
838     return MMSYSERR_NOTSUPPORTED;
839 }
840
841 /**************************************************************************
842  *                              widDsDesc                       [internal]
843  */
844 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
845 {
846     memcpy(desc, &(WInDev[wDevID].ds_desc), sizeof(DSDRIVERDESC));
847     return MMSYSERR_NOERROR;
848 }
849
850 /**************************************************************************
851  *                              widMessage (WINEALSA.@)
852  */
853 DWORD WINAPI ALSA_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
854                              DWORD dwParam1, DWORD dwParam2)
855 {
856     TRACE("(%u, %s, %08X, %08X, %08X);\n",
857           wDevID, ALSA_getMessage(wMsg), dwUser, dwParam1, dwParam2);
858
859     switch (wMsg) {
860     case DRVM_INIT:
861     case DRVM_EXIT:
862     case DRVM_ENABLE:
863     case DRVM_DISABLE:
864         /* FIXME: Pretend this is supported */
865         return 0;
866     case WIDM_OPEN:             return widOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
867     case WIDM_CLOSE:            return widClose         (wDevID);
868     case WIDM_ADDBUFFER:        return widAddBuffer     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
869     case WIDM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
870     case WIDM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
871     case WIDM_GETDEVCAPS:       return widGetDevCaps    (wDevID, (LPWAVEOUTCAPSW)dwParam1,      dwParam2);
872     case WIDM_GETNUMDEVS:       return widGetNumDevs    ();
873     case WIDM_GETPOS:           return widGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
874     case WIDM_RESET:            return widReset         (wDevID);
875     case WIDM_START:            return widStart (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
876     case WIDM_STOP:             return widStop  (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
877     case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
878     case DRV_QUERYDEVICEINTERFACE:     return widDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
879     case DRV_QUERYDSOUNDIFACE:  return widDsCreate   (wDevID, (PIDSCDRIVER*)dwParam1);
880     case DRV_QUERYDSOUNDDESC:   return widDsDesc     (wDevID, (PDSDRIVERDESC)dwParam1);
881     default:
882         FIXME("unknown message %d!\n", wMsg);
883     }
884     return MMSYSERR_NOTSUPPORTED;
885 }
886
887 #else /* HAVE_ALSA */
888
889 /**************************************************************************
890  *                              widMessage (WINEALSA.@)
891  */
892 DWORD WINAPI ALSA_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
893                              DWORD dwParam1, DWORD dwParam2)
894 {
895     FIXME("(%u, %04X, %08X, %08X, %08X):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
896     return MMSYSERR_NOTENABLED;
897 }
898
899 #endif /* HAVE_ALSA */