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