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