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