599079cada78ad760fd630110b2eb95fe2d50fda
[platform/upstream/pulseaudio.git] / src / modules / alsa / alsa-util.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2004-2006 Lennart Poettering
5   Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
6
7   PulseAudio is free software; you can redistribute it and/or modify
8   it under the terms of the GNU Lesser General Public License as published
9   by the Free Software Foundation; either version 2 of the License,
10   or (at your option) any later version.
11
12   PulseAudio is distributed in the hope that it will be useful, but
13   WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   General Public License for more details.
16
17   You should have received a copy of the GNU Lesser General Public License
18   along with PulseAudio; if not, write to the Free Software
19   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20   USA.
21 ***/
22
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26
27 #include <sys/types.h>
28 #include <limits.h>
29 #include <asoundlib.h>
30
31 #include <pulse/sample.h>
32 #include <pulse/xmalloc.h>
33 #include <pulse/timeval.h>
34
35 #include <pulsecore/log.h>
36 #include <pulsecore/macro.h>
37 #include <pulsecore/core-util.h>
38 #include <pulsecore/atomic.h>
39
40 #include "alsa-util.h"
41
42 struct pa_alsa_fdlist {
43     unsigned num_fds;
44     struct pollfd *fds;
45     /* This is a temporary buffer used to avoid lots of mallocs */
46     struct pollfd *work_fds;
47
48     snd_mixer_t *mixer;
49
50     pa_mainloop_api *m;
51     pa_defer_event *defer;
52     pa_io_event **ios;
53
54     pa_bool_t polled;
55
56     void (*cb)(void *userdata);
57     void *userdata;
58 };
59
60 static void io_cb(pa_mainloop_api*a, pa_io_event* e, int fd, pa_io_event_flags_t events, void *userdata) {
61
62     struct pa_alsa_fdlist *fdl = userdata;
63     int err;
64     unsigned i;
65     unsigned short revents;
66
67     pa_assert(a);
68     pa_assert(fdl);
69     pa_assert(fdl->mixer);
70     pa_assert(fdl->fds);
71     pa_assert(fdl->work_fds);
72
73     if (fdl->polled)
74         return;
75
76     fdl->polled = TRUE;
77
78     memcpy(fdl->work_fds, fdl->fds, sizeof(struct pollfd) * fdl->num_fds);
79
80     for (i = 0; i < fdl->num_fds; i++) {
81         if (e == fdl->ios[i]) {
82             if (events & PA_IO_EVENT_INPUT)
83                 fdl->work_fds[i].revents |= POLLIN;
84             if (events & PA_IO_EVENT_OUTPUT)
85                 fdl->work_fds[i].revents |= POLLOUT;
86             if (events & PA_IO_EVENT_ERROR)
87                 fdl->work_fds[i].revents |= POLLERR;
88             if (events & PA_IO_EVENT_HANGUP)
89                 fdl->work_fds[i].revents |= POLLHUP;
90             break;
91         }
92     }
93
94     pa_assert(i != fdl->num_fds);
95
96     if ((err = snd_mixer_poll_descriptors_revents(fdl->mixer, fdl->work_fds, fdl->num_fds, &revents)) < 0) {
97         pa_log_error("Unable to get poll revent: %s", snd_strerror(err));
98         return;
99     }
100
101     a->defer_enable(fdl->defer, 1);
102
103     if (revents)
104         snd_mixer_handle_events(fdl->mixer);
105 }
106
107 static void defer_cb(pa_mainloop_api*a, pa_defer_event* e, void *userdata) {
108     struct pa_alsa_fdlist *fdl = userdata;
109     unsigned num_fds, i;
110     int err;
111     struct pollfd *temp;
112
113     pa_assert(a);
114     pa_assert(fdl);
115     pa_assert(fdl->mixer);
116
117     a->defer_enable(fdl->defer, 0);
118
119     num_fds = (unsigned) snd_mixer_poll_descriptors_count(fdl->mixer);
120
121     if (num_fds != fdl->num_fds) {
122         if (fdl->fds)
123             pa_xfree(fdl->fds);
124         if (fdl->work_fds)
125             pa_xfree(fdl->work_fds);
126         fdl->fds = pa_xnew0(struct pollfd, num_fds);
127         fdl->work_fds = pa_xnew(struct pollfd, num_fds);
128     }
129
130     memset(fdl->work_fds, 0, sizeof(struct pollfd) * num_fds);
131
132     if ((err = snd_mixer_poll_descriptors(fdl->mixer, fdl->work_fds, num_fds)) < 0) {
133         pa_log_error("Unable to get poll descriptors: %s", snd_strerror(err));
134         return;
135     }
136
137     fdl->polled = FALSE;
138
139     if (memcmp(fdl->fds, fdl->work_fds, sizeof(struct pollfd) * num_fds) == 0)
140         return;
141
142     if (fdl->ios) {
143         for (i = 0; i < fdl->num_fds; i++)
144             a->io_free(fdl->ios[i]);
145
146         if (num_fds != fdl->num_fds) {
147             pa_xfree(fdl->ios);
148             fdl->ios = NULL;
149         }
150     }
151
152     if (!fdl->ios)
153         fdl->ios = pa_xnew(pa_io_event*, num_fds);
154
155     /* Swap pointers */
156     temp = fdl->work_fds;
157     fdl->work_fds = fdl->fds;
158     fdl->fds = temp;
159
160     fdl->num_fds = num_fds;
161
162     for (i = 0;i < num_fds;i++)
163         fdl->ios[i] = a->io_new(a, fdl->fds[i].fd,
164             ((fdl->fds[i].events & POLLIN) ? PA_IO_EVENT_INPUT : 0) |
165             ((fdl->fds[i].events & POLLOUT) ? PA_IO_EVENT_OUTPUT : 0),
166             io_cb, fdl);
167 }
168
169 struct pa_alsa_fdlist *pa_alsa_fdlist_new(void) {
170     struct pa_alsa_fdlist *fdl;
171
172     fdl = pa_xnew0(struct pa_alsa_fdlist, 1);
173
174     fdl->num_fds = 0;
175     fdl->fds = NULL;
176     fdl->work_fds = NULL;
177     fdl->mixer = NULL;
178     fdl->m = NULL;
179     fdl->defer = NULL;
180     fdl->ios = NULL;
181     fdl->polled = FALSE;
182
183     return fdl;
184 }
185
186 void pa_alsa_fdlist_free(struct pa_alsa_fdlist *fdl) {
187     pa_assert(fdl);
188
189     if (fdl->defer) {
190         pa_assert(fdl->m);
191         fdl->m->defer_free(fdl->defer);
192     }
193
194     if (fdl->ios) {
195         unsigned i;
196         pa_assert(fdl->m);
197         for (i = 0; i < fdl->num_fds; i++)
198             fdl->m->io_free(fdl->ios[i]);
199         pa_xfree(fdl->ios);
200     }
201
202     if (fdl->fds)
203         pa_xfree(fdl->fds);
204     if (fdl->work_fds)
205         pa_xfree(fdl->work_fds);
206
207     pa_xfree(fdl);
208 }
209
210 int pa_alsa_fdlist_set_mixer(struct pa_alsa_fdlist *fdl, snd_mixer_t *mixer_handle, pa_mainloop_api* m) {
211     pa_assert(fdl);
212     pa_assert(mixer_handle);
213     pa_assert(m);
214     pa_assert(!fdl->m);
215
216     fdl->mixer = mixer_handle;
217     fdl->m = m;
218     fdl->defer = m->defer_new(m, defer_cb, fdl);
219
220     return 0;
221 }
222
223 static int set_format(snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hwparams, pa_sample_format_t *f) {
224
225     static const snd_pcm_format_t format_trans[] = {
226         [PA_SAMPLE_U8] = SND_PCM_FORMAT_U8,
227         [PA_SAMPLE_ALAW] = SND_PCM_FORMAT_A_LAW,
228         [PA_SAMPLE_ULAW] = SND_PCM_FORMAT_MU_LAW,
229         [PA_SAMPLE_S16LE] = SND_PCM_FORMAT_S16_LE,
230         [PA_SAMPLE_S16BE] = SND_PCM_FORMAT_S16_BE,
231         [PA_SAMPLE_FLOAT32LE] = SND_PCM_FORMAT_FLOAT_LE,
232         [PA_SAMPLE_FLOAT32BE] = SND_PCM_FORMAT_FLOAT_BE,
233         [PA_SAMPLE_S32LE] = SND_PCM_FORMAT_S32_LE,
234         [PA_SAMPLE_S32BE] = SND_PCM_FORMAT_S32_BE,
235         [PA_SAMPLE_S24LE] = SND_PCM_FORMAT_S24_3LE,
236         [PA_SAMPLE_S24BE] = SND_PCM_FORMAT_S24_3BE,
237         [PA_SAMPLE_S24_32LE] = SND_PCM_FORMAT_S24_LE,
238         [PA_SAMPLE_S24_32BE] = SND_PCM_FORMAT_S24_BE,
239     };
240
241     static const pa_sample_format_t try_order[] = {
242         PA_SAMPLE_FLOAT32NE,
243         PA_SAMPLE_FLOAT32RE,
244         PA_SAMPLE_S32NE,
245         PA_SAMPLE_S32RE,
246         PA_SAMPLE_S24_32NE,
247         PA_SAMPLE_S24_32RE,
248         PA_SAMPLE_S24NE,
249         PA_SAMPLE_S24RE,
250         PA_SAMPLE_S16NE,
251         PA_SAMPLE_S16RE,
252         PA_SAMPLE_ALAW,
253         PA_SAMPLE_ULAW,
254         PA_SAMPLE_U8,
255         PA_SAMPLE_INVALID
256     };
257
258     int i, ret;
259
260     pa_assert(pcm_handle);
261     pa_assert(f);
262
263     if ((ret = snd_pcm_hw_params_set_format(pcm_handle, hwparams, format_trans[*f])) >= 0)
264         return ret;
265
266     if (*f == PA_SAMPLE_FLOAT32BE)
267         *f = PA_SAMPLE_FLOAT32LE;
268     else if (*f == PA_SAMPLE_FLOAT32LE)
269         *f = PA_SAMPLE_FLOAT32BE;
270     else if (*f == PA_SAMPLE_S24BE)
271         *f = PA_SAMPLE_S24LE;
272     else if (*f == PA_SAMPLE_S24LE)
273         *f = PA_SAMPLE_S24BE;
274     else if (*f == PA_SAMPLE_S24_32BE)
275         *f = PA_SAMPLE_S24_32LE;
276     else if (*f == PA_SAMPLE_S24_32LE)
277         *f = PA_SAMPLE_S24_32BE;
278     else if (*f == PA_SAMPLE_S16BE)
279         *f = PA_SAMPLE_S16LE;
280     else if (*f == PA_SAMPLE_S16LE)
281         *f = PA_SAMPLE_S16BE;
282     else if (*f == PA_SAMPLE_S32BE)
283         *f = PA_SAMPLE_S32LE;
284     else if (*f == PA_SAMPLE_S32LE)
285         *f = PA_SAMPLE_S32BE;
286     else
287         goto try_auto;
288
289     if ((ret = snd_pcm_hw_params_set_format(pcm_handle, hwparams, format_trans[*f])) >= 0)
290         return ret;
291
292 try_auto:
293
294     for (i = 0; try_order[i] != PA_SAMPLE_INVALID; i++) {
295         *f = try_order[i];
296
297         if ((ret = snd_pcm_hw_params_set_format(pcm_handle, hwparams, format_trans[*f])) >= 0)
298             return ret;
299     }
300
301     return -1;
302 }
303
304 /* Set the hardware parameters of the given ALSA device. Returns the
305  * selected fragment settings in *period and *period_size */
306 int pa_alsa_set_hw_params(
307         snd_pcm_t *pcm_handle,
308         pa_sample_spec *ss,
309         uint32_t *periods,
310         snd_pcm_uframes_t *period_size,
311         snd_pcm_uframes_t tsched_size,
312         pa_bool_t *use_mmap,
313         pa_bool_t *use_tsched,
314         pa_bool_t require_exact_channel_number) {
315
316     int ret = -1;
317     snd_pcm_uframes_t _period_size = period_size ? *period_size : 0;
318     unsigned int _periods = periods ? *periods : 0;
319     snd_pcm_uframes_t buffer_size;
320     unsigned int r = ss->rate;
321     unsigned int c = ss->channels;
322     pa_sample_format_t f = ss->format;
323     snd_pcm_hw_params_t *hwparams;
324     pa_bool_t _use_mmap = use_mmap && *use_mmap;
325     pa_bool_t _use_tsched = use_tsched && *use_tsched;
326     int dir;
327
328     pa_assert(pcm_handle);
329     pa_assert(ss);
330
331     snd_pcm_hw_params_alloca(&hwparams);
332
333     if ((ret = snd_pcm_hw_params_any(pcm_handle, hwparams)) < 0)
334         goto finish;
335
336     if ((ret = snd_pcm_hw_params_set_rate_resample(pcm_handle, hwparams, 0)) < 0)
337         goto finish;
338
339     if (_use_mmap) {
340         if ((ret = snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_MMAP_INTERLEAVED)) < 0) {
341
342             /* mmap() didn't work, fall back to interleaved */
343
344             if ((ret = snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
345                 goto finish;
346
347             _use_mmap = FALSE;
348         }
349
350     } else if ((ret = snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
351         goto finish;
352
353     if (!_use_mmap)
354         _use_tsched = FALSE;
355
356     if ((ret = set_format(pcm_handle, hwparams, &f)) < 0)
357         goto finish;
358
359     if ((ret = snd_pcm_hw_params_set_rate_near(pcm_handle, hwparams, &r, NULL)) < 0)
360         goto finish;
361
362     if (require_exact_channel_number) {
363         if ((ret = snd_pcm_hw_params_set_channels(pcm_handle, hwparams, c)) < 0)
364             goto finish;
365     } else {
366         if ((ret = snd_pcm_hw_params_set_channels_near(pcm_handle, hwparams, &c)) < 0)
367             goto finish;
368     }
369
370     if ((ret = snd_pcm_hw_params_set_periods_integer(pcm_handle, hwparams)) < 0)
371         goto finish;
372
373     if (_period_size && tsched_size && _periods) {
374         /* Adjust the buffer sizes, if we didn't get the rate we were asking for */
375         _period_size = (snd_pcm_uframes_t) (((uint64_t) _period_size * r) / ss->rate);
376         tsched_size = (snd_pcm_uframes_t) (((uint64_t) tsched_size * r) / ss->rate);
377
378         if (_use_tsched) {
379             _period_size = tsched_size;
380             _periods = 1;
381
382             pa_assert_se(snd_pcm_hw_params_get_buffer_size_max(hwparams, &buffer_size) == 0);
383             pa_log_debug("Maximum hw buffer size is %u ms", (unsigned) buffer_size * 1000 / r);
384         }
385
386         buffer_size = _periods * _period_size;
387
388         if (_periods > 0) {
389
390             /* First we pass 0 as direction to get exactly what we asked
391              * for. That this is necessary is presumably a bug in ALSA */
392
393             dir = 0;
394             if ((ret = snd_pcm_hw_params_set_periods_near(pcm_handle, hwparams, &_periods, &dir)) < 0) {
395                 dir = 1;
396                 if ((ret = snd_pcm_hw_params_set_periods_near(pcm_handle, hwparams, &_periods, &dir)) < 0) {
397                     dir = -1;
398                     if ((ret = snd_pcm_hw_params_set_periods_near(pcm_handle, hwparams, &_periods, &dir)) < 0)
399                         goto finish;
400                 }
401             }
402         }
403
404         if (_period_size > 0)
405             if ((ret = snd_pcm_hw_params_set_buffer_size_near(pcm_handle, hwparams, &buffer_size)) < 0)
406                 goto finish;
407     }
408
409     if  ((ret = snd_pcm_hw_params(pcm_handle, hwparams)) < 0)
410         goto finish;
411
412     if (ss->rate != r)
413         pa_log_info("Device %s doesn't support %u Hz, changed to %u Hz.", snd_pcm_name(pcm_handle), ss->rate, r);
414
415     if (ss->channels != c)
416         pa_log_info("Device %s doesn't support %u channels, changed to %u.", snd_pcm_name(pcm_handle), ss->channels, c);
417
418     if (ss->format != f)
419         pa_log_info("Device %s doesn't support sample format %s, changed to %s.", snd_pcm_name(pcm_handle), pa_sample_format_to_string(ss->format), pa_sample_format_to_string(f));
420
421     if ((ret = snd_pcm_prepare(pcm_handle)) < 0)
422         goto finish;
423
424     if ((ret = snd_pcm_hw_params_get_period_size(hwparams, &_period_size, &dir)) < 0 ||
425         (ret = snd_pcm_hw_params_get_periods(hwparams, &_periods, &dir)) < 0)
426         goto finish;
427
428     /* If the sample rate deviates too much, we need to resample */
429     if (r < ss->rate*.95 || r > ss->rate*1.05)
430         ss->rate = r;
431     ss->channels = (uint8_t) c;
432     ss->format = f;
433
434     pa_assert(_periods > 0);
435     pa_assert(_period_size > 0);
436
437     if (periods)
438         *periods = _periods;
439
440     if (period_size)
441         *period_size = _period_size;
442
443     if (use_mmap)
444         *use_mmap = _use_mmap;
445
446     if (use_tsched)
447         *use_tsched = _use_tsched;
448
449     ret = 0;
450
451     snd_pcm_nonblock(pcm_handle, 1);
452
453 finish:
454
455     return ret;
456 }
457
458 int pa_alsa_set_sw_params(snd_pcm_t *pcm, snd_pcm_uframes_t avail_min) {
459     snd_pcm_sw_params_t *swparams;
460     int err;
461
462     pa_assert(pcm);
463
464     snd_pcm_sw_params_alloca(&swparams);
465
466     if ((err = snd_pcm_sw_params_current(pcm, swparams) < 0)) {
467         pa_log_warn("Unable to determine current swparams: %s\n", snd_strerror(err));
468         return err;
469     }
470
471     if ((err = snd_pcm_sw_params_set_stop_threshold(pcm, swparams, (snd_pcm_uframes_t) -1)) < 0) {
472         pa_log_warn("Unable to set stop threshold: %s\n", snd_strerror(err));
473         return err;
474     }
475
476     if ((err = snd_pcm_sw_params_set_start_threshold(pcm, swparams, (snd_pcm_uframes_t) -1)) < 0) {
477         pa_log_warn("Unable to set start threshold: %s\n", snd_strerror(err));
478         return err;
479     }
480
481     if ((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, avail_min)) < 0) {
482         pa_log_error("snd_pcm_sw_params_set_avail_min() failed: %s", snd_strerror(err));
483         return err;
484     }
485
486     if ((err = snd_pcm_sw_params(pcm, swparams)) < 0) {
487         pa_log_warn("Unable to set sw params: %s\n", snd_strerror(err));
488         return err;
489     }
490
491     return 0;
492 }
493
494 static const struct pa_alsa_profile_info device_table[] = {
495     {{ 1, { PA_CHANNEL_POSITION_MONO }},
496      "hw",
497      "Analog Mono",
498      "analog-mono",
499      1 },
500
501     {{ 2, { PA_CHANNEL_POSITION_LEFT, PA_CHANNEL_POSITION_RIGHT }},
502      "front",
503      "Analog Stereo",
504      "analog-stereo",
505      10 },
506
507     {{ 2, { PA_CHANNEL_POSITION_LEFT, PA_CHANNEL_POSITION_RIGHT }},
508      "iec958",
509      "IEC958 Digital Stereo",
510      "iec958-stereo",
511      5 },
512
513     {{ 2, { PA_CHANNEL_POSITION_LEFT, PA_CHANNEL_POSITION_RIGHT }},
514      "hdmi",
515      "HDMI Digital Stereo",
516      "hdmi-stereo",
517      4 },
518
519     {{ 4, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
520             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT }},
521      "surround40",
522      "Analog Surround 4.0",
523      "analog-surround-40",
524      7 },
525
526     {{ 4, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
527             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT }},
528      "a52",
529      "IEC958/AC3 Digital Surround 4.0",
530      "iec958-ac3-surround-40",
531      2 },
532
533     {{ 5, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
534             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
535             PA_CHANNEL_POSITION_LFE }},
536      "surround41",
537      "Analog Surround 4.1",
538      "analog-surround-41",
539      7 },
540
541     {{ 5, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
542             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
543             PA_CHANNEL_POSITION_CENTER }},
544      "surround50",
545      "Analog Surround 5.0",
546      "analog-surround-50",
547      7 },
548
549     {{ 6, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
550             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
551             PA_CHANNEL_POSITION_CENTER, PA_CHANNEL_POSITION_LFE }},
552      "surround51",
553      "Analog Surround 5.1",
554      "analog-surround-51",
555      8 },
556
557     {{ 6, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_CENTER,
558             PA_CHANNEL_POSITION_FRONT_RIGHT, PA_CHANNEL_POSITION_REAR_LEFT,
559             PA_CHANNEL_POSITION_REAR_RIGHT, PA_CHANNEL_POSITION_LFE}},
560      "a52",
561      "IEC958/AC3 Digital Surround 5.1",
562      "iec958-ac3-surround-51",
563      3 },
564
565     {{ 8, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
566             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
567             PA_CHANNEL_POSITION_CENTER, PA_CHANNEL_POSITION_LFE,
568             PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT }},
569      "surround71",
570      "Analog Surround 7.1",
571      "analog-surround-71",
572      7 },
573
574     {{ 0, { 0 }}, NULL, NULL, NULL, 0 }
575 };
576
577 snd_pcm_t *pa_alsa_open_by_device_id_auto(
578         const char *dev_id,
579         char **dev,
580         pa_sample_spec *ss,
581         pa_channel_map* map,
582         int mode,
583         uint32_t *nfrags,
584         snd_pcm_uframes_t *period_size,
585         snd_pcm_uframes_t tsched_size,
586         pa_bool_t *use_mmap,
587         pa_bool_t *use_tsched,
588         const pa_alsa_profile_info **profile) {
589
590     int i;
591     int direction = 1;
592     char *d;
593     snd_pcm_t *pcm_handle;
594
595     pa_assert(dev_id);
596     pa_assert(dev);
597     pa_assert(ss);
598     pa_assert(map);
599     pa_assert(nfrags);
600     pa_assert(period_size);
601
602     /* First we try to find a device string with a superset of the
603      * requested channel map and open it without the plug: prefix. We
604      * iterate through our device table from top to bottom and take
605      * the first that matches. If we didn't find a working device that
606      * way, we iterate backwards, and check all devices that do not
607      * provide a superset of the requested channel map.*/
608
609     i = 0;
610     for (;;) {
611
612         if ((direction > 0) == pa_channel_map_superset(&device_table[i].map, map)) {
613             pa_sample_spec try_ss;
614
615             pa_log_debug("Checking for %s (%s)", device_table[i].name, device_table[i].alsa_name);
616
617             d = pa_sprintf_malloc("%s:%s", device_table[i].alsa_name, dev_id);
618
619             try_ss.channels = device_table[i].map.channels;
620             try_ss.rate = ss->rate;
621             try_ss.format = ss->format;
622
623             pcm_handle = pa_alsa_open_by_device_string(
624                     d,
625                     dev,
626                     &try_ss,
627                     map,
628                     mode,
629                     nfrags,
630                     period_size,
631                     tsched_size,
632                     use_mmap,
633                     use_tsched,
634                     TRUE);
635
636             pa_xfree(d);
637
638             if (pcm_handle) {
639
640                 *ss = try_ss;
641                 *map = device_table[i].map;
642                 pa_assert(map->channels == ss->channels);
643
644                 if (profile)
645                     *profile = &device_table[i];
646
647                 return pcm_handle;
648             }
649         }
650
651         if (direction > 0) {
652             if (!device_table[i+1].alsa_name) {
653                 /* OK, so we are at the end of our list. Let's turn
654                  * back. */
655                 direction = -1;
656             } else {
657                 /* We are not at the end of the list, so let's simply
658                  * try the next entry */
659                 i++;
660             }
661         }
662
663         if (direction < 0) {
664
665             if (device_table[i+1].alsa_name &&
666                 device_table[i].map.channels == device_table[i+1].map.channels) {
667
668                 /* OK, the next entry has the same number of channels,
669                  * let's try it */
670                 i++;
671
672             } else {
673                 /* Hmm, so the next entry does not have the same
674                  * number of channels, so let's go backwards until we
675                  * find the next entry with a differnt number of
676                  * channels */
677
678                 for (i--; i >= 0; i--)
679                     if (device_table[i].map.channels != device_table[i+1].map.channels)
680                         break;
681
682                 /* Hmm, there is no entry with a different number of
683                  * entries, then we're done */
684                 if (i < 0)
685                     break;
686
687                 /* OK, now lets find go back as long as we have the same number of channels */
688                 for (; i > 0; i--)
689                     if (device_table[i].map.channels != device_table[i-1].map.channels)
690                         break;
691             }
692         }
693     }
694
695     /* OK, we didn't find any good device, so let's try the raw plughw: stuff */
696
697     d = pa_sprintf_malloc("hw:%s", dev_id);
698     pa_log_debug("Trying %s as last resort...", d);
699     pcm_handle = pa_alsa_open_by_device_string(d, dev, ss, map, mode, nfrags, period_size, tsched_size, use_mmap, use_tsched, FALSE);
700     pa_xfree(d);
701
702     if (pcm_handle && profile)
703         *profile = NULL;
704
705     return pcm_handle;
706 }
707
708 snd_pcm_t *pa_alsa_open_by_device_id_profile(
709         const char *dev_id,
710         char **dev,
711         pa_sample_spec *ss,
712         pa_channel_map* map,
713         int mode,
714         uint32_t *nfrags,
715         snd_pcm_uframes_t *period_size,
716         snd_pcm_uframes_t tsched_size,
717         pa_bool_t *use_mmap,
718         pa_bool_t *use_tsched,
719         const pa_alsa_profile_info *profile) {
720
721     char *d;
722     snd_pcm_t *pcm_handle;
723     pa_sample_spec try_ss;
724
725     pa_assert(dev_id);
726     pa_assert(dev);
727     pa_assert(ss);
728     pa_assert(map);
729     pa_assert(nfrags);
730     pa_assert(period_size);
731     pa_assert(profile);
732
733     d = pa_sprintf_malloc("%s:%s", profile->alsa_name, dev_id);
734
735     try_ss.channels = profile->map.channels;
736     try_ss.rate = ss->rate;
737     try_ss.format = ss->format;
738
739     pcm_handle = pa_alsa_open_by_device_string(
740             d,
741             dev,
742             &try_ss,
743             map,
744             mode,
745             nfrags,
746             period_size,
747             tsched_size,
748             use_mmap,
749             use_tsched,
750             TRUE);
751
752     pa_xfree(d);
753
754     if (!pcm_handle)
755         return NULL;
756
757     *ss = try_ss;
758     *map = profile->map;
759     pa_assert(map->channels == ss->channels);
760
761     return pcm_handle;
762 }
763
764 snd_pcm_t *pa_alsa_open_by_device_string(
765         const char *device,
766         char **dev,
767         pa_sample_spec *ss,
768         pa_channel_map* map,
769         int mode,
770         uint32_t *nfrags,
771         snd_pcm_uframes_t *period_size,
772         snd_pcm_uframes_t tsched_size,
773         pa_bool_t *use_mmap,
774         pa_bool_t *use_tsched,
775         pa_bool_t require_exact_channel_number) {
776
777     int err;
778     char *d;
779     snd_pcm_t *pcm_handle;
780     pa_bool_t reformat = FALSE;
781
782     pa_assert(device);
783     pa_assert(ss);
784     pa_assert(map);
785
786     d = pa_xstrdup(device);
787
788     for (;;) {
789         pa_log_debug("Trying %s %s SND_PCM_NO_AUTO_FORMAT ...", d, reformat ? "without" : "with");
790
791         /* We don't pass SND_PCM_NONBLOCK here, since alsa-lib <=
792          * 1.0.17a would then ignore the SND_PCM_NO_xxx flags. Instead
793          * we enable nonblock mode afterwards via
794          * snd_pcm_nonblock(). Also see
795          * http://mailman.alsa-project.org/pipermail/alsa-devel/2008-August/010258.html */
796
797         if ((err = snd_pcm_open(&pcm_handle, d, mode,
798                                 /*SND_PCM_NONBLOCK|*/
799                                 SND_PCM_NO_AUTO_RESAMPLE|
800                                 SND_PCM_NO_AUTO_CHANNELS|
801                                 (reformat ? 0 : SND_PCM_NO_AUTO_FORMAT))) < 0) {
802             pa_log_info("Error opening PCM device %s: %s", d, snd_strerror(err));
803             pa_xfree(d);
804             return NULL;
805         }
806
807         if ((err = pa_alsa_set_hw_params(pcm_handle, ss, nfrags, period_size, tsched_size, use_mmap, use_tsched, require_exact_channel_number)) < 0) {
808
809             if (!reformat) {
810                 reformat = TRUE;
811
812                 snd_pcm_close(pcm_handle);
813                 continue;
814             }
815
816             /* Hmm, some hw is very exotic, so we retry with plug, if without it didn't work */
817
818             if (!pa_startswith(d, "plug:") && !pa_startswith(d, "plughw:")) {
819                 char *t;
820
821                 t = pa_sprintf_malloc("plug:%s", d);
822                 pa_xfree(d);
823                 d = t;
824
825                 reformat = FALSE;
826
827                 snd_pcm_close(pcm_handle);
828                 continue;
829             }
830
831             pa_log_info("Failed to set hardware parameters on %s: %s", d, snd_strerror(err));
832             pa_xfree(d);
833             snd_pcm_close(pcm_handle);
834             return NULL;
835         }
836
837         if (dev)
838             *dev = d;
839         else
840             pa_xfree(d);
841
842         if (ss->channels != map->channels)
843             pa_channel_map_init_extend(map, ss->channels, PA_CHANNEL_MAP_ALSA);
844
845         return pcm_handle;
846     }
847 }
848
849 int pa_alsa_probe_profiles(
850         const char *dev_id,
851         const pa_sample_spec *ss,
852         void (*cb)(const pa_alsa_profile_info *sink, const pa_alsa_profile_info *source, void *userdata),
853         void *userdata) {
854
855     const pa_alsa_profile_info *i;
856
857     pa_assert(dev_id);
858     pa_assert(ss);
859     pa_assert(cb);
860
861     /* We try each combination of playback/capture. We also try to
862      * open only for capture resp. only for sink. Don't get confused
863      * by the trailing entry in device_table we use for this! */
864
865     for (i = device_table; i < device_table + PA_ELEMENTSOF(device_table); i++) {
866         const pa_alsa_profile_info *j;
867         snd_pcm_t *pcm_i = NULL;
868
869         if (i->alsa_name) {
870             char *id;
871             pa_sample_spec try_ss;
872             pa_channel_map try_map;
873
874             pa_log_debug("Checking for playback on %s (%s)", i->name, i->alsa_name);
875             id = pa_sprintf_malloc("%s:%s", i->alsa_name, dev_id);
876
877             try_ss = *ss;
878             try_ss.channels = i->map.channels;
879             try_map = i->map;
880
881             pcm_i = pa_alsa_open_by_device_string(
882                     id, NULL,
883                     &try_ss, &try_map,
884                     SND_PCM_STREAM_PLAYBACK,
885                     NULL, NULL, 0, NULL, NULL,
886                     TRUE);
887
888             pa_xfree(id);
889
890             if (!pcm_i)
891                 continue;
892         }
893
894         for (j = device_table; j < device_table + PA_ELEMENTSOF(device_table); j++) {
895             snd_pcm_t *pcm_j = NULL;
896
897             if (j->alsa_name) {
898                 char *jd;
899                 pa_sample_spec try_ss;
900                 pa_channel_map try_map;
901
902                 pa_log_debug("Checking for capture on %s (%s)", j->name, j->alsa_name);
903                 jd = pa_sprintf_malloc("%s:%s", j->alsa_name, dev_id);
904
905                 try_ss = *ss;
906                 try_ss.channels = j->map.channels;
907                 try_map = j->map;
908
909                 pcm_j = pa_alsa_open_by_device_string(
910                         jd, NULL,
911                         &try_ss, &try_map,
912                         SND_PCM_STREAM_CAPTURE,
913                         NULL, NULL, 0, NULL, NULL,
914                         TRUE);
915
916                 pa_xfree(jd);
917
918                 if (!pcm_j)
919                     continue;
920             }
921
922             if (pcm_j)
923                 snd_pcm_close(pcm_j);
924
925             if (i->alsa_name || j->alsa_name)
926                 cb(i->alsa_name ? i : NULL,
927                    j->alsa_name ? j : NULL, userdata);
928         }
929
930         if (pcm_i)
931             snd_pcm_close(pcm_i);
932     }
933
934     return TRUE;
935 }
936
937 int pa_alsa_prepare_mixer(snd_mixer_t *mixer, const char *dev) {
938     int err;
939
940     pa_assert(mixer);
941     pa_assert(dev);
942
943     if ((err = snd_mixer_attach(mixer, dev)) < 0) {
944         pa_log_info("Unable to attach to mixer %s: %s", dev, snd_strerror(err));
945         return -1;
946     }
947
948     if ((err = snd_mixer_selem_register(mixer, NULL, NULL)) < 0) {
949         pa_log_warn("Unable to register mixer: %s", snd_strerror(err));
950         return -1;
951     }
952
953     if ((err = snd_mixer_load(mixer)) < 0) {
954         pa_log_warn("Unable to load mixer: %s", snd_strerror(err));
955         return -1;
956     }
957
958     pa_log_info("Successfully attached to mixer '%s'", dev);
959
960     return 0;
961 }
962
963 static pa_bool_t elem_has_volume(snd_mixer_elem_t *elem, pa_bool_t playback) {
964     pa_assert(elem);
965
966     if (playback && snd_mixer_selem_has_playback_volume(elem))
967         return TRUE;
968
969     if (!playback && snd_mixer_selem_has_capture_volume(elem))
970         return TRUE;
971
972     return FALSE;
973 }
974
975 static pa_bool_t elem_has_switch(snd_mixer_elem_t *elem, pa_bool_t playback) {
976     pa_assert(elem);
977
978     if (playback && snd_mixer_selem_has_playback_switch(elem))
979         return TRUE;
980
981     if (!playback && snd_mixer_selem_has_capture_switch(elem))
982         return TRUE;
983
984     return FALSE;
985 }
986
987 snd_mixer_elem_t *pa_alsa_find_elem(snd_mixer_t *mixer, const char *name, const char *fallback, pa_bool_t playback) {
988     snd_mixer_elem_t *elem = NULL, *fallback_elem = NULL;
989     snd_mixer_selem_id_t *sid = NULL;
990
991     snd_mixer_selem_id_alloca(&sid);
992
993     pa_assert(mixer);
994     pa_assert(name);
995
996     snd_mixer_selem_id_set_name(sid, name);
997
998     if ((elem = snd_mixer_find_selem(mixer, sid))) {
999
1000         if (elem_has_volume(elem, playback) &&
1001             elem_has_switch(elem, playback))
1002             goto success;
1003
1004         if (!elem_has_volume(elem, playback) &&
1005             !elem_has_switch(elem, playback))
1006             elem = NULL;
1007     }
1008
1009     pa_log_info("Cannot find mixer control \"%s\" or mixer control is no combination of switch/volume.", snd_mixer_selem_id_get_name(sid));
1010
1011     if (fallback) {
1012         snd_mixer_selem_id_set_name(sid, fallback);
1013
1014         if ((fallback_elem = snd_mixer_find_selem(mixer, sid))) {
1015
1016             if (elem_has_volume(fallback_elem, playback) &&
1017                 elem_has_switch(fallback_elem, playback)) {
1018                 elem = fallback_elem;
1019                 goto success;
1020             }
1021
1022             if (!elem_has_volume(fallback_elem, playback) &&
1023                 !elem_has_switch(fallback_elem, playback))
1024                 fallback_elem = NULL;
1025         }
1026
1027         pa_log_warn("Cannot find fallback mixer control \"%s\" or mixer control is no combination of switch/volume.", snd_mixer_selem_id_get_name(sid));
1028     }
1029
1030     if (elem && fallback_elem) {
1031
1032         /* Hmm, so we have both elements, but neither has both mute
1033          * and volume. Let's prefer the one with the volume */
1034
1035         if (elem_has_volume(elem, playback))
1036             goto success;
1037
1038         if (elem_has_volume(fallback_elem, playback)) {
1039             elem = fallback_elem;
1040             goto success;
1041         }
1042     }
1043
1044     if (!elem && fallback_elem)
1045         elem = fallback_elem;
1046
1047 success:
1048
1049     if (elem)
1050         pa_log_info("Using mixer control \"%s\".", snd_mixer_selem_id_get_name(sid));
1051
1052     return elem;
1053 }
1054
1055 static const snd_mixer_selem_channel_id_t alsa_channel_ids[PA_CHANNEL_POSITION_MAX] = {
1056     [PA_CHANNEL_POSITION_MONO] = SND_MIXER_SCHN_MONO, /* The ALSA name is just an alias! */
1057
1058     [PA_CHANNEL_POSITION_FRONT_CENTER] = SND_MIXER_SCHN_FRONT_CENTER,
1059     [PA_CHANNEL_POSITION_FRONT_LEFT] = SND_MIXER_SCHN_FRONT_LEFT,
1060     [PA_CHANNEL_POSITION_FRONT_RIGHT] = SND_MIXER_SCHN_FRONT_RIGHT,
1061
1062     [PA_CHANNEL_POSITION_REAR_CENTER] = SND_MIXER_SCHN_REAR_CENTER,
1063     [PA_CHANNEL_POSITION_REAR_LEFT] = SND_MIXER_SCHN_REAR_LEFT,
1064     [PA_CHANNEL_POSITION_REAR_RIGHT] = SND_MIXER_SCHN_REAR_RIGHT,
1065
1066     [PA_CHANNEL_POSITION_LFE] = SND_MIXER_SCHN_WOOFER,
1067
1068     [PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER] = SND_MIXER_SCHN_UNKNOWN,
1069     [PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER] = SND_MIXER_SCHN_UNKNOWN,
1070
1071     [PA_CHANNEL_POSITION_SIDE_LEFT] = SND_MIXER_SCHN_SIDE_LEFT,
1072     [PA_CHANNEL_POSITION_SIDE_RIGHT] = SND_MIXER_SCHN_SIDE_RIGHT,
1073
1074     [PA_CHANNEL_POSITION_AUX0] = SND_MIXER_SCHN_UNKNOWN,
1075     [PA_CHANNEL_POSITION_AUX1] = SND_MIXER_SCHN_UNKNOWN,
1076     [PA_CHANNEL_POSITION_AUX2] = SND_MIXER_SCHN_UNKNOWN,
1077     [PA_CHANNEL_POSITION_AUX3] = SND_MIXER_SCHN_UNKNOWN,
1078     [PA_CHANNEL_POSITION_AUX4] = SND_MIXER_SCHN_UNKNOWN,
1079     [PA_CHANNEL_POSITION_AUX5] = SND_MIXER_SCHN_UNKNOWN,
1080     [PA_CHANNEL_POSITION_AUX6] = SND_MIXER_SCHN_UNKNOWN,
1081     [PA_CHANNEL_POSITION_AUX7] = SND_MIXER_SCHN_UNKNOWN,
1082     [PA_CHANNEL_POSITION_AUX8] = SND_MIXER_SCHN_UNKNOWN,
1083     [PA_CHANNEL_POSITION_AUX9] =  SND_MIXER_SCHN_UNKNOWN,
1084     [PA_CHANNEL_POSITION_AUX10] = SND_MIXER_SCHN_UNKNOWN,
1085     [PA_CHANNEL_POSITION_AUX11] = SND_MIXER_SCHN_UNKNOWN,
1086     [PA_CHANNEL_POSITION_AUX12] = SND_MIXER_SCHN_UNKNOWN,
1087     [PA_CHANNEL_POSITION_AUX13] = SND_MIXER_SCHN_UNKNOWN,
1088     [PA_CHANNEL_POSITION_AUX14] = SND_MIXER_SCHN_UNKNOWN,
1089     [PA_CHANNEL_POSITION_AUX15] = SND_MIXER_SCHN_UNKNOWN,
1090     [PA_CHANNEL_POSITION_AUX16] = SND_MIXER_SCHN_UNKNOWN,
1091     [PA_CHANNEL_POSITION_AUX17] = SND_MIXER_SCHN_UNKNOWN,
1092     [PA_CHANNEL_POSITION_AUX18] = SND_MIXER_SCHN_UNKNOWN,
1093     [PA_CHANNEL_POSITION_AUX19] = SND_MIXER_SCHN_UNKNOWN,
1094     [PA_CHANNEL_POSITION_AUX20] = SND_MIXER_SCHN_UNKNOWN,
1095     [PA_CHANNEL_POSITION_AUX21] = SND_MIXER_SCHN_UNKNOWN,
1096     [PA_CHANNEL_POSITION_AUX22] = SND_MIXER_SCHN_UNKNOWN,
1097     [PA_CHANNEL_POSITION_AUX23] = SND_MIXER_SCHN_UNKNOWN,
1098     [PA_CHANNEL_POSITION_AUX24] = SND_MIXER_SCHN_UNKNOWN,
1099     [PA_CHANNEL_POSITION_AUX25] = SND_MIXER_SCHN_UNKNOWN,
1100     [PA_CHANNEL_POSITION_AUX26] = SND_MIXER_SCHN_UNKNOWN,
1101     [PA_CHANNEL_POSITION_AUX27] = SND_MIXER_SCHN_UNKNOWN,
1102     [PA_CHANNEL_POSITION_AUX28] = SND_MIXER_SCHN_UNKNOWN,
1103     [PA_CHANNEL_POSITION_AUX29] = SND_MIXER_SCHN_UNKNOWN,
1104     [PA_CHANNEL_POSITION_AUX30] = SND_MIXER_SCHN_UNKNOWN,
1105     [PA_CHANNEL_POSITION_AUX31] = SND_MIXER_SCHN_UNKNOWN,
1106
1107     [PA_CHANNEL_POSITION_TOP_CENTER] = SND_MIXER_SCHN_UNKNOWN,
1108
1109     [PA_CHANNEL_POSITION_TOP_FRONT_CENTER] = SND_MIXER_SCHN_UNKNOWN,
1110     [PA_CHANNEL_POSITION_TOP_FRONT_LEFT] = SND_MIXER_SCHN_UNKNOWN,
1111     [PA_CHANNEL_POSITION_TOP_FRONT_RIGHT] = SND_MIXER_SCHN_UNKNOWN,
1112
1113     [PA_CHANNEL_POSITION_TOP_REAR_CENTER] = SND_MIXER_SCHN_UNKNOWN,
1114     [PA_CHANNEL_POSITION_TOP_REAR_LEFT] = SND_MIXER_SCHN_UNKNOWN,
1115     [PA_CHANNEL_POSITION_TOP_REAR_RIGHT] = SND_MIXER_SCHN_UNKNOWN
1116 };
1117
1118
1119 int pa_alsa_calc_mixer_map(snd_mixer_elem_t *elem, const pa_channel_map *channel_map, snd_mixer_selem_channel_id_t mixer_map[], pa_bool_t playback) {
1120     unsigned i;
1121     pa_bool_t alsa_channel_used[SND_MIXER_SCHN_LAST];
1122     pa_bool_t mono_used = FALSE;
1123
1124     pa_assert(elem);
1125     pa_assert(channel_map);
1126     pa_assert(mixer_map);
1127
1128     memset(&alsa_channel_used, 0, sizeof(alsa_channel_used));
1129
1130     if (channel_map->channels > 1 &&
1131         ((playback && snd_mixer_selem_has_playback_volume_joined(elem)) ||
1132          (!playback && snd_mixer_selem_has_capture_volume_joined(elem)))) {
1133         pa_log_info("ALSA device lacks independant volume controls for each channel.");
1134         return -1;
1135     }
1136
1137     for (i = 0; i < channel_map->channels; i++) {
1138         snd_mixer_selem_channel_id_t id;
1139         pa_bool_t is_mono;
1140
1141         is_mono = channel_map->map[i] == PA_CHANNEL_POSITION_MONO;
1142         id = alsa_channel_ids[channel_map->map[i]];
1143
1144         if (!is_mono && id == SND_MIXER_SCHN_UNKNOWN) {
1145             pa_log_info("Configured channel map contains channel '%s' that is unknown to the ALSA mixer.", pa_channel_position_to_string(channel_map->map[i]));
1146             return -1;
1147         }
1148
1149         if ((is_mono && mono_used) || (!is_mono && alsa_channel_used[id])) {
1150             pa_log_info("Channel map has duplicate channel '%s', falling back to software volume control.", pa_channel_position_to_string(channel_map->map[i]));
1151             return -1;
1152         }
1153
1154         if ((playback && (!snd_mixer_selem_has_playback_channel(elem, id) || (is_mono && !snd_mixer_selem_is_playback_mono(elem)))) ||
1155             (!playback && (!snd_mixer_selem_has_capture_channel(elem, id) || (is_mono && !snd_mixer_selem_is_capture_mono(elem))))) {
1156
1157             pa_log_info("ALSA device lacks separate volumes control for channel '%s'", pa_channel_position_to_string(channel_map->map[i]));
1158             return -1;
1159         }
1160
1161         if (is_mono) {
1162             mixer_map[i] = SND_MIXER_SCHN_MONO;
1163             mono_used = TRUE;
1164         } else {
1165             mixer_map[i] = id;
1166             alsa_channel_used[id] = TRUE;
1167         }
1168     }
1169
1170     pa_log_info("All %u channels can be mapped to mixer channels.", channel_map->channels);
1171
1172     return 0;
1173 }
1174
1175 void pa_alsa_dump(snd_pcm_t *pcm) {
1176     int err;
1177     snd_output_t *out;
1178
1179     pa_assert(pcm);
1180
1181     pa_assert_se(snd_output_buffer_open(&out) == 0);
1182
1183     if ((err = snd_pcm_dump(pcm, out)) < 0)
1184         pa_log_debug("snd_pcm_dump(): %s", snd_strerror(err));
1185     else {
1186         char *s = NULL;
1187         snd_output_buffer_string(out, &s);
1188         pa_log_debug("snd_pcm_dump():\n%s", pa_strnull(s));
1189     }
1190
1191     pa_assert_se(snd_output_close(out) == 0);
1192 }
1193
1194 void pa_alsa_dump_status(snd_pcm_t *pcm) {
1195     int err;
1196     snd_output_t *out;
1197     snd_pcm_status_t *status;
1198
1199     pa_assert(pcm);
1200
1201     snd_pcm_status_alloca(&status);
1202
1203     pa_assert_se(snd_output_buffer_open(&out) == 0);
1204
1205     pa_assert_se(snd_pcm_status(pcm, status) == 0);
1206
1207     if ((err = snd_pcm_status_dump(status, out)) < 0)
1208         pa_log_debug("snd_pcm_dump(): %s", snd_strerror(err));
1209     else {
1210         char *s = NULL;
1211         snd_output_buffer_string(out, &s);
1212         pa_log_debug("snd_pcm_dump():\n%s", pa_strnull(s));
1213     }
1214
1215     pa_assert_se(snd_output_close(out) == 0);
1216 }
1217
1218 static void alsa_error_handler(const char *file, int line, const char *function, int err, const char *fmt,...) {
1219     va_list ap;
1220     char *alsa_file;
1221
1222     alsa_file = pa_sprintf_malloc("(alsa-lib)%s", file);
1223
1224     va_start(ap, fmt);
1225
1226     pa_log_levelv_meta(PA_LOG_INFO, alsa_file, line, function, fmt, ap);
1227
1228     va_end(ap);
1229
1230     pa_xfree(alsa_file);
1231 }
1232
1233 static pa_atomic_t n_error_handler_installed = PA_ATOMIC_INIT(0);
1234
1235 void pa_alsa_redirect_errors_inc(void) {
1236     /* This is not really thread safe, but we do our best */
1237
1238     if (pa_atomic_inc(&n_error_handler_installed) == 0)
1239         snd_lib_error_set_handler(alsa_error_handler);
1240 }
1241
1242 void pa_alsa_redirect_errors_dec(void) {
1243     int r;
1244
1245     pa_assert_se((r = pa_atomic_dec(&n_error_handler_installed)) >= 1);
1246
1247     if (r == 1)
1248         snd_lib_error_set_handler(NULL);
1249 }
1250
1251 void pa_alsa_init_proplist_card(pa_proplist *p, int card) {
1252     char *cn, *lcn;
1253
1254     pa_assert(p);
1255     pa_assert(card >= 0);
1256
1257     pa_proplist_setf(p, "alsa.card", "%i", card);
1258
1259     if (snd_card_get_name(card, &cn) >= 0) {
1260         pa_proplist_sets(p, "alsa.card_name", cn);
1261         free(cn);
1262     }
1263
1264     if (snd_card_get_longname(card, &lcn) >= 0) {
1265         pa_proplist_sets(p, "alsa.long_card_name", lcn);
1266         free(lcn);
1267     }
1268 }
1269
1270 void pa_alsa_init_proplist_pcm(pa_proplist *p, snd_pcm_info_t *pcm_info) {
1271
1272     static const char * const alsa_class_table[SND_PCM_CLASS_LAST+1] = {
1273         [SND_PCM_CLASS_GENERIC] = "generic",
1274         [SND_PCM_CLASS_MULTI] = "multi",
1275         [SND_PCM_CLASS_MODEM] = "modem",
1276         [SND_PCM_CLASS_DIGITIZER] = "digitizer"
1277     };
1278     static const char * const class_table[SND_PCM_CLASS_LAST+1] = {
1279         [SND_PCM_CLASS_GENERIC] = "sound",
1280         [SND_PCM_CLASS_MULTI] = NULL,
1281         [SND_PCM_CLASS_MODEM] = "modem",
1282         [SND_PCM_CLASS_DIGITIZER] = NULL
1283     };
1284     static const char * const alsa_subclass_table[SND_PCM_SUBCLASS_LAST+1] = {
1285         [SND_PCM_SUBCLASS_GENERIC_MIX] = "generic-mix",
1286         [SND_PCM_SUBCLASS_MULTI_MIX] = "multi-mix"
1287     };
1288
1289     snd_pcm_class_t class;
1290     snd_pcm_subclass_t subclass;
1291     const char *n, *id, *sdn, *cn;
1292     int card;
1293
1294     pa_assert(p);
1295     pa_assert(pcm_info);
1296
1297     pa_proplist_sets(p, PA_PROP_DEVICE_API, "alsa");
1298
1299     class = snd_pcm_info_get_class(pcm_info);
1300     if (class <= SND_PCM_CLASS_LAST) {
1301         if (class_table[class])
1302             pa_proplist_sets(p, PA_PROP_DEVICE_CLASS, class_table[class]);
1303         if (alsa_class_table[class])
1304             pa_proplist_sets(p, "alsa.class", alsa_class_table[class]);
1305     }
1306     subclass = snd_pcm_info_get_subclass(pcm_info);
1307     if (subclass <= SND_PCM_SUBCLASS_LAST)
1308         if (alsa_subclass_table[subclass])
1309             pa_proplist_sets(p, "alsa.subclass", alsa_subclass_table[subclass]);
1310
1311     if ((n = snd_pcm_info_get_name(pcm_info)))
1312         pa_proplist_sets(p, "alsa.name", n);
1313
1314     if ((id = snd_pcm_info_get_id(pcm_info)))
1315         pa_proplist_sets(p, "alsa.id", id);
1316
1317     pa_proplist_setf(p, "alsa.subdevice", "%u", snd_pcm_info_get_subdevice(pcm_info));
1318     if ((sdn = snd_pcm_info_get_subdevice_name(pcm_info)))
1319         pa_proplist_sets(p, "alsa.subdevice_name", sdn);
1320
1321     pa_proplist_setf(p, "alsa.device", "%u", snd_pcm_info_get_device(pcm_info));
1322
1323     if ((card = snd_pcm_info_get_card(pcm_info)) >= 0) {
1324         pa_alsa_init_proplist_card(p, card);
1325         cn = pa_proplist_gets(p, "alsa.card_name");
1326     }
1327
1328     if (cn && n)
1329         pa_proplist_setf(p, PA_PROP_DEVICE_DESCRIPTION, "%s - %s", cn, n);
1330     else if (cn)
1331         pa_proplist_sets(p, PA_PROP_DEVICE_DESCRIPTION, cn);
1332     else if (n)
1333         pa_proplist_sets(p, PA_PROP_DEVICE_DESCRIPTION, n);
1334 }
1335
1336 int pa_alsa_recover_from_poll(snd_pcm_t *pcm, int revents) {
1337     snd_pcm_state_t state;
1338     int err;
1339
1340     pa_assert(pcm);
1341
1342     if (revents & POLLERR)
1343         pa_log_debug("Got POLLERR from ALSA");
1344     if (revents & POLLNVAL)
1345         pa_log_warn("Got POLLNVAL from ALSA");
1346     if (revents & POLLHUP)
1347         pa_log_warn("Got POLLHUP from ALSA");
1348     if (revents & POLLPRI)
1349         pa_log_warn("Got POLLPRI from ALSA");
1350     if (revents & POLLIN)
1351         pa_log_debug("Got POLLIN from ALSA");
1352     if (revents & POLLOUT)
1353         pa_log_debug("Got POLLOUT from ALSA");
1354
1355     state = snd_pcm_state(pcm);
1356     pa_log_debug("PCM state is %s", snd_pcm_state_name(state));
1357
1358     /* Try to recover from this error */
1359
1360     switch (state) {
1361
1362         case SND_PCM_STATE_XRUN:
1363             if ((err = snd_pcm_recover(pcm, -EPIPE, 1)) != 0) {
1364                 pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP and XRUN: %s", snd_strerror(err));
1365                 return -1;
1366             }
1367             break;
1368
1369         case SND_PCM_STATE_SUSPENDED:
1370             if ((err = snd_pcm_recover(pcm, -ESTRPIPE, 1)) != 0) {
1371                 pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP and SUSPENDED: %s", snd_strerror(err));
1372                 return -1;
1373             }
1374             break;
1375
1376         default:
1377
1378             snd_pcm_drop(pcm);
1379
1380             if ((err = snd_pcm_prepare(pcm)) < 0) {
1381                 pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP with snd_pcm_prepare(): %s", snd_strerror(err));
1382                 return -1;
1383             }
1384             break;
1385     }
1386
1387     return 0;
1388 }
1389
1390 pa_rtpoll_item* pa_alsa_build_pollfd(snd_pcm_t *pcm, pa_rtpoll *rtpoll) {
1391     int n, err;
1392     struct pollfd *pollfd;
1393     pa_rtpoll_item *item;
1394
1395     pa_assert(pcm);
1396
1397     if ((n = snd_pcm_poll_descriptors_count(pcm)) < 0) {
1398         pa_log("snd_pcm_poll_descriptors_count() failed: %s", snd_strerror(n));
1399         return NULL;
1400     }
1401
1402     item = pa_rtpoll_item_new(rtpoll, PA_RTPOLL_NEVER, (unsigned) n);
1403     pollfd = pa_rtpoll_item_get_pollfd(item, NULL);
1404
1405     if ((err = snd_pcm_poll_descriptors(pcm, pollfd, (unsigned) n)) < 0) {
1406         pa_log("snd_pcm_poll_descriptors() failed: %s", snd_strerror(err));
1407         pa_rtpoll_item_free(item);
1408         return NULL;
1409     }
1410
1411     return item;
1412 }
1413
1414 snd_pcm_sframes_t pa_alsa_safe_avail_update(snd_pcm_t *pcm, size_t hwbuf_size, const pa_sample_spec *ss) {
1415     snd_pcm_sframes_t n;
1416     size_t k;
1417
1418     pa_assert(pcm);
1419     pa_assert(hwbuf_size > 0);
1420     pa_assert(ss);
1421
1422     /* Some ALSA driver expose weird bugs, let's inform the user about
1423      * what is going on */
1424
1425     n = snd_pcm_avail_update(pcm);
1426
1427     if (n <= 0)
1428         return n;
1429
1430     k = (size_t) n * pa_frame_size(ss);
1431
1432     if (k >= hwbuf_size * 3 ||
1433         k >= pa_bytes_per_second(ss)*10)
1434         pa_log("snd_pcm_avail_update() returned a value that is exceptionally large: %lu bytes (%lu ms) "
1435                "Most likely this is an ALSA driver bug. Please report this issue to the PulseAudio developers.",
1436                (unsigned long) k, (unsigned long) (pa_bytes_to_usec(k, ss) / PA_USEC_PER_MSEC));
1437
1438     return n;
1439 }
1440
1441 int pa_alsa_safe_mmap_begin(snd_pcm_t *pcm, const snd_pcm_channel_area_t **areas, snd_pcm_uframes_t *offset, snd_pcm_uframes_t *frames, size_t hwbuf_size, const pa_sample_spec *ss) {
1442     int r;
1443     snd_pcm_uframes_t before;
1444     size_t k;
1445
1446     pa_assert(pcm);
1447     pa_assert(areas);
1448     pa_assert(offset);
1449     pa_assert(frames);
1450     pa_assert(hwbuf_size > 0);
1451     pa_assert(ss);
1452
1453     before = *frames;
1454
1455     r = snd_pcm_mmap_begin(pcm, areas, offset, frames);
1456
1457     if (r < 0)
1458         return r;
1459
1460     k = (size_t) *frames * pa_frame_size(ss);
1461
1462     if (*frames > before ||
1463         k >= hwbuf_size * 3 ||
1464         k >= pa_bytes_per_second(ss)*10)
1465
1466         pa_log("snd_pcm_mmap_begin() returned a value that is exceptionally large: %lu bytes (%lu ms) "
1467                "Most likely this is an ALSA driver bug. Please report this issue to the PulseAudio developers.",
1468                (unsigned long) k, (unsigned long) (pa_bytes_to_usec(k, ss) / PA_USEC_PER_MSEC));
1469
1470     return r;
1471 }