Merge dead branch 'lockfree'
[profile/ivi/pulseaudio-panda.git] / src / modules / 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
34 #include <pulsecore/log.h>
35 #include <pulsecore/macro.h>
36 #include <pulsecore/core-util.h>
37 #include <pulsecore/atomic.h>
38
39 #include "alsa-util.h"
40
41 struct pa_alsa_fdlist {
42     int num_fds;
43     struct pollfd *fds;
44     /* This is a temporary buffer used to avoid lots of mallocs */
45     struct pollfd *work_fds;
46
47     snd_mixer_t *mixer;
48
49     pa_mainloop_api *m;
50     pa_defer_event *defer;
51     pa_io_event **ios;
52
53     int polled;
54
55     void (*cb)(void *userdata);
56     void *userdata;
57 };
58
59 static void io_cb(pa_mainloop_api*a, pa_io_event* e, PA_GCC_UNUSED int fd, pa_io_event_flags_t events, void *userdata) {
60
61     struct pa_alsa_fdlist *fdl = userdata;
62     int err, i;
63     unsigned short revents;
64
65     pa_assert(a);
66     pa_assert(fdl);
67     pa_assert(fdl->mixer);
68     pa_assert(fdl->fds);
69     pa_assert(fdl->work_fds);
70
71     if (fdl->polled)
72         return;
73
74     fdl->polled = 1;
75
76     memcpy(fdl->work_fds, fdl->fds, sizeof(struct pollfd) * fdl->num_fds);
77
78     for (i = 0;i < fdl->num_fds; i++) {
79         if (e == fdl->ios[i]) {
80             if (events & PA_IO_EVENT_INPUT)
81                 fdl->work_fds[i].revents |= POLLIN;
82             if (events & PA_IO_EVENT_OUTPUT)
83                 fdl->work_fds[i].revents |= POLLOUT;
84             if (events & PA_IO_EVENT_ERROR)
85                 fdl->work_fds[i].revents |= POLLERR;
86             if (events & PA_IO_EVENT_HANGUP)
87                 fdl->work_fds[i].revents |= POLLHUP;
88             break;
89         }
90     }
91
92     pa_assert(i != fdl->num_fds);
93
94     if ((err = snd_mixer_poll_descriptors_revents(fdl->mixer, fdl->work_fds, fdl->num_fds, &revents)) < 0) {
95         pa_log_error("Unable to get poll revent: %s", snd_strerror(err));
96         return;
97     }
98
99     a->defer_enable(fdl->defer, 1);
100
101     if (revents)
102         snd_mixer_handle_events(fdl->mixer);
103 }
104
105 static void defer_cb(pa_mainloop_api*a, PA_GCC_UNUSED pa_defer_event* e, void *userdata) {
106     struct pa_alsa_fdlist *fdl = userdata;
107     int num_fds, i, err;
108     struct pollfd *temp;
109
110     pa_assert(a);
111     pa_assert(fdl);
112     pa_assert(fdl->mixer);
113
114     a->defer_enable(fdl->defer, 0);
115
116     num_fds = snd_mixer_poll_descriptors_count(fdl->mixer);
117     pa_assert(num_fds > 0);
118
119     if (num_fds != fdl->num_fds) {
120         if (fdl->fds)
121             pa_xfree(fdl->fds);
122         if (fdl->work_fds)
123             pa_xfree(fdl->work_fds);
124         fdl->fds = pa_xnew0(struct pollfd, num_fds);
125         fdl->work_fds = pa_xnew(struct pollfd, num_fds);
126     }
127
128     memset(fdl->work_fds, 0, sizeof(struct pollfd) * num_fds);
129
130     if ((err = snd_mixer_poll_descriptors(fdl->mixer, fdl->work_fds, num_fds)) < 0) {
131         pa_log_error("Unable to get poll descriptors: %s", snd_strerror(err));
132         return;
133     }
134
135     fdl->polled = 0;
136
137     if (memcmp(fdl->fds, fdl->work_fds, sizeof(struct pollfd) * num_fds) == 0)
138         return;
139
140     if (fdl->ios) {
141         for (i = 0; i < fdl->num_fds; i++)
142             a->io_free(fdl->ios[i]);
143
144         if (num_fds != fdl->num_fds) {
145             pa_xfree(fdl->ios);
146             fdl->ios = NULL;
147         }
148     }
149
150     if (!fdl->ios)
151         fdl->ios = pa_xnew(pa_io_event*, num_fds);
152
153     /* Swap pointers */
154     temp = fdl->work_fds;
155     fdl->work_fds = fdl->fds;
156     fdl->fds = temp;
157
158     fdl->num_fds = num_fds;
159
160     for (i = 0;i < num_fds;i++)
161         fdl->ios[i] = a->io_new(a, fdl->fds[i].fd,
162             ((fdl->fds[i].events & POLLIN) ? PA_IO_EVENT_INPUT : 0) |
163             ((fdl->fds[i].events & POLLOUT) ? PA_IO_EVENT_OUTPUT : 0),
164             io_cb, fdl);
165 }
166
167 struct pa_alsa_fdlist *pa_alsa_fdlist_new(void) {
168     struct pa_alsa_fdlist *fdl;
169
170     fdl = pa_xnew0(struct pa_alsa_fdlist, 1);
171
172     fdl->num_fds = 0;
173     fdl->fds = NULL;
174     fdl->work_fds = NULL;
175     fdl->mixer = NULL;
176     fdl->m = NULL;
177     fdl->defer = NULL;
178     fdl->ios = NULL;
179     fdl->polled = 0;
180
181     return fdl;
182 }
183
184 void pa_alsa_fdlist_free(struct pa_alsa_fdlist *fdl) {
185     pa_assert(fdl);
186
187     if (fdl->defer) {
188         pa_assert(fdl->m);
189         fdl->m->defer_free(fdl->defer);
190     }
191
192     if (fdl->ios) {
193         int i;
194         pa_assert(fdl->m);
195         for (i = 0;i < fdl->num_fds;i++)
196             fdl->m->io_free(fdl->ios[i]);
197         pa_xfree(fdl->ios);
198     }
199
200     if (fdl->fds)
201         pa_xfree(fdl->fds);
202     if (fdl->work_fds)
203         pa_xfree(fdl->work_fds);
204
205     pa_xfree(fdl);
206 }
207
208 int pa_alsa_fdlist_set_mixer(struct pa_alsa_fdlist *fdl, snd_mixer_t *mixer_handle, pa_mainloop_api* m) {
209     pa_assert(fdl);
210     pa_assert(mixer_handle);
211     pa_assert(m);
212     pa_assert(!fdl->m);
213
214     fdl->mixer = mixer_handle;
215     fdl->m = m;
216     fdl->defer = m->defer_new(m, defer_cb, fdl);
217
218     return 0;
219 }
220
221 static int set_format(snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hwparams, pa_sample_format_t *f) {
222
223     static const snd_pcm_format_t format_trans[] = {
224         [PA_SAMPLE_U8] = SND_PCM_FORMAT_U8,
225         [PA_SAMPLE_ALAW] = SND_PCM_FORMAT_A_LAW,
226         [PA_SAMPLE_ULAW] = SND_PCM_FORMAT_MU_LAW,
227         [PA_SAMPLE_S16LE] = SND_PCM_FORMAT_S16_LE,
228         [PA_SAMPLE_S16BE] = SND_PCM_FORMAT_S16_BE,
229         [PA_SAMPLE_FLOAT32LE] = SND_PCM_FORMAT_FLOAT_LE,
230         [PA_SAMPLE_FLOAT32BE] = SND_PCM_FORMAT_FLOAT_BE,
231         [PA_SAMPLE_S32LE] = SND_PCM_FORMAT_S32_LE,
232         [PA_SAMPLE_S32BE] = SND_PCM_FORMAT_S32_BE,
233     };
234
235     static const pa_sample_format_t try_order[] = {
236         PA_SAMPLE_FLOAT32NE,
237         PA_SAMPLE_FLOAT32RE,
238         PA_SAMPLE_S32NE,
239         PA_SAMPLE_S32RE,
240         PA_SAMPLE_S16NE,
241         PA_SAMPLE_S16RE,
242         PA_SAMPLE_ALAW,
243         PA_SAMPLE_ULAW,
244         PA_SAMPLE_U8,
245         PA_SAMPLE_INVALID
246     };
247
248     int i, ret;
249
250     pa_assert(pcm_handle);
251     pa_assert(f);
252
253     if ((ret = snd_pcm_hw_params_set_format(pcm_handle, hwparams, format_trans[*f])) >= 0)
254         return ret;
255
256     if (*f == PA_SAMPLE_FLOAT32BE)
257         *f = PA_SAMPLE_FLOAT32LE;
258     else if (*f == PA_SAMPLE_FLOAT32LE)
259         *f = PA_SAMPLE_FLOAT32BE;
260     else if (*f == PA_SAMPLE_S16BE)
261         *f = PA_SAMPLE_S16LE;
262     else if (*f == PA_SAMPLE_S16LE)
263         *f = PA_SAMPLE_S16BE;
264     else if (*f == PA_SAMPLE_S32BE)
265         *f = PA_SAMPLE_S32LE;
266     else if (*f == PA_SAMPLE_S32LE)
267         *f = PA_SAMPLE_S32BE;
268     else
269         goto try_auto;
270
271     if ((ret = snd_pcm_hw_params_set_format(pcm_handle, hwparams, format_trans[*f])) >= 0)
272         return ret;
273
274 try_auto:
275
276     for (i = 0; try_order[i] != PA_SAMPLE_INVALID; i++) {
277         *f = try_order[i];
278
279         if ((ret = snd_pcm_hw_params_set_format(pcm_handle, hwparams, format_trans[*f])) >= 0)
280             return ret;
281     }
282
283     return -1;
284 }
285
286 /* Set the hardware parameters of the given ALSA device. Returns the
287  * selected fragment settings in *period and *period_size */
288 int pa_alsa_set_hw_params(
289         snd_pcm_t *pcm_handle,
290         pa_sample_spec *ss,
291         uint32_t *periods,
292         snd_pcm_uframes_t *period_size,
293         snd_pcm_uframes_t tsched_size,
294         pa_bool_t *use_mmap,
295         pa_bool_t *use_tsched,
296         pa_bool_t require_exact_channel_number) {
297
298     int ret = -1;
299     snd_pcm_uframes_t _period_size = *period_size;
300     unsigned int _periods = *periods;
301     snd_pcm_uframes_t buffer_size;
302     unsigned int r = ss->rate;
303     unsigned int c = ss->channels;
304     pa_sample_format_t f = ss->format;
305     snd_pcm_hw_params_t *hwparams;
306     pa_bool_t _use_mmap = use_mmap && *use_mmap;
307     pa_bool_t _use_tsched = use_tsched && *use_tsched;
308     int dir;
309
310     pa_assert(pcm_handle);
311     pa_assert(ss);
312     pa_assert(periods);
313     pa_assert(period_size);
314
315     snd_pcm_hw_params_alloca(&hwparams);
316
317     if ((ret = snd_pcm_hw_params_any(pcm_handle, hwparams)) < 0)
318         goto finish;
319
320     if ((ret = snd_pcm_hw_params_set_rate_resample(pcm_handle, hwparams, 0)) < 0)
321         goto finish;
322
323     if (_use_mmap) {
324         if ((ret = snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_MMAP_INTERLEAVED)) < 0) {
325
326             /* mmap() didn't work, fall back to interleaved */
327
328             if ((ret = snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
329                 goto finish;
330
331             _use_mmap = FALSE;
332         }
333
334     } else if ((ret = snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
335         goto finish;
336
337     if (!_use_mmap)
338         _use_tsched = FALSE;
339
340     if ((ret = set_format(pcm_handle, hwparams, &f)) < 0)
341         goto finish;
342
343     if ((ret = snd_pcm_hw_params_set_rate_near(pcm_handle, hwparams, &r, NULL)) < 0)
344         goto finish;
345
346     /* Adjust the buffer sizes, if we didn't get the rate we were asking for */
347     _period_size = (snd_pcm_uframes_t) (((uint64_t) _period_size * r) / ss->rate);
348     tsched_size = (snd_pcm_uframes_t) (((uint64_t) tsched_size * r) / ss->rate);
349
350     if (require_exact_channel_number) {
351         if ((ret = snd_pcm_hw_params_set_channels(pcm_handle, hwparams, c)) < 0)
352             goto finish;
353     } else {
354         if ((ret = snd_pcm_hw_params_set_channels_near(pcm_handle, hwparams, &c)) < 0)
355             goto finish;
356     }
357
358     if (_use_tsched) {
359         _period_size = tsched_size;
360         _periods = 1;
361
362         pa_assert_se(snd_pcm_hw_params_get_buffer_size_max(hwparams, &buffer_size) == 0);
363         pa_log_debug("Maximum hw buffer size is %u ms", (unsigned) buffer_size * 1000 / r);
364     }
365
366     buffer_size = _periods * _period_size;
367
368     if ((ret = snd_pcm_hw_params_set_periods_integer(pcm_handle, hwparams)) < 0)
369         goto finish;
370
371     if (_periods > 0) {
372         dir = 1;
373         if ((ret = snd_pcm_hw_params_set_periods_near(pcm_handle, hwparams, &_periods, &dir)) < 0) {
374             dir = -1;
375             if ((ret = snd_pcm_hw_params_set_periods_near(pcm_handle, hwparams, &_periods, &dir)) < 0)
376                 goto finish;
377         }
378     }
379
380     if (_period_size > 0)
381         if ((ret = snd_pcm_hw_params_set_buffer_size_near(pcm_handle, hwparams, &buffer_size)) < 0)
382             goto finish;
383
384     if  ((ret = snd_pcm_hw_params(pcm_handle, hwparams)) < 0)
385         goto finish;
386
387     if (ss->rate != r)
388         pa_log_warn("Device %s doesn't support %u Hz, changed to %u Hz.", snd_pcm_name(pcm_handle), ss->rate, r);
389
390     if (ss->channels != c)
391         pa_log_warn("Device %s doesn't support %u channels, changed to %u.", snd_pcm_name(pcm_handle), ss->channels, c);
392
393     if (ss->format != f)
394         pa_log_warn("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));
395
396     if ((ret = snd_pcm_prepare(pcm_handle)) < 0)
397         goto finish;
398
399     if ((ret = snd_pcm_hw_params_get_period_size(hwparams, &_period_size, &dir)) < 0 ||
400         (ret = snd_pcm_hw_params_get_periods(hwparams, &_periods, &dir)) < 0)
401         goto finish;
402
403     /* If the sample rate deviates too much, we need to resample */
404     if (r < ss->rate*.95 || r > ss->rate*1.05)
405         ss->rate = r;
406     ss->channels = c;
407     ss->format = f;
408
409     pa_assert(_periods > 0);
410     pa_assert(_period_size > 0);
411
412     *periods = _periods;
413     *period_size = _period_size;
414
415     if (use_mmap)
416         *use_mmap = _use_mmap;
417
418     if (use_tsched)
419         *use_tsched = _use_tsched;
420
421     ret = 0;
422
423 finish:
424
425     return ret;
426 }
427
428 int pa_alsa_set_sw_params(snd_pcm_t *pcm, snd_pcm_uframes_t avail_min) {
429     snd_pcm_sw_params_t *swparams;
430     int err;
431
432     pa_assert(pcm);
433
434     snd_pcm_sw_params_alloca(&swparams);
435
436     if ((err = snd_pcm_sw_params_current(pcm, swparams) < 0)) {
437         pa_log_warn("Unable to determine current swparams: %s\n", snd_strerror(err));
438         return err;
439     }
440
441     if ((err = snd_pcm_sw_params_set_stop_threshold(pcm, swparams, (snd_pcm_uframes_t) -1)) < 0) {
442         pa_log_warn("Unable to set stop threshold: %s\n", snd_strerror(err));
443         return err;
444     }
445
446     if ((err = snd_pcm_sw_params_set_start_threshold(pcm, swparams, (snd_pcm_uframes_t) -1)) < 0) {
447         pa_log_warn("Unable to set start threshold: %s\n", snd_strerror(err));
448         return err;
449     }
450
451     if ((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, avail_min)) < 0) {
452         pa_log_error("snd_pcm_sw_params_set_avail_min() failed: %s", snd_strerror(err));
453         return err;
454     }
455
456     if ((err = snd_pcm_sw_params(pcm, swparams)) < 0) {
457         pa_log_warn("Unable to set sw params: %s\n", snd_strerror(err));
458         return err;
459     }
460
461     return 0;
462 }
463
464 struct device_info {
465     pa_channel_map map;
466     const char *name;
467 };
468
469 static const struct device_info device_table[] = {
470     {{ 2, { PA_CHANNEL_POSITION_LEFT, PA_CHANNEL_POSITION_RIGHT } }, "front" },
471
472     {{ 4, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
473             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT }}, "surround40" },
474
475     {{ 5, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
476             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
477             PA_CHANNEL_POSITION_LFE }}, "surround41" },
478
479     {{ 5, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
480             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
481             PA_CHANNEL_POSITION_CENTER }}, "surround50" },
482
483     {{ 6, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
484             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
485             PA_CHANNEL_POSITION_CENTER, PA_CHANNEL_POSITION_LFE }}, "surround51" },
486
487     {{ 8, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
488             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
489             PA_CHANNEL_POSITION_CENTER, PA_CHANNEL_POSITION_LFE,
490             PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT }} , "surround71" },
491
492     {{ 0, { 0 }}, NULL }
493 };
494
495 static pa_bool_t channel_map_superset(const pa_channel_map *a, const pa_channel_map *b) {
496     pa_bool_t in_a[PA_CHANNEL_POSITION_MAX];
497     unsigned i;
498
499     pa_assert(a);
500     pa_assert(b);
501
502     memset(in_a, 0, sizeof(in_a));
503
504     for (i = 0; i < a->channels; i++)
505         in_a[a->map[i]] = TRUE;
506
507     for (i = 0; i < b->channels; i++)
508         if (!in_a[b->map[i]])
509             return FALSE;
510
511     return TRUE;
512 }
513
514 snd_pcm_t *pa_alsa_open_by_device_id(
515         const char *dev_id,
516         char **dev,
517         pa_sample_spec *ss,
518         pa_channel_map* map,
519         int mode,
520         uint32_t *nfrags,
521         snd_pcm_uframes_t *period_size,
522         snd_pcm_uframes_t tsched_size,
523         pa_bool_t *use_mmap,
524         pa_bool_t *use_tsched) {
525
526     int i;
527     int direction = 1;
528     int err;
529     char *d;
530     snd_pcm_t *pcm_handle;
531
532     pa_assert(dev_id);
533     pa_assert(dev);
534     pa_assert(ss);
535     pa_assert(map);
536     pa_assert(nfrags);
537     pa_assert(period_size);
538
539     /* First we try to find a device string with a superset of the
540      * requested channel map and open it without the plug: prefix. We
541      * iterate through our device table from top to bottom and take
542      * the first that matches. If we didn't find a working device that
543      * way, we iterate backwards, and check all devices that do not
544      * provide a superset of the requested channel map.*/
545
546     for (i = 0;; i += direction) {
547         pa_sample_spec try_ss;
548
549         if (i < 0) {
550             pa_assert(direction == -1);
551
552             /* OK, so we iterated backwards, and now are at the
553              * beginning of our list. */
554
555             break;
556
557         } else if (!device_table[i].name) {
558             pa_assert(direction == 1);
559
560             /* OK, so we are at the end of our list. at iterated
561              * forwards. */
562
563             i--;
564             direction = -1;
565         }
566
567         if ((direction > 0) == !channel_map_superset(&device_table[i].map, map))
568             continue;
569
570         d = pa_sprintf_malloc("%s:%s", device_table[i].name, dev_id);
571         pa_log_debug("Trying %s...", d);
572
573         if ((err = snd_pcm_open(&pcm_handle, d, mode,
574                                 SND_PCM_NONBLOCK|
575                                 SND_PCM_NO_AUTO_RESAMPLE|
576                                 SND_PCM_NO_AUTO_CHANNELS|
577                                 SND_PCM_NO_AUTO_FORMAT)) < 0) {
578             pa_log_info("Couldn't open PCM device %s: %s", d, snd_strerror(err));
579             pa_xfree(d);
580             continue;
581         }
582
583         try_ss.channels = device_table[i].map.channels;
584         try_ss.rate = ss->rate;
585         try_ss.format = ss->format;
586
587         if ((err = pa_alsa_set_hw_params(pcm_handle, &try_ss, nfrags, period_size, tsched_size, use_mmap, use_tsched, TRUE)) < 0) {
588             pa_log_info("PCM device %s refused our hw parameters: %s", d, snd_strerror(err));
589             pa_xfree(d);
590             snd_pcm_close(pcm_handle);
591             continue;
592         }
593
594         *ss = try_ss;
595         *map = device_table[i].map;
596         pa_assert(map->channels == ss->channels);
597         *dev = d;
598         return pcm_handle;
599     }
600
601     /* OK, we didn't find any good device, so let's try the raw plughw: stuff */
602
603     d = pa_sprintf_malloc("plughw:%s", dev_id);
604     pa_log_debug("Trying %s as last resort...", d);
605     pcm_handle = pa_alsa_open_by_device_string(d, dev, ss, map, mode, nfrags, period_size, tsched_size, use_mmap, use_tsched);
606     pa_xfree(d);
607
608     return pcm_handle;
609 }
610
611 snd_pcm_t *pa_alsa_open_by_device_string(
612         const char *device,
613         char **dev,
614         pa_sample_spec *ss,
615         pa_channel_map* map,
616         int mode,
617         uint32_t *nfrags,
618         snd_pcm_uframes_t *period_size,
619         snd_pcm_uframes_t tsched_size,
620         pa_bool_t *use_mmap,
621         pa_bool_t *use_tsched) {
622
623     int err;
624     char *d;
625     snd_pcm_t *pcm_handle;
626
627     pa_assert(device);
628     pa_assert(dev);
629     pa_assert(ss);
630     pa_assert(map);
631     pa_assert(nfrags);
632     pa_assert(period_size);
633
634     d = pa_xstrdup(device);
635
636     for (;;) {
637
638         if ((err = snd_pcm_open(&pcm_handle, d, mode, SND_PCM_NONBLOCK|
639                                 SND_PCM_NO_AUTO_RESAMPLE|
640                                 SND_PCM_NO_AUTO_CHANNELS|
641                                 SND_PCM_NO_AUTO_FORMAT)) < 0) {
642             pa_log("Error opening PCM device %s: %s", d, snd_strerror(err));
643             pa_xfree(d);
644             return NULL;
645         }
646
647         if ((err = pa_alsa_set_hw_params(pcm_handle, ss, nfrags, period_size, tsched_size, use_mmap, use_tsched, FALSE)) < 0) {
648
649             if (err == -EPERM) {
650                 /* Hmm, some hw is very exotic, so we retry with plug, if without it didn't work */
651
652                 if (pa_startswith(d, "hw:")) {
653                     char *t = pa_sprintf_malloc("plughw:%s", d+3);
654                     pa_log_debug("Opening the device as '%s' didn't work, retrying with '%s'.", d, t);
655                     pa_xfree(d);
656                     d = t;
657
658                     snd_pcm_close(pcm_handle);
659                     continue;
660                 }
661
662                 pa_log("Failed to set hardware parameters on %s: %s", d, snd_strerror(err));
663                 pa_xfree(d);
664                 snd_pcm_close(pcm_handle);
665                 return NULL;
666             }
667         }
668
669         *dev = d;
670
671         if (ss->channels != map->channels)
672             pa_channel_map_init_extend(map, ss->channels, PA_CHANNEL_MAP_ALSA);
673
674         return pcm_handle;
675     }
676 }
677
678 int pa_alsa_prepare_mixer(snd_mixer_t *mixer, const char *dev) {
679     int err;
680
681     pa_assert(mixer);
682     pa_assert(dev);
683
684     if ((err = snd_mixer_attach(mixer, dev)) < 0) {
685         pa_log_info("Unable to attach to mixer %s: %s", dev, snd_strerror(err));
686         return -1;
687     }
688
689     if ((err = snd_mixer_selem_register(mixer, NULL, NULL)) < 0) {
690         pa_log_warn("Unable to register mixer: %s", snd_strerror(err));
691         return -1;
692     }
693
694     if ((err = snd_mixer_load(mixer)) < 0) {
695         pa_log_warn("Unable to load mixer: %s", snd_strerror(err));
696         return -1;
697     }
698
699     pa_log_info("Successfully attached to mixer '%s'", dev);
700
701     return 0;
702 }
703
704 snd_mixer_elem_t *pa_alsa_find_elem(snd_mixer_t *mixer, const char *name, const char *fallback) {
705     snd_mixer_elem_t *elem;
706     snd_mixer_selem_id_t *sid = NULL;
707
708     snd_mixer_selem_id_alloca(&sid);
709
710     pa_assert(mixer);
711     pa_assert(name);
712
713     snd_mixer_selem_id_set_name(sid, name);
714
715     if (!(elem = snd_mixer_find_selem(mixer, sid))) {
716         pa_log_info("Cannot find mixer control \"%s\".", snd_mixer_selem_id_get_name(sid));
717
718         if (fallback) {
719             snd_mixer_selem_id_set_name(sid, fallback);
720
721             if (!(elem = snd_mixer_find_selem(mixer, sid)))
722                 pa_log_warn("Cannot find fallback mixer control \"%s\".", snd_mixer_selem_id_get_name(sid));
723         }
724     }
725
726     if (elem)
727         pa_log_info("Using mixer control \"%s\".", snd_mixer_selem_id_get_name(sid));
728
729     return elem;
730 }
731
732 static const snd_mixer_selem_channel_id_t alsa_channel_ids[PA_CHANNEL_POSITION_MAX] = {
733     [PA_CHANNEL_POSITION_MONO] = SND_MIXER_SCHN_MONO, /* The ALSA name is just an alias! */
734
735     [PA_CHANNEL_POSITION_FRONT_CENTER] = SND_MIXER_SCHN_FRONT_CENTER,
736     [PA_CHANNEL_POSITION_FRONT_LEFT] = SND_MIXER_SCHN_FRONT_LEFT,
737     [PA_CHANNEL_POSITION_FRONT_RIGHT] = SND_MIXER_SCHN_FRONT_RIGHT,
738
739     [PA_CHANNEL_POSITION_REAR_CENTER] = SND_MIXER_SCHN_REAR_CENTER,
740     [PA_CHANNEL_POSITION_REAR_LEFT] = SND_MIXER_SCHN_REAR_LEFT,
741     [PA_CHANNEL_POSITION_REAR_RIGHT] = SND_MIXER_SCHN_REAR_RIGHT,
742
743     [PA_CHANNEL_POSITION_LFE] = SND_MIXER_SCHN_WOOFER,
744
745     [PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER] = SND_MIXER_SCHN_UNKNOWN,
746     [PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER] = SND_MIXER_SCHN_UNKNOWN,
747
748     [PA_CHANNEL_POSITION_SIDE_LEFT] = SND_MIXER_SCHN_SIDE_LEFT,
749     [PA_CHANNEL_POSITION_SIDE_RIGHT] = SND_MIXER_SCHN_SIDE_RIGHT,
750
751     [PA_CHANNEL_POSITION_AUX0] = SND_MIXER_SCHN_UNKNOWN,
752     [PA_CHANNEL_POSITION_AUX1] = SND_MIXER_SCHN_UNKNOWN,
753     [PA_CHANNEL_POSITION_AUX2] = SND_MIXER_SCHN_UNKNOWN,
754     [PA_CHANNEL_POSITION_AUX3] = SND_MIXER_SCHN_UNKNOWN,
755     [PA_CHANNEL_POSITION_AUX4] = SND_MIXER_SCHN_UNKNOWN,
756     [PA_CHANNEL_POSITION_AUX5] = SND_MIXER_SCHN_UNKNOWN,
757     [PA_CHANNEL_POSITION_AUX6] = SND_MIXER_SCHN_UNKNOWN,
758     [PA_CHANNEL_POSITION_AUX7] = SND_MIXER_SCHN_UNKNOWN,
759     [PA_CHANNEL_POSITION_AUX8] = SND_MIXER_SCHN_UNKNOWN,
760     [PA_CHANNEL_POSITION_AUX9] =  SND_MIXER_SCHN_UNKNOWN,
761     [PA_CHANNEL_POSITION_AUX10] = SND_MIXER_SCHN_UNKNOWN,
762     [PA_CHANNEL_POSITION_AUX11] = SND_MIXER_SCHN_UNKNOWN,
763     [PA_CHANNEL_POSITION_AUX12] = SND_MIXER_SCHN_UNKNOWN,
764     [PA_CHANNEL_POSITION_AUX13] = SND_MIXER_SCHN_UNKNOWN,
765     [PA_CHANNEL_POSITION_AUX14] = SND_MIXER_SCHN_UNKNOWN,
766     [PA_CHANNEL_POSITION_AUX15] = SND_MIXER_SCHN_UNKNOWN,
767     [PA_CHANNEL_POSITION_AUX16] = SND_MIXER_SCHN_UNKNOWN,
768     [PA_CHANNEL_POSITION_AUX17] = SND_MIXER_SCHN_UNKNOWN,
769     [PA_CHANNEL_POSITION_AUX18] = SND_MIXER_SCHN_UNKNOWN,
770     [PA_CHANNEL_POSITION_AUX19] = SND_MIXER_SCHN_UNKNOWN,
771     [PA_CHANNEL_POSITION_AUX20] = SND_MIXER_SCHN_UNKNOWN,
772     [PA_CHANNEL_POSITION_AUX21] = SND_MIXER_SCHN_UNKNOWN,
773     [PA_CHANNEL_POSITION_AUX22] = SND_MIXER_SCHN_UNKNOWN,
774     [PA_CHANNEL_POSITION_AUX23] = SND_MIXER_SCHN_UNKNOWN,
775     [PA_CHANNEL_POSITION_AUX24] = SND_MIXER_SCHN_UNKNOWN,
776     [PA_CHANNEL_POSITION_AUX25] = SND_MIXER_SCHN_UNKNOWN,
777     [PA_CHANNEL_POSITION_AUX26] = SND_MIXER_SCHN_UNKNOWN,
778     [PA_CHANNEL_POSITION_AUX27] = SND_MIXER_SCHN_UNKNOWN,
779     [PA_CHANNEL_POSITION_AUX28] = SND_MIXER_SCHN_UNKNOWN,
780     [PA_CHANNEL_POSITION_AUX29] = SND_MIXER_SCHN_UNKNOWN,
781     [PA_CHANNEL_POSITION_AUX30] = SND_MIXER_SCHN_UNKNOWN,
782     [PA_CHANNEL_POSITION_AUX31] = SND_MIXER_SCHN_UNKNOWN,
783
784     [PA_CHANNEL_POSITION_TOP_CENTER] = SND_MIXER_SCHN_UNKNOWN,
785
786     [PA_CHANNEL_POSITION_TOP_FRONT_CENTER] = SND_MIXER_SCHN_UNKNOWN,
787     [PA_CHANNEL_POSITION_TOP_FRONT_LEFT] = SND_MIXER_SCHN_UNKNOWN,
788     [PA_CHANNEL_POSITION_TOP_FRONT_RIGHT] = SND_MIXER_SCHN_UNKNOWN,
789
790     [PA_CHANNEL_POSITION_TOP_REAR_CENTER] = SND_MIXER_SCHN_UNKNOWN,
791     [PA_CHANNEL_POSITION_TOP_REAR_LEFT] = SND_MIXER_SCHN_UNKNOWN,
792     [PA_CHANNEL_POSITION_TOP_REAR_RIGHT] = SND_MIXER_SCHN_UNKNOWN
793 };
794
795
796 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) {
797     unsigned i;
798     pa_bool_t alsa_channel_used[SND_MIXER_SCHN_LAST];
799     pa_bool_t mono_used = FALSE;
800
801     pa_assert(elem);
802     pa_assert(channel_map);
803     pa_assert(mixer_map);
804
805     memset(&alsa_channel_used, 0, sizeof(alsa_channel_used));
806
807     if (channel_map->channels > 1 &&
808         ((playback && snd_mixer_selem_has_playback_volume_joined(elem)) ||
809          (!playback && snd_mixer_selem_has_capture_volume_joined(elem)))) {
810         pa_log_info("ALSA device lacks independant volume controls for each channel, falling back to software volume control.");
811         return -1;
812     }
813
814     for (i = 0; i < channel_map->channels; i++) {
815         snd_mixer_selem_channel_id_t id;
816         pa_bool_t is_mono;
817
818         is_mono = channel_map->map[i] == PA_CHANNEL_POSITION_MONO;
819         id = alsa_channel_ids[channel_map->map[i]];
820
821         if (!is_mono && id == SND_MIXER_SCHN_UNKNOWN) {
822             pa_log_info("Configured channel map contains channel '%s' that is unknown to the ALSA mixer. Falling back to software volume control.", pa_channel_position_to_string(channel_map->map[i]));
823             return -1;
824         }
825
826         if ((is_mono && mono_used) || (!is_mono && alsa_channel_used[id])) {
827             pa_log_info("Channel map has duplicate channel '%s', falling back to software volume control.", pa_channel_position_to_string(channel_map->map[i]));
828             return -1;
829         }
830
831         if ((playback && (!snd_mixer_selem_has_playback_channel(elem, id) || (is_mono && !snd_mixer_selem_is_playback_mono(elem)))) ||
832             (!playback && (!snd_mixer_selem_has_capture_channel(elem, id) || (is_mono && !snd_mixer_selem_is_capture_mono(elem))))) {
833
834             pa_log_info("ALSA device lacks separate volumes control for channel '%s', falling back to software volume control.", pa_channel_position_to_string(channel_map->map[i]));
835             return -1;
836         }
837
838         if (is_mono) {
839             mixer_map[i] = SND_MIXER_SCHN_MONO;
840             mono_used = TRUE;
841         } else {
842             mixer_map[i] = id;
843             alsa_channel_used[id] = TRUE;
844         }
845     }
846
847     pa_log_info("All %u channels can be mapped to mixer channels.", channel_map->channels);
848
849     return 0;
850 }
851
852 void pa_alsa_0dB_playback(snd_mixer_elem_t *elem) {
853     long min, max, v;
854
855     pa_assert(elem);
856
857     /* Try to enable 0 dB if possible. If ALSA cannot do dB, then use
858      * raw volume levels and fix them to 75% */
859
860     if (snd_mixer_selem_set_playback_dB_all(elem, 0, -1) >= 0)
861         return;
862
863     if (snd_mixer_selem_set_playback_dB_all(elem, 0, 1) >= 0)
864         return;
865
866     if (snd_mixer_selem_get_playback_volume_range(elem, &min, &max) < 0)
867         return;
868
869     v = min + ((max - min) * 3) / 4; /* 75% */
870
871     if (v <= min)
872         v = max;
873
874     snd_mixer_selem_set_playback_volume_all(elem, v);
875 }
876
877 void pa_alsa_0dB_capture(snd_mixer_elem_t *elem) {
878     long min, max, v;
879
880     pa_assert(elem);
881
882     /* Try to enable 0 dB if possible. If ALSA cannot do dB, then use
883      * raw volume levels and fix them to 75% */
884
885     if (snd_mixer_selem_set_capture_dB_all(elem, 0, -1) >= 0)
886         return;
887
888     if (snd_mixer_selem_set_capture_dB_all(elem, 0, 1) >= 0)
889         return;
890
891     if (snd_mixer_selem_get_capture_volume_range(elem, &min, &max) < 0)
892         return;
893
894     v = min + ((max - min) * 3) / 4; /* 75% */
895
896     if (v <= min)
897         v = max;
898
899     snd_mixer_selem_set_capture_volume_all(elem, v);
900 }
901
902 void pa_alsa_dump(snd_pcm_t *pcm) {
903     int err;
904     snd_output_t *out;
905
906     pa_assert(pcm);
907
908     pa_assert_se(snd_output_buffer_open(&out) == 0);
909
910     if ((err = snd_pcm_dump(pcm, out)) < 0)
911         pa_log_debug("snd_pcm_dump(): %s", snd_strerror(err));
912     else {
913         char *s = NULL;
914         snd_output_buffer_string(out, &s);
915         pa_log_debug("snd_pcm_dump():\n%s", pa_strnull(s));
916     }
917
918     pa_assert_se(snd_output_close(out) == 0);
919 }
920
921 void pa_alsa_dump_status(snd_pcm_t *pcm) {
922     int err;
923     snd_output_t *out;
924     snd_pcm_status_t *status;
925
926     pa_assert(pcm);
927
928     snd_pcm_status_alloca(&status);
929
930     pa_assert_se(snd_output_buffer_open(&out) == 0);
931
932     pa_assert_se(snd_pcm_status(pcm, status) == 0);
933
934     if ((err = snd_pcm_status_dump(status, out)) < 0)
935         pa_log_debug("snd_pcm_dump(): %s", snd_strerror(err));
936     else {
937         char *s = NULL;
938         snd_output_buffer_string(out, &s);
939         pa_log_debug("snd_pcm_dump():\n%s", pa_strnull(s));
940     }
941
942     pa_assert_se(snd_output_close(out) == 0);
943 }
944
945 static void alsa_error_handler(const char *file, int line, const char *function, int err, const char *fmt,...) {
946     va_list ap;
947
948     va_start(ap, fmt);
949
950     pa_log_levelv_meta(PA_LOG_WARN, file, line, function, fmt, ap);
951
952     va_end(ap);
953 }
954
955 static pa_atomic_t n_error_handler_installed = PA_ATOMIC_INIT(0);
956
957 void pa_alsa_redirect_errors_inc(void) {
958     /* This is not really thread safe, but we do our best */
959
960     if (pa_atomic_inc(&n_error_handler_installed) == 0)
961         snd_lib_error_set_handler(alsa_error_handler);
962 }
963
964 void pa_alsa_redirect_errors_dec(void) {
965     int r;
966
967     pa_assert_se((r = pa_atomic_dec(&n_error_handler_installed)) >= 1);
968
969     if (r == 1)
970         snd_lib_error_set_handler(NULL);
971 }
972
973 void pa_alsa_init_proplist(pa_proplist *p, snd_pcm_info_t *pcm_info) {
974
975     static const char * const alsa_class_table[SND_PCM_CLASS_LAST+1] = {
976         [SND_PCM_CLASS_GENERIC] = "generic",
977         [SND_PCM_CLASS_MULTI] = "multi",
978         [SND_PCM_CLASS_MODEM] = "modem",
979         [SND_PCM_CLASS_DIGITIZER] = "digitizer"
980     };
981     static const char * const class_table[SND_PCM_CLASS_LAST+1] = {
982         [SND_PCM_CLASS_GENERIC] = "sound",
983         [SND_PCM_CLASS_MULTI] = NULL,
984         [SND_PCM_CLASS_MODEM] = "modem",
985         [SND_PCM_CLASS_DIGITIZER] = NULL
986     };
987     static const char * const alsa_subclass_table[SND_PCM_SUBCLASS_LAST+1] = {
988         [SND_PCM_SUBCLASS_GENERIC_MIX] = "generic-mix",
989         [SND_PCM_SUBCLASS_MULTI_MIX] = "multi-mix"
990     };
991
992     snd_pcm_class_t class;
993     snd_pcm_subclass_t subclass;
994     const char *n, *id, *sdn;
995     char *cn = NULL, *lcn = NULL;
996     int card;
997
998     pa_assert(p);
999     pa_assert(pcm_info);
1000
1001     pa_proplist_sets(p, PA_PROP_DEVICE_API, "alsa");
1002
1003     class = snd_pcm_info_get_class(pcm_info);
1004     if (class <= SND_PCM_CLASS_LAST) {
1005         if (class_table[class])
1006             pa_proplist_sets(p, PA_PROP_DEVICE_CLASS, class_table[class]);
1007         if (alsa_class_table[class])
1008             pa_proplist_sets(p, "alsa.class", alsa_class_table[class]);
1009     }
1010     subclass = snd_pcm_info_get_subclass(pcm_info);
1011     if (subclass <= SND_PCM_SUBCLASS_LAST)
1012         if (alsa_subclass_table[subclass])
1013             pa_proplist_sets(p, "alsa.subclass", alsa_subclass_table[subclass]);
1014
1015     if ((n = snd_pcm_info_get_name(pcm_info)))
1016         pa_proplist_sets(p, "alsa.name", n);
1017
1018     if ((id = snd_pcm_info_get_id(pcm_info)))
1019         pa_proplist_sets(p, "alsa.id", id);
1020
1021     pa_proplist_setf(p, "alsa.subdevice", "%u", snd_pcm_info_get_subdevice(pcm_info));
1022     if ((sdn = snd_pcm_info_get_subdevice_name(pcm_info)))
1023         pa_proplist_sets(p, "alsa.subdevice_name", sdn);
1024
1025     pa_proplist_setf(p, "alsa.device", "%u", snd_pcm_info_get_device(pcm_info));
1026
1027     if ((card = snd_pcm_info_get_card(pcm_info)) >= 0) {
1028         pa_proplist_setf(p, "alsa.card", "%i", card);
1029
1030         if (snd_card_get_name(card, &cn) >= 0)
1031             pa_proplist_sets(p, "alsa.card_name", cn);
1032
1033         if (snd_card_get_longname(card, &lcn) >= 0)
1034             pa_proplist_sets(p, "alsa.long_card_name", lcn);
1035     }
1036
1037     if (cn && n)
1038         pa_proplist_setf(p, PA_PROP_DEVICE_DESCRIPTION, "%s - %s", cn, n);
1039     else if (cn)
1040         pa_proplist_sets(p, PA_PROP_DEVICE_DESCRIPTION, cn);
1041     else if (n)
1042         pa_proplist_sets(p, PA_PROP_DEVICE_DESCRIPTION, n);
1043
1044     free(lcn);
1045     free(cn);
1046 }
1047
1048 int pa_alsa_recover_from_poll(snd_pcm_t *pcm, int revents) {
1049     snd_pcm_state_t state;
1050     int err;
1051
1052     pa_assert(pcm);
1053
1054     if (revents & POLLERR)
1055         pa_log_warn("Got POLLERR from ALSA");
1056     if (revents & POLLNVAL)
1057         pa_log_warn("Got POLLNVAL from ALSA");
1058     if (revents & POLLHUP)
1059         pa_log_warn("Got POLLHUP from ALSA");
1060
1061     state = snd_pcm_state(pcm);
1062     pa_log_warn("PCM state is %s", snd_pcm_state_name(state));
1063
1064     /* Try to recover from this error */
1065
1066     switch (state) {
1067
1068         case SND_PCM_STATE_XRUN:
1069             if ((err = snd_pcm_recover(pcm, -EPIPE, 1)) != 0) {
1070                 pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP and XRUN: %s", snd_strerror(err));
1071                 return -1;
1072             }
1073             break;
1074
1075         case SND_PCM_STATE_SUSPENDED:
1076             if ((err = snd_pcm_recover(pcm, -ESTRPIPE, 1)) != 0) {
1077                 pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP and SUSPENDED: %s", snd_strerror(err));
1078                 return -1;
1079             }
1080             break;
1081
1082         default:
1083
1084             snd_pcm_drop(pcm);
1085
1086             if ((err = snd_pcm_prepare(pcm)) < 0) {
1087                 pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP with snd_pcm_prepare(): %s", snd_strerror(err));
1088                 return -1;
1089             }
1090             break;
1091     }
1092
1093     return 0;
1094 }
1095
1096 pa_rtpoll_item* pa_alsa_build_pollfd(snd_pcm_t *pcm, pa_rtpoll *rtpoll) {
1097     int n, err;
1098     struct pollfd *pollfd;
1099     pa_rtpoll_item *item;
1100
1101     pa_assert(pcm);
1102
1103     if ((n = snd_pcm_poll_descriptors_count(pcm)) < 0) {
1104         pa_log("snd_pcm_poll_descriptors_count() failed: %s", snd_strerror(n));
1105         return NULL;
1106     }
1107
1108     item = pa_rtpoll_item_new(rtpoll, PA_RTPOLL_NEVER, n);
1109     pollfd = pa_rtpoll_item_get_pollfd(item, NULL);
1110
1111     if ((err = snd_pcm_poll_descriptors(pcm, pollfd, n)) < 0) {
1112         pa_log("snd_pcm_poll_descriptors() failed: %s", snd_strerror(err));
1113         pa_rtpoll_item_free(item);
1114         return NULL;
1115     }
1116
1117     return item;
1118 }