crypt32: Add additional path for Solaris 11 Express.
[wine] / dlls / winealsa.drv / waveinit.c
1 /*
2  * Sample Wine Driver for Advanced Linux Sound System (ALSA)
3  *      Based on version <final> of the ALSA API
4  *
5  * This file performs the initialisation and scanning of the sound subsystem.
6  *
7  * Copyright    2002 Eric Pouech
8  *              2002 Marco Pietrobono
9  *              2003 Christian Costa : WaveIn support
10  *              2006-2007 Maarten Lankhorst
11  *
12  * This library is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with this library; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25  */
26
27 #include "config.h"
28 #include "wine/port.h"
29
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <string.h>
34 #ifdef HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
37 #include <errno.h>
38 #include <limits.h>
39 #include <fcntl.h>
40 #ifdef HAVE_SYS_IOCTL_H
41 # include <sys/ioctl.h>
42 #endif
43 #ifdef HAVE_SYS_MMAN_H
44 # include <sys/mman.h>
45 #endif
46 #include "windef.h"
47 #include "winbase.h"
48 #include "wingdi.h"
49 #include "winerror.h"
50 #include "winuser.h"
51 #include "winnls.h"
52 #include "winreg.h"
53 #include "mmddk.h"
54 #include "mmreg.h"
55 #include "dsound.h"
56 #include "dsdriver.h"
57
58 #include "alsa.h"
59
60 #include "wine/library.h"
61 #include "wine/unicode.h"
62 #include "wine/debug.h"
63
64 WINE_DEFAULT_DEBUG_CHANNEL(wave);
65
66 /*----------------------------------------------------------------------------
67 **  ALSA_TestDeviceForWine
68 **
69 **      Test to see if a given device is sufficient for Wine.
70 */
71 static int ALSA_TestDeviceForWine(int card, int device,  snd_pcm_stream_t streamtype)
72 {
73     snd_pcm_t *pcm = NULL;
74     char pcmname[256];
75     int retcode;
76     snd_pcm_hw_params_t *hwparams;
77     const char *reason = NULL;
78     unsigned int rrate;
79
80     hwparams = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof() );
81
82     /* Note that the plug: device masks out a lot of info, we want to avoid that */
83     sprintf(pcmname, "hw:%d,%d", card, device);
84     retcode = snd_pcm_open(&pcm, pcmname, streamtype, SND_PCM_NONBLOCK);
85     if (retcode < 0)
86     {
87         /* Note that a busy device isn't automatically disqualified */
88         if (retcode == (-1 * EBUSY))
89             retcode = 0;
90         goto exit;
91     }
92
93     retcode = snd_pcm_hw_params_any(pcm, hwparams);
94     if (retcode < 0)
95     {
96         reason = "Could not retrieve hw_params";
97         goto exit;
98     }
99
100     /* set the count of channels */
101     retcode = snd_pcm_hw_params_set_channels(pcm, hwparams, 2);
102     if (retcode < 0)
103     {
104         retcode = snd_pcm_hw_params_set_channels(pcm, hwparams, 1); /* If we can't open stereo, try mono; this is vital for snd_usb_audio microphones */
105     }
106     if (retcode < 0)
107     {
108         reason = "Could not set channels";
109         goto exit;
110     }
111
112     rrate = 44100;
113     retcode = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rrate, 0);
114     if (retcode < 0)
115     {
116         reason = "Could not set rate";
117         goto exit;
118     }
119
120     if (rrate == 0)
121     {
122         reason = "Rate came back as 0";
123         goto exit;
124     }
125
126     /* write the parameters to device */
127     retcode = snd_pcm_hw_params(pcm, hwparams);
128     if (retcode < 0)
129     {
130         reason = "Could not set hwparams";
131         goto exit;
132     }
133
134     retcode = 0;
135
136 exit:
137     if (pcm)
138         snd_pcm_close(pcm);
139     HeapFree( GetProcessHeap(), 0, hwparams );
140
141     if (retcode != 0 && retcode != (-1 * ENOENT))
142         TRACE("Discarding card %d/device %d:  %s [%d(%s)]\n", card, device, reason, retcode, snd_strerror(retcode));
143
144     return retcode;
145 }
146
147 /*----------------------------------------------------------------------------
148 ** ALSA_RegGetString
149 **  Retrieve a string from a registry key
150 */
151 static int ALSA_RegGetString(HKEY key, const char *value, char **bufp)
152 {
153     DWORD rc;
154     DWORD type;
155     DWORD bufsize;
156
157     *bufp = NULL;
158     rc = RegQueryValueExA(key, value, NULL, &type, NULL, &bufsize);
159     if (rc != ERROR_SUCCESS)
160         return(rc);
161
162     if (type != REG_SZ)
163         return 1;
164
165     *bufp = HeapAlloc(GetProcessHeap(), 0, bufsize);
166     if (! *bufp)
167         return 1;
168
169     rc = RegQueryValueExA(key, value, NULL, NULL, (LPBYTE)*bufp, &bufsize);
170     return rc;
171 }
172
173 /*----------------------------------------------------------------------------
174 ** ALSA_RegGetBoolean
175 **  Get a string and interpret it as a boolean
176 */
177
178 /* Possible truths:
179    Y(es), T(rue), 1, E(nabled) */
180
181 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1' || (ch) == 'e' || (ch) == 'E')
182 static int ALSA_RegGetBoolean(HKEY key, const char *value, BOOL *answer)
183 {
184     DWORD rc;
185     char *buf = NULL;
186
187     rc = ALSA_RegGetString(key, value, &buf);
188     if (buf)
189     {
190         *answer = FALSE;
191         if (IS_OPTION_TRUE(*buf))
192             *answer = TRUE;
193
194         HeapFree(GetProcessHeap(), 0, buf);
195     }
196
197     return rc;
198 }
199
200 /*----------------------------------------------------------------------------
201 ** ALSA_RegGetInt
202 **  Get a string and interpret it as a DWORD
203 */
204 static int ALSA_RegGetInt(HKEY key, const char *value, DWORD *answer)
205 {
206     DWORD rc;
207     char *buf = NULL;
208
209     rc = ALSA_RegGetString(key, value, &buf);
210     if (buf)
211     {
212         *answer = atoi(buf);
213         HeapFree(GetProcessHeap(), 0, buf);
214     }
215
216     return rc;
217 }
218
219 /* return a string duplicated on the win32 process heap, free with HeapFree */
220 static char* ALSA_strdup(const char *s) {
221     char *result = HeapAlloc(GetProcessHeap(), 0, strlen(s)+1);
222     if (!result)
223         return NULL;
224     strcpy(result, s);
225     return result;
226 }
227
228 #define ALSA_RETURN_ONFAIL(mycall)                                      \
229 {                                                                       \
230     int rc;                                                             \
231     {rc = mycall;}                                                      \
232     if ((rc) < 0)                                                       \
233     {                                                                   \
234         ERR("%s failed:  %s(%d)\n", #mycall, snd_strerror(rc), rc);     \
235         return(rc);                                                     \
236     }                                                                   \
237 }
238
239 /*----------------------------------------------------------------------------
240 **  ALSA_ComputeCaps
241 **
242 **      Given an ALSA PCM, figure out our HW CAPS structure info.
243 **  ctl can be null, pcm is required, as is all output parms.
244 **
245 */
246 static int ALSA_ComputeCaps(snd_ctl_t *ctl, snd_pcm_t *pcm,
247         WORD *channels, DWORD *flags, DWORD *formats, DWORD *supports)
248 {
249     snd_pcm_hw_params_t *hw_params;
250     snd_pcm_format_mask_t *fmask;
251     snd_pcm_access_mask_t *acmask;
252     unsigned int ratemin = 0;
253     unsigned int ratemax = 0;
254     unsigned int chmin = 0;
255     unsigned int chmax = 0;
256     int rc, dir = 0;
257
258     hw_params = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_hw_params_sizeof() );
259     fmask = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_format_mask_sizeof() );
260     acmask = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_access_mask_sizeof() );
261
262     if ((rc = snd_pcm_hw_params_any(pcm, hw_params)) < 0) goto done;
263
264     snd_pcm_hw_params_get_format_mask(hw_params, fmask);
265
266     if ((rc = snd_pcm_hw_params_get_access_mask(hw_params, acmask)) < 0) goto done;
267
268     if ((rc = snd_pcm_hw_params_get_rate_min(hw_params, &ratemin, &dir)) < 0) goto done;
269     if ((rc = snd_pcm_hw_params_get_rate_max(hw_params, &ratemax, &dir)) < 0) goto done;
270     if ((rc = snd_pcm_hw_params_get_channels_min(hw_params, &chmin)) < 0) goto done;
271     if ((rc = snd_pcm_hw_params_get_channels_max(hw_params, &chmax)) < 0) goto done;
272
273 #define X(r,v) \
274     if ( (r) >= ratemin && ( (r) <= ratemax || ratemax == -1) ) \
275     { \
276        if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_U8)) \
277        { \
278           if (chmin <= 1 && 1 <= chmax) \
279               *formats |= WAVE_FORMAT_##v##M08; \
280           if (chmin <= 2 && 2 <= chmax) \
281               *formats |= WAVE_FORMAT_##v##S08; \
282        } \
283        if (snd_pcm_format_mask_test( fmask, SND_PCM_FORMAT_S16_LE)) \
284        { \
285           if (chmin <= 1 && 1 <= chmax) \
286               *formats |= WAVE_FORMAT_##v##M16; \
287           if (chmin <= 2 && 2 <= chmax) \
288               *formats |= WAVE_FORMAT_##v##S16; \
289        } \
290     }
291     X(11025,1);
292     X(22050,2);
293     X(44100,4);
294     X(48000,48);
295     X(96000,96);
296 #undef X
297
298     if (chmin > 1)
299         FIXME("Device has a minimum of %d channels\n", chmin);
300     *channels = chmax;
301
302     /* FIXME: is sample accurate always true ?
303     ** Can we do WAVECAPS_PITCH, WAVECAPS_SYNC, or WAVECAPS_PLAYBACKRATE? */
304     *supports |= WAVECAPS_SAMPLEACCURATE;
305
306     *supports |= WAVECAPS_DIRECTSOUND;
307
308     /* check for volume control support */
309     if (ctl) {
310         if (snd_ctl_name(ctl))
311         {
312             snd_hctl_t *hctl;
313             if (snd_hctl_open(&hctl, snd_ctl_name(ctl), 0) >= 0)
314             {
315                 snd_hctl_load(hctl);
316                 if (!ALSA_CheckSetVolume( hctl, NULL, NULL, NULL, NULL, NULL, NULL, NULL ))
317                 {
318                     *supports |= WAVECAPS_VOLUME;
319                     if (chmin <= 2 && 2 <= chmax)
320                         *supports |= WAVECAPS_LRVOLUME;
321                 }
322                 snd_hctl_free(hctl);
323                 snd_hctl_close(hctl);
324             }
325         }
326     }
327
328     *flags = DSCAPS_CERTIFIED | DSCAPS_CONTINUOUSRATE;
329     *flags |= DSCAPS_SECONDARYMONO | DSCAPS_SECONDARYSTEREO;
330     *flags |= DSCAPS_SECONDARY8BIT | DSCAPS_SECONDARY16BIT;
331
332     if (*formats & (WAVE_FORMAT_1M08  | WAVE_FORMAT_2M08  |
333                                WAVE_FORMAT_4M08  | WAVE_FORMAT_48M08 |
334                                WAVE_FORMAT_96M08 | WAVE_FORMAT_1M16  |
335                                WAVE_FORMAT_2M16  | WAVE_FORMAT_4M16  |
336                                WAVE_FORMAT_48M16 | WAVE_FORMAT_96M16) )
337         *flags |= DSCAPS_PRIMARYMONO;
338
339     if (*formats & (WAVE_FORMAT_1S08  | WAVE_FORMAT_2S08  |
340                                WAVE_FORMAT_4S08  | WAVE_FORMAT_48S08 |
341                                WAVE_FORMAT_96S08 | WAVE_FORMAT_1S16  |
342                                WAVE_FORMAT_2S16  | WAVE_FORMAT_4S16  |
343                                WAVE_FORMAT_48S16 | WAVE_FORMAT_96S16) )
344         *flags |= DSCAPS_PRIMARYSTEREO;
345
346     if (*formats & (WAVE_FORMAT_1M08  | WAVE_FORMAT_2M08  |
347                                WAVE_FORMAT_4M08  | WAVE_FORMAT_48M08 |
348                                WAVE_FORMAT_96M08 | WAVE_FORMAT_1S08  |
349                                WAVE_FORMAT_2S08  | WAVE_FORMAT_4S08  |
350                                WAVE_FORMAT_48S08 | WAVE_FORMAT_96S08) )
351         *flags |= DSCAPS_PRIMARY8BIT;
352
353     if (*formats & (WAVE_FORMAT_1M16  | WAVE_FORMAT_2M16  |
354                                WAVE_FORMAT_4M16  | WAVE_FORMAT_48M16 |
355                                WAVE_FORMAT_96M16 | WAVE_FORMAT_1S16  |
356                                WAVE_FORMAT_2S16  | WAVE_FORMAT_4S16  |
357                                WAVE_FORMAT_48S16 | WAVE_FORMAT_96S16) )
358         *flags |= DSCAPS_PRIMARY16BIT;
359
360     rc = 0;
361
362 done:
363     if (rc < 0) ERR("failed: %s(%d)\n", snd_strerror(rc), rc);
364     HeapFree( GetProcessHeap(), 0, hw_params );
365     HeapFree( GetProcessHeap(), 0, fmask );
366     HeapFree( GetProcessHeap(), 0, acmask );
367     return rc;
368 }
369
370 /*----------------------------------------------------------------------------
371 **  ALSA_AddCommonDevice
372 **
373 **      Perform Alsa initialization common to both capture and playback
374 **
375 **  Side Effect:  ww->pcname and ww->ctlname may need to be freed.
376 **
377 **  Note:  this was originally coded by using snd_pcm_name(pcm), until
378 **         I discovered that with at least one version of alsa lib,
379 **         the use of a pcm named default:0 would cause snd_pcm_name() to fail.
380 **         So passing the name in is logically extraneous.  Sigh.
381 */
382 static int ALSA_AddCommonDevice(snd_ctl_t *ctl, snd_pcm_t *pcm, const char *pcmname, WINE_WAVEDEV *ww)
383 {
384     snd_pcm_info_t *infop;
385     int rc;
386
387     infop = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_info_sizeof() );
388     if ((rc = snd_pcm_info(pcm, infop)) < 0)
389     {
390         HeapFree( GetProcessHeap(), 0, infop );
391         return rc;
392     }
393
394     if (pcm && pcmname)
395         ww->pcmname = ALSA_strdup(pcmname);
396     else
397     {
398         HeapFree( GetProcessHeap(), 0, infop );
399         return -1;
400     }
401
402     if (ctl && snd_ctl_name(ctl))
403         ww->ctlname = ALSA_strdup(snd_ctl_name(ctl));
404
405     strcpy(ww->interface_name, "winealsa: ");
406     memcpy(ww->interface_name + strlen(ww->interface_name),
407             ww->pcmname,
408             min(strlen(ww->pcmname), sizeof(ww->interface_name) - strlen("winealsa:   ")));
409
410     strcpy(ww->ds_desc.szDrvname, "winealsa.drv");
411
412     memcpy(ww->ds_desc.szDesc, snd_pcm_info_get_name(infop),
413             min( (sizeof(ww->ds_desc.szDesc) - 1), strlen(snd_pcm_info_get_name(infop))) );
414
415     ww->ds_caps.dwMinSecondarySampleRate = DSBFREQUENCY_MIN;
416     ww->ds_caps.dwMaxSecondarySampleRate = DSBFREQUENCY_MAX;
417     ww->ds_caps.dwPrimaryBuffers = 1;
418
419     HeapFree( GetProcessHeap(), 0, infop );
420     return 0;
421 }
422
423 /*----------------------------------------------------------------------------
424 ** ALSA_FreeDevice
425 */
426 static void ALSA_FreeDevice(WINE_WAVEDEV *ww)
427 {
428     HeapFree(GetProcessHeap(), 0, ww->pcmname);
429     ww->pcmname = NULL;
430
431     HeapFree(GetProcessHeap(), 0, ww->ctlname);
432     ww->ctlname = NULL;
433 }
434
435 /*----------------------------------------------------------------------------
436 **  ALSA_AddDeviceToArray
437 **
438 **      Dynamically size one of the wavein or waveout arrays of devices,
439 **  and add a fully configured device node to the array.
440 **
441 */
442 static int ALSA_AddDeviceToArray(WINE_WAVEDEV *ww, WINE_WAVEDEV **array,
443         DWORD *count, DWORD *alloced, int isdefault)
444 {
445     int i = *count;
446
447     if (*count >= *alloced)
448     {
449         (*alloced) += WAVEDEV_ALLOC_EXTENT_SIZE;
450         if (! (*array))
451             *array = HeapAlloc(GetProcessHeap(), 0, sizeof(*ww) * (*alloced));
452         else
453             *array = HeapReAlloc(GetProcessHeap(), 0, *array, sizeof(*ww) * (*alloced));
454
455         if (!*array)
456         {
457             return -1;
458         }
459     }
460
461     /* If this is the default, arrange for it to be the first element */
462     if (isdefault && i > 0)
463     {
464         (*array)[*count] = (*array)[0];
465         i = 0;
466     }
467
468     (*array)[i] = *ww;
469
470     (*count)++;
471     return 0;
472 }
473
474 /*----------------------------------------------------------------------------
475 **  ALSA_AddPlaybackDevice
476 **
477 **      Add a given Alsa device to Wine's internal list of Playback
478 **  devices.
479 */
480 static int ALSA_AddPlaybackDevice(snd_ctl_t *ctl, snd_pcm_t *pcm, const char *pcmname, int isdefault)
481 {
482     WINE_WAVEDEV    wwo;
483     int rc;
484
485     memset(&wwo, '\0', sizeof(wwo));
486
487     rc = ALSA_AddCommonDevice(ctl, pcm, pcmname, &wwo);
488     if (rc)
489         return(rc);
490
491     MultiByteToWideChar(CP_UNIXCP, 0, wwo.ds_desc.szDesc, -1,
492                         wwo.outcaps.szPname, sizeof(wwo.outcaps.szPname)/sizeof(WCHAR));
493     wwo.outcaps.szPname[sizeof(wwo.outcaps.szPname)/sizeof(WCHAR) - 1] = '\0';
494
495     wwo.outcaps.wMid = MM_CREATIVE;
496     wwo.outcaps.wPid = MM_CREATIVE_SBP16_WAVEOUT;
497     wwo.outcaps.vDriverVersion = 0x0100;
498
499     rc = ALSA_ComputeCaps(ctl, pcm, &wwo.outcaps.wChannels, &wwo.ds_caps.dwFlags,
500             &wwo.outcaps.dwFormats, &wwo.outcaps.dwSupport);
501     if (rc)
502     {
503         WARN("Error calculating device caps for pcm [%s]\n", wwo.pcmname);
504         ALSA_FreeDevice(&wwo);
505         return(rc);
506     }
507
508     rc = ALSA_AddDeviceToArray(&wwo, &WOutDev, &ALSA_WodNumDevs, &ALSA_WodNumMallocedDevs, isdefault);
509     if (rc)
510         ALSA_FreeDevice(&wwo);
511     return (rc);
512 }
513
514 /*----------------------------------------------------------------------------
515 **  ALSA_AddCaptureDevice
516 **
517 **      Add a given Alsa device to Wine's internal list of Capture
518 **  devices.
519 */
520 static int ALSA_AddCaptureDevice(snd_ctl_t *ctl, snd_pcm_t *pcm, const char *pcmname, int isdefault)
521 {
522     WINE_WAVEDEV    wwi;
523     int rc;
524
525     memset(&wwi, '\0', sizeof(wwi));
526
527     rc = ALSA_AddCommonDevice(ctl, pcm, pcmname, &wwi);
528     if (rc)
529         return(rc);
530
531     MultiByteToWideChar(CP_UNIXCP, 0, wwi.ds_desc.szDesc, -1,
532                         wwi.incaps.szPname, sizeof(wwi.incaps.szPname) / sizeof(WCHAR));
533     wwi.incaps.szPname[sizeof(wwi.incaps.szPname)/sizeof(WCHAR) - 1] = '\0';
534
535     wwi.incaps.wMid = MM_CREATIVE;
536     wwi.incaps.wPid = MM_CREATIVE_SBP16_WAVEOUT;
537     wwi.incaps.vDriverVersion = 0x0100;
538
539     rc = ALSA_ComputeCaps(ctl, pcm, &wwi.incaps.wChannels, &wwi.ds_caps.dwFlags,
540             &wwi.incaps.dwFormats, &wwi.dwSupport);
541     if (rc)
542     {
543         WARN("Error calculating device caps for pcm [%s]\n", wwi.pcmname);
544         ALSA_FreeDevice(&wwi);
545         return(rc);
546     }
547
548     rc = ALSA_AddDeviceToArray(&wwi, &WInDev, &ALSA_WidNumDevs, &ALSA_WidNumMallocedDevs, isdefault);
549     if (rc)
550         ALSA_FreeDevice(&wwi);
551     return(rc);
552 }
553
554 /*----------------------------------------------------------------------------
555 **  ALSA_CheckEnvironment
556 **
557 **      Given an Alsa style configuration node, scan its subitems
558 **  for environment variable names, and use them to find an override,
559 **  if appropriate.
560 **      This is essentially a long and convoluted way of doing:
561 **          getenv("ALSA_CARD")
562 **          getenv("ALSA_CTL_CARD")
563 **          getenv("ALSA_PCM_CARD")
564 **          getenv("ALSA_PCM_DEVICE")
565 **
566 **  The output value is set with the atoi() of the first environment
567 **  variable found to be set, if any; otherwise, it is left alone
568 */
569 static void ALSA_CheckEnvironment(snd_config_t *node, int *outvalue)
570 {
571     snd_config_iterator_t iter;
572
573     for (iter = snd_config_iterator_first(node);
574          iter != snd_config_iterator_end(node);
575          iter = snd_config_iterator_next(iter))
576     {
577         snd_config_t *leaf = snd_config_iterator_entry(iter);
578         if (snd_config_get_type(leaf) == SND_CONFIG_TYPE_STRING)
579         {
580             const char *value;
581             if (snd_config_get_string(leaf, &value) >= 0)
582             {
583                 char *p = getenv(value);
584                 if (p)
585                 {
586                     *outvalue = atoi(p);
587                     return;
588                 }
589             }
590         }
591     }
592 }
593
594 /*----------------------------------------------------------------------------
595 **  ALSA_DefaultDevices
596 **
597 **      Jump through Alsa style hoops to (hopefully) properly determine
598 **  Alsa defaults for CTL Card #, as well as for PCM Card + Device #.
599 **  We'll also find out if the user has set any of the environment
600 **  variables that specify we're to use a specific card or device.
601 **
602 **  Parameters:
603 **      directhw        Whether to use a direct hardware device or not;
604 **                      essentially switches the pcm device name from
605 **                      one of 'default:X' or 'plughw:X' to "hw:X"
606 **      defctlcard      If !NULL, will hold the ctl card number given
607 **                      by the ALSA config as the default
608 **      defpcmcard      If !NULL, default pcm card #
609 **      defpcmdev       If !NULL, default pcm device #
610 **      fixedctlcard    If !NULL, and the user set the appropriate
611 **                          environment variable, we'll set to the
612 **                          card the user specified.
613 **      fixedpcmcard    If !NULL, and the user set the appropriate
614 **                          environment variable, we'll set to the
615 **                          card the user specified.
616 **      fixedpcmdev     If !NULL, and the user set the appropriate
617 **                          environment variable, we'll set to the
618 **                          device the user specified.
619 **
620 **  Returns:  0 on success, < 0 on failure
621 */
622 static int ALSA_DefaultDevices(int directhw,
623             long *defctlcard,
624             long *defpcmcard, long *defpcmdev,
625             int *fixedctlcard,
626             int *fixedpcmcard, int *fixedpcmdev)
627 {
628     snd_config_t   *configp;
629     char pcmsearch[256];
630
631     ALSA_RETURN_ONFAIL(snd_config_update());
632
633     if (defctlcard)
634         if (snd_config_search(snd_config, "defaults.ctl.card", &configp) >= 0)
635             snd_config_get_integer(configp, defctlcard);
636
637     if (defpcmcard)
638         if (snd_config_search(snd_config, "defaults.pcm.card", &configp) >= 0)
639             snd_config_get_integer(configp, defpcmcard);
640
641     if (defpcmdev)
642         if (snd_config_search(snd_config, "defaults.pcm.device", &configp) >= 0)
643             snd_config_get_integer(configp, defpcmdev);
644
645
646     if (fixedctlcard)
647     {
648         if (snd_config_search(snd_config, "ctl.hw.@args.CARD.default.vars", &configp) >= 0)
649             ALSA_CheckEnvironment(configp, fixedctlcard);
650     }
651
652     if (fixedpcmcard)
653     {
654         sprintf(pcmsearch, "pcm.%s.@args.CARD.default.vars", directhw ? "hw" : "plughw");
655         if (snd_config_search(snd_config, pcmsearch, &configp) >= 0)
656             ALSA_CheckEnvironment(configp, fixedpcmcard);
657     }
658
659     if (fixedpcmdev)
660     {
661         sprintf(pcmsearch, "pcm.%s.@args.DEV.default.vars", directhw ? "hw" : "plughw");
662         if (snd_config_search(snd_config, pcmsearch, &configp) >= 0)
663             ALSA_CheckEnvironment(configp, fixedpcmdev);
664     }
665
666     return 0;
667 }
668
669
670 /*----------------------------------------------------------------------------
671 **  ALSA_ScanDevices
672 **
673 **      Iterate through all discoverable ALSA cards, searching
674 **  for usable PCM devices.
675 **
676 **  Parameters:
677 **      directhw        Whether to use a direct hardware device or not;
678 **                      essentially switches the pcm device name from
679 **                      one of 'default:X' or 'plughw:X' to "hw:X"
680 **      defctlcard      Alsa's notion of the default ctl card.
681 **      defpcmcard         . pcm card
682 **      defpcmdev          . pcm device
683 **      fixedctlcard    If not -1, then gives the value of ALSA_CTL_CARD
684 **                          or equivalent environment variable
685 **      fixedpcmcard    If not -1, then gives the value of ALSA_PCM_CARD
686 **                          or equivalent environment variable
687 **      fixedpcmdev     If not -1, then gives the value of ALSA_PCM_DEVICE
688 **                          or equivalent environment variable
689 **
690 **  Returns:  0 on success, < 0 on failure
691 */
692 static int ALSA_ScanDevices(int directhw,
693         long defctlcard, long defpcmcard, long defpcmdev,
694         int fixedctlcard, int fixedpcmcard, int fixedpcmdev)
695 {
696     int card = fixedpcmcard;
697     int scan_devices = (fixedpcmdev == -1);
698
699     /*------------------------------------------------------------------------
700     ** Loop through all available cards
701     **----------------------------------------------------------------------*/
702     if (card == -1)
703         snd_card_next(&card);
704
705     for (; card != -1; snd_card_next(&card))
706     {
707         char ctlname[256];
708         snd_ctl_t *ctl;
709         int rc;
710         int device;
711
712         /*--------------------------------------------------------------------
713         ** Try to open a ctl handle; Wine doesn't absolutely require one,
714         **  but it does allow for volume control and for device scanning
715         **------------------------------------------------------------------*/
716         sprintf(ctlname, "hw:%d", fixedctlcard == -1 ? card : fixedctlcard);
717         rc = snd_ctl_open(&ctl, ctlname, SND_CTL_NONBLOCK);
718         if (rc < 0)
719         {
720             ctl = NULL;
721             WARN("Unable to open an alsa ctl for [%s] (pcm card %d): %s; not scanning devices\n",
722                     ctlname, card, snd_strerror(rc));
723             if (fixedpcmdev == -1)
724                 fixedpcmdev = 0;
725         }
726
727         /*--------------------------------------------------------------------
728         ** Loop through all available devices on this card
729         **------------------------------------------------------------------*/
730         device = fixedpcmdev;
731         if (device == -1)
732             snd_ctl_pcm_next_device(ctl, &device);
733
734         for (; device != -1; snd_ctl_pcm_next_device(ctl, &device))
735         {
736             char defaultpcmname[256];
737             char plugpcmname[256];
738             char hwpcmname[256];
739             char *pcmname = NULL;
740             snd_pcm_t *pcm;
741
742             sprintf(defaultpcmname, "default");
743             sprintf(plugpcmname,    "plughw:%d,%d", card, device);
744             sprintf(hwpcmname,      "hw:%d,%d", card, device);
745
746             /*----------------------------------------------------------------
747             ** See if it's a valid playback device
748             **--------------------------------------------------------------*/
749             if (ALSA_TestDeviceForWine(card, device, SND_PCM_STREAM_PLAYBACK) == 0)
750             {
751                 /* If we can, try the default:X device name first */
752                 if (! scan_devices && ! directhw)
753                 {
754                     pcmname = defaultpcmname;
755                     rc = snd_pcm_open(&pcm, pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
756                 }
757                 else
758                     rc = -1;
759
760                 if (rc < 0)
761                 {
762                     pcmname = directhw ? hwpcmname : plugpcmname;
763                     rc = snd_pcm_open(&pcm, pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
764                 }
765
766                 if (rc >= 0)
767                 {
768                     if (defctlcard == card && defpcmcard == card && defpcmdev == device)
769                         ALSA_AddPlaybackDevice(ctl, pcm, pcmname, TRUE);
770                     else
771                         ALSA_AddPlaybackDevice(ctl, pcm, pcmname, FALSE);
772                     snd_pcm_close(pcm);
773                 }
774                 else
775                 {
776                     TRACE("Device [%s/%s] failed to open for playback: %s\n",
777                         directhw || scan_devices ? "(N/A)" : defaultpcmname,
778                         directhw ? hwpcmname : plugpcmname,
779                         snd_strerror(rc));
780                 }
781             }
782
783             /*----------------------------------------------------------------
784             ** See if it's a valid capture device
785             **--------------------------------------------------------------*/
786             if (ALSA_TestDeviceForWine(card, device, SND_PCM_STREAM_CAPTURE) == 0)
787             {
788                 /* If we can, try the default:X device name first */
789                 if (! scan_devices && ! directhw)
790                 {
791                     pcmname = defaultpcmname;
792                     rc = snd_pcm_open(&pcm, pcmname, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
793                 }
794                 else
795                     rc = -1;
796
797                 if (rc < 0)
798                 {
799                     pcmname = directhw ? hwpcmname : plugpcmname;
800                     rc = snd_pcm_open(&pcm, pcmname, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
801                 }
802
803                 if (rc >= 0)
804                 {
805                     if (defctlcard == card && defpcmcard == card && defpcmdev == device)
806                         ALSA_AddCaptureDevice(ctl, pcm, pcmname, TRUE);
807                     else
808                         ALSA_AddCaptureDevice(ctl, pcm, pcmname, FALSE);
809
810                     snd_pcm_close(pcm);
811                 }
812                 else
813                 {
814                     TRACE("Device [%s/%s] failed to open for capture: %s\n",
815                         directhw || scan_devices ? "(N/A)" : defaultpcmname,
816                         directhw ? hwpcmname : plugpcmname,
817                         snd_strerror(rc));
818                 }
819             }
820
821             if (! scan_devices)
822                 break;
823         }
824
825         if (ctl)
826             snd_ctl_close(ctl);
827
828         /*--------------------------------------------------------------------
829         ** If the user has set env variables such that we're pegged to
830         **  a specific card, then break after we've examined it
831         **------------------------------------------------------------------*/
832         if (fixedpcmcard != -1)
833             break;
834     }
835
836     return 0;
837
838 }
839
840 /*----------------------------------------------------------------------------
841 ** ALSA_PerformDefaultScan
842 **  Perform the basic default scanning for devices within ALSA.
843 **  The hope is that this routine implements a 'correct'
844 **  scanning algorithm from the Alsalib point of view.
845 **
846 **      Note that Wine, overall, has other mechanisms to
847 **  override and specify exact CTL and PCM device names,
848 **  but this routine is imagined as the default that
849 **  99% of users will use.
850 **
851 **      The basic algorithm is simple:
852 **  Use snd_card_next to iterate cards; within cards, use
853 **  snd_ctl_pcm_next_device to iterate through devices.
854 **
855 **      We add a little complexity by taking into consideration
856 **  environment variables such as ALSA_CARD (et all), and by
857 **  detecting when a given device matches the default specified
858 **  by Alsa.
859 **
860 **  Parameters:
861 **      directhw        If !0, indicates we should use the hw:X
862 **                      PCM interface, rather than first try
863 **                      the 'default' device followed by the plughw
864 **                      device.  (default and plughw do fancy mixing
865 **                      and audio scaling, if they are available).
866 **      devscan         If TRUE, we should scan all devices, not
867 **                      juse use device 0 on each card
868 **
869 **  Returns:
870 **      0   on success
871 **
872 **  Effects:
873 **      Invokes the ALSA_AddXXXDevice functions on valid
874 **  looking devices
875 */
876 static int ALSA_PerformDefaultScan(int directhw, BOOL devscan)
877 {
878     long defctlcard = -1, defpcmcard = -1, defpcmdev = -1;
879     int fixedctlcard = -1, fixedpcmcard = -1, fixedpcmdev = -1;
880     int rc;
881
882     /* FIXME:  We should dlsym the new snd_names_list/snd_names_list_free 1.0.9 apis,
883     **          and use them instead of this scan mechanism if they are present         */
884
885     rc = ALSA_DefaultDevices(directhw, &defctlcard, &defpcmcard, &defpcmdev,
886             &fixedctlcard, &fixedpcmcard, &fixedpcmdev);
887     if (rc)
888         return(rc);
889
890     if (fixedpcmdev == -1 && ! devscan)
891         fixedpcmdev = 0;
892
893     return(ALSA_ScanDevices(directhw, defctlcard, defpcmcard, defpcmdev, fixedctlcard, fixedpcmcard, fixedpcmdev));
894 }
895
896
897 /*----------------------------------------------------------------------------
898 ** ALSA_AddUserSpecifiedDevice
899 **  Add a device given from the registry
900 */
901 static int ALSA_AddUserSpecifiedDevice(const char *ctlname, const char *pcmname)
902 {
903     int rc;
904     int okay = 0;
905     snd_ctl_t *ctl = NULL;
906     snd_pcm_t *pcm = NULL;
907
908     if (ctlname)
909     {
910         rc = snd_ctl_open(&ctl, ctlname, SND_CTL_NONBLOCK);
911         if (rc < 0)
912             ctl = NULL;
913     }
914
915     rc = snd_pcm_open(&pcm, pcmname, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
916     if (rc >= 0)
917     {
918         ALSA_AddPlaybackDevice(ctl, pcm, pcmname, FALSE);
919         okay++;
920         snd_pcm_close(pcm);
921     }
922
923     rc = snd_pcm_open(&pcm, pcmname, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
924     if (rc >= 0)
925     {
926         ALSA_AddCaptureDevice(ctl, pcm, pcmname, FALSE);
927         okay++;
928         snd_pcm_close(pcm);
929     }
930
931     if (ctl)
932         snd_ctl_close(ctl);
933
934     return (okay == 0);
935 }
936
937
938 /*----------------------------------------------------------------------------
939 ** ALSA_WaveInit
940 **  Initialize the Wine Alsa sub system.
941 ** The main task is to probe for and store a list of all appropriate playback
942 ** and capture devices.
943 **  Key control points are from the registry key:
944 **  [Software\Wine\Alsa Driver]
945 **  AutoScanCards           Whether or not to scan all known sound cards
946 **                          and add them to Wine's list (default yes)
947 **  AutoScanDevices         Whether or not to scan all known PCM devices
948 **                          on each card (default no)
949 **  UseDirectHW             Whether or not to use the hw:X device,
950 **                          instead of the fancy default:X or plughw:X device.
951 **                          The hw:X device goes straight to the hardware
952 **                          without any fancy mixing or audio scaling in between.
953 **  DeviceCount             If present, specifies the number of hard coded
954 **                          Alsa devices to add to Wine's list; default 0
955 **  DevicePCMn              Specifies the Alsa PCM devices to open for
956 **                          Device n (where n goes from 1 to DeviceCount)
957 **  DeviceCTLn              Specifies the Alsa control devices to open for
958 **                          Device n (where n goes from 1 to DeviceCount)
959 **
960 **                          Using AutoScanCards no, and then Devicexxx info
961 **                          is a way to exactly specify the devices used by Wine.
962 **
963 */
964 void ALSA_WaveInit(void)
965 {
966     DWORD rc;
967     BOOL  AutoScanCards = TRUE;
968     BOOL  AutoScanDevices = FALSE;
969     BOOL  UseDirectHW = FALSE;
970     DWORD DeviceCount = 0;
971     HKEY  key = 0;
972     int   i;
973     static int loaded;
974
975     if (loaded++)
976         return;
977
978     /* @@ Wine registry key: HKCU\Software\Wine\Alsa Driver */
979     rc = RegOpenKeyExA(HKEY_CURRENT_USER, "Software\\Wine\\Alsa Driver", 0, KEY_QUERY_VALUE, &key);
980     if (rc == ERROR_SUCCESS)
981     {
982         ALSA_RegGetBoolean(key, "AutoScanCards", &AutoScanCards);
983         ALSA_RegGetBoolean(key, "AutoScanDevices", &AutoScanDevices);
984         ALSA_RegGetBoolean(key, "UseDirectHW", &UseDirectHW);
985         ALSA_RegGetInt(key, "DeviceCount", &DeviceCount);
986     }
987
988     if (AutoScanCards)
989         ALSA_PerformDefaultScan(UseDirectHW, AutoScanDevices);
990
991     for (i = 0; i < DeviceCount; i++)
992     {
993         char *ctl_name = NULL;
994         char *pcm_name = NULL;
995         char value[30];
996
997         sprintf(value, "DevicePCM%d", i + 1);
998         if (ALSA_RegGetString(key, value, &pcm_name) == ERROR_SUCCESS)
999         {
1000             sprintf(value, "DeviceCTL%d", i + 1);
1001             ALSA_RegGetString(key, value, &ctl_name);
1002             ALSA_AddUserSpecifiedDevice(ctl_name, pcm_name);
1003         }
1004
1005         HeapFree(GetProcessHeap(), 0, ctl_name);
1006         HeapFree(GetProcessHeap(), 0, pcm_name);
1007     }
1008
1009     if (key)
1010         RegCloseKey(key);
1011 }