Merge branch 'new-world-order'
[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 #include <pulse/timeval.h>
34
35 #include <pulsecore/log.h>
36 #include <pulsecore/macro.h>
37 #include <pulsecore/core-util.h>
38 #include <pulsecore/atomic.h>
39
40 #include "alsa-util.h"
41
42 struct pa_alsa_fdlist {
43     unsigned num_fds;
44     struct pollfd *fds;
45     /* This is a temporary buffer used to avoid lots of mallocs */
46     struct pollfd *work_fds;
47
48     snd_mixer_t *mixer;
49
50     pa_mainloop_api *m;
51     pa_defer_event *defer;
52     pa_io_event **ios;
53
54     pa_bool_t polled;
55
56     void (*cb)(void *userdata);
57     void *userdata;
58 };
59
60 static void io_cb(pa_mainloop_api*a, pa_io_event* e, int fd, pa_io_event_flags_t events, void *userdata) {
61
62     struct pa_alsa_fdlist *fdl = userdata;
63     int err;
64     unsigned i;
65     unsigned short revents;
66
67     pa_assert(a);
68     pa_assert(fdl);
69     pa_assert(fdl->mixer);
70     pa_assert(fdl->fds);
71     pa_assert(fdl->work_fds);
72
73     if (fdl->polled)
74         return;
75
76     fdl->polled = TRUE;
77
78     memcpy(fdl->work_fds, fdl->fds, sizeof(struct pollfd) * fdl->num_fds);
79
80     for (i = 0; i < fdl->num_fds; i++) {
81         if (e == fdl->ios[i]) {
82             if (events & PA_IO_EVENT_INPUT)
83                 fdl->work_fds[i].revents |= POLLIN;
84             if (events & PA_IO_EVENT_OUTPUT)
85                 fdl->work_fds[i].revents |= POLLOUT;
86             if (events & PA_IO_EVENT_ERROR)
87                 fdl->work_fds[i].revents |= POLLERR;
88             if (events & PA_IO_EVENT_HANGUP)
89                 fdl->work_fds[i].revents |= POLLHUP;
90             break;
91         }
92     }
93
94     pa_assert(i != fdl->num_fds);
95
96     if ((err = snd_mixer_poll_descriptors_revents(fdl->mixer, fdl->work_fds, fdl->num_fds, &revents)) < 0) {
97         pa_log_error("Unable to get poll revent: %s", snd_strerror(err));
98         return;
99     }
100
101     a->defer_enable(fdl->defer, 1);
102
103     if (revents)
104         snd_mixer_handle_events(fdl->mixer);
105 }
106
107 static void defer_cb(pa_mainloop_api*a, pa_defer_event* e, void *userdata) {
108     struct pa_alsa_fdlist *fdl = userdata;
109     unsigned num_fds, i;
110     int err;
111     struct pollfd *temp;
112
113     pa_assert(a);
114     pa_assert(fdl);
115     pa_assert(fdl->mixer);
116
117     a->defer_enable(fdl->defer, 0);
118
119     num_fds = (unsigned) snd_mixer_poll_descriptors_count(fdl->mixer);
120
121     if (num_fds != fdl->num_fds) {
122         if (fdl->fds)
123             pa_xfree(fdl->fds);
124         if (fdl->work_fds)
125             pa_xfree(fdl->work_fds);
126         fdl->fds = pa_xnew0(struct pollfd, num_fds);
127         fdl->work_fds = pa_xnew(struct pollfd, num_fds);
128     }
129
130     memset(fdl->work_fds, 0, sizeof(struct pollfd) * num_fds);
131
132     if ((err = snd_mixer_poll_descriptors(fdl->mixer, fdl->work_fds, num_fds)) < 0) {
133         pa_log_error("Unable to get poll descriptors: %s", snd_strerror(err));
134         return;
135     }
136
137     fdl->polled = FALSE;
138
139     if (memcmp(fdl->fds, fdl->work_fds, sizeof(struct pollfd) * num_fds) == 0)
140         return;
141
142     if (fdl->ios) {
143         for (i = 0; i < fdl->num_fds; i++)
144             a->io_free(fdl->ios[i]);
145
146         if (num_fds != fdl->num_fds) {
147             pa_xfree(fdl->ios);
148             fdl->ios = NULL;
149         }
150     }
151
152     if (!fdl->ios)
153         fdl->ios = pa_xnew(pa_io_event*, num_fds);
154
155     /* Swap pointers */
156     temp = fdl->work_fds;
157     fdl->work_fds = fdl->fds;
158     fdl->fds = temp;
159
160     fdl->num_fds = num_fds;
161
162     for (i = 0;i < num_fds;i++)
163         fdl->ios[i] = a->io_new(a, fdl->fds[i].fd,
164             ((fdl->fds[i].events & POLLIN) ? PA_IO_EVENT_INPUT : 0) |
165             ((fdl->fds[i].events & POLLOUT) ? PA_IO_EVENT_OUTPUT : 0),
166             io_cb, fdl);
167 }
168
169 struct pa_alsa_fdlist *pa_alsa_fdlist_new(void) {
170     struct pa_alsa_fdlist *fdl;
171
172     fdl = pa_xnew0(struct pa_alsa_fdlist, 1);
173
174     fdl->num_fds = 0;
175     fdl->fds = NULL;
176     fdl->work_fds = NULL;
177     fdl->mixer = NULL;
178     fdl->m = NULL;
179     fdl->defer = NULL;
180     fdl->ios = NULL;
181     fdl->polled = FALSE;
182
183     return fdl;
184 }
185
186 void pa_alsa_fdlist_free(struct pa_alsa_fdlist *fdl) {
187     pa_assert(fdl);
188
189     if (fdl->defer) {
190         pa_assert(fdl->m);
191         fdl->m->defer_free(fdl->defer);
192     }
193
194     if (fdl->ios) {
195         unsigned i;
196         pa_assert(fdl->m);
197         for (i = 0; i < fdl->num_fds; i++)
198             fdl->m->io_free(fdl->ios[i]);
199         pa_xfree(fdl->ios);
200     }
201
202     if (fdl->fds)
203         pa_xfree(fdl->fds);
204     if (fdl->work_fds)
205         pa_xfree(fdl->work_fds);
206
207     pa_xfree(fdl);
208 }
209
210 int pa_alsa_fdlist_set_mixer(struct pa_alsa_fdlist *fdl, snd_mixer_t *mixer_handle, pa_mainloop_api* m) {
211     pa_assert(fdl);
212     pa_assert(mixer_handle);
213     pa_assert(m);
214     pa_assert(!fdl->m);
215
216     fdl->mixer = mixer_handle;
217     fdl->m = m;
218     fdl->defer = m->defer_new(m, defer_cb, fdl);
219
220     return 0;
221 }
222
223 static int set_format(snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hwparams, pa_sample_format_t *f) {
224
225     static const snd_pcm_format_t format_trans[] = {
226         [PA_SAMPLE_U8] = SND_PCM_FORMAT_U8,
227         [PA_SAMPLE_ALAW] = SND_PCM_FORMAT_A_LAW,
228         [PA_SAMPLE_ULAW] = SND_PCM_FORMAT_MU_LAW,
229         [PA_SAMPLE_S16LE] = SND_PCM_FORMAT_S16_LE,
230         [PA_SAMPLE_S16BE] = SND_PCM_FORMAT_S16_BE,
231         [PA_SAMPLE_FLOAT32LE] = SND_PCM_FORMAT_FLOAT_LE,
232         [PA_SAMPLE_FLOAT32BE] = SND_PCM_FORMAT_FLOAT_BE,
233         [PA_SAMPLE_S32LE] = SND_PCM_FORMAT_S32_LE,
234         [PA_SAMPLE_S32BE] = SND_PCM_FORMAT_S32_BE,
235     };
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
375         /* First we pass 0 as direction to get exactly what we asked
376          * for. That this is necessary is presumably a bug in ALSA */
377
378         dir = 0;
379         if ((ret = snd_pcm_hw_params_set_periods_near(pcm_handle, hwparams, &_periods, &dir)) < 0) {
380             dir = 1;
381             if ((ret = snd_pcm_hw_params_set_periods_near(pcm_handle, hwparams, &_periods, &dir)) < 0) {
382                 dir = -1;
383                 if ((ret = snd_pcm_hw_params_set_periods_near(pcm_handle, hwparams, &_periods, &dir)) < 0)
384                     goto finish;
385             }
386         }
387     }
388
389     if (_period_size > 0)
390         if ((ret = snd_pcm_hw_params_set_buffer_size_near(pcm_handle, hwparams, &buffer_size)) < 0)
391             goto finish;
392
393     if  ((ret = snd_pcm_hw_params(pcm_handle, hwparams)) < 0)
394         goto finish;
395
396     if (ss->rate != r)
397         pa_log_warn("Device %s doesn't support %u Hz, changed to %u Hz.", snd_pcm_name(pcm_handle), ss->rate, r);
398
399     if (ss->channels != c)
400         pa_log_warn("Device %s doesn't support %u channels, changed to %u.", snd_pcm_name(pcm_handle), ss->channels, c);
401
402     if (ss->format != f)
403         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));
404
405     if ((ret = snd_pcm_prepare(pcm_handle)) < 0)
406         goto finish;
407
408     if ((ret = snd_pcm_hw_params_get_period_size(hwparams, &_period_size, &dir)) < 0 ||
409         (ret = snd_pcm_hw_params_get_periods(hwparams, &_periods, &dir)) < 0)
410         goto finish;
411
412     /* If the sample rate deviates too much, we need to resample */
413     if (r < ss->rate*.95 || r > ss->rate*1.05)
414         ss->rate = r;
415     ss->channels = (uint8_t) c;
416     ss->format = f;
417
418     pa_assert(_periods > 0);
419     pa_assert(_period_size > 0);
420
421     *periods = _periods;
422     *period_size = _period_size;
423
424     if (use_mmap)
425         *use_mmap = _use_mmap;
426
427     if (use_tsched)
428         *use_tsched = _use_tsched;
429
430     ret = 0;
431
432     snd_pcm_nonblock(pcm_handle, 1);
433
434 finish:
435
436     return ret;
437 }
438
439 int pa_alsa_set_sw_params(snd_pcm_t *pcm, snd_pcm_uframes_t avail_min) {
440     snd_pcm_sw_params_t *swparams;
441     int err;
442
443     pa_assert(pcm);
444
445     snd_pcm_sw_params_alloca(&swparams);
446
447     if ((err = snd_pcm_sw_params_current(pcm, swparams) < 0)) {
448         pa_log_warn("Unable to determine current swparams: %s\n", snd_strerror(err));
449         return err;
450     }
451
452     if ((err = snd_pcm_sw_params_set_stop_threshold(pcm, swparams, (snd_pcm_uframes_t) -1)) < 0) {
453         pa_log_warn("Unable to set stop threshold: %s\n", snd_strerror(err));
454         return err;
455     }
456
457     if ((err = snd_pcm_sw_params_set_start_threshold(pcm, swparams, (snd_pcm_uframes_t) -1)) < 0) {
458         pa_log_warn("Unable to set start threshold: %s\n", snd_strerror(err));
459         return err;
460     }
461
462     if ((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, avail_min)) < 0) {
463         pa_log_error("snd_pcm_sw_params_set_avail_min() failed: %s", snd_strerror(err));
464         return err;
465     }
466
467     if ((err = snd_pcm_sw_params(pcm, swparams)) < 0) {
468         pa_log_warn("Unable to set sw params: %s\n", snd_strerror(err));
469         return err;
470     }
471
472     return 0;
473 }
474
475 struct device_info {
476     pa_channel_map map;
477     const char *name;
478 };
479
480 static const struct device_info device_table[] = {
481     {{ 2, { PA_CHANNEL_POSITION_LEFT, PA_CHANNEL_POSITION_RIGHT } }, "front" },
482
483     {{ 4, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
484             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT }}, "surround40" },
485
486     {{ 5, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
487             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
488             PA_CHANNEL_POSITION_LFE }}, "surround41" },
489
490     {{ 5, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
491             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
492             PA_CHANNEL_POSITION_CENTER }}, "surround50" },
493
494     {{ 6, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
495             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
496             PA_CHANNEL_POSITION_CENTER, PA_CHANNEL_POSITION_LFE }}, "surround51" },
497
498     {{ 8, { PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
499             PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
500             PA_CHANNEL_POSITION_CENTER, PA_CHANNEL_POSITION_LFE,
501             PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT }} , "surround71" },
502
503     {{ 0, { 0 }}, NULL }
504 };
505
506 static pa_bool_t channel_map_superset(const pa_channel_map *a, const pa_channel_map *b) {
507     pa_bool_t in_a[PA_CHANNEL_POSITION_MAX];
508     unsigned i;
509
510     pa_assert(a);
511     pa_assert(b);
512
513     memset(in_a, 0, sizeof(in_a));
514
515     for (i = 0; i < a->channels; i++)
516         in_a[a->map[i]] = TRUE;
517
518     for (i = 0; i < b->channels; i++)
519         if (!in_a[b->map[i]])
520             return FALSE;
521
522     return TRUE;
523 }
524
525 snd_pcm_t *pa_alsa_open_by_device_id(
526         const char *dev_id,
527         char **dev,
528         pa_sample_spec *ss,
529         pa_channel_map* map,
530         int mode,
531         uint32_t *nfrags,
532         snd_pcm_uframes_t *period_size,
533         snd_pcm_uframes_t tsched_size,
534         pa_bool_t *use_mmap,
535         pa_bool_t *use_tsched) {
536
537     int i;
538     int direction = 1;
539     int err;
540     char *d;
541     snd_pcm_t *pcm_handle;
542
543     pa_assert(dev_id);
544     pa_assert(dev);
545     pa_assert(ss);
546     pa_assert(map);
547     pa_assert(nfrags);
548     pa_assert(period_size);
549
550     /* First we try to find a device string with a superset of the
551      * requested channel map and open it without the plug: prefix. We
552      * iterate through our device table from top to bottom and take
553      * the first that matches. If we didn't find a working device that
554      * way, we iterate backwards, and check all devices that do not
555      * provide a superset of the requested channel map.*/
556
557     for (i = 0;; i += direction) {
558         pa_sample_spec try_ss;
559
560         if (i < 0) {
561             pa_assert(direction == -1);
562
563             /* OK, so we iterated backwards, and now are at the
564              * beginning of our list. */
565
566             break;
567
568         } else if (!device_table[i].name) {
569             pa_assert(direction == 1);
570
571             /* OK, so we are at the end of our list. at iterated
572              * forwards. */
573
574             i--;
575             direction = -1;
576         }
577
578         if ((direction > 0) == !channel_map_superset(&device_table[i].map, map))
579             continue;
580
581         d = pa_sprintf_malloc("%s:%s", device_table[i].name, dev_id);
582
583         for (;;) {
584             pa_log_debug("Trying %s...", d);
585
586             /* We don't pass SND_PCM_NONBLOCK here, since alsa-lib <=
587              * 1.0.17a would then ignore the SND_PCM_NO_xxx
588              * flags. Instead we enable nonblock mode afterwards via
589              * snd_pcm_nonblock(). Also see
590              * http://mailman.alsa-project.org/pipermail/alsa-devel/2008-August/010258.html */
591
592             if ((err = snd_pcm_open(&pcm_handle, d, mode,
593                                     /* SND_PCM_NONBLOCK| */
594                                     SND_PCM_NO_AUTO_RESAMPLE|
595                                     SND_PCM_NO_AUTO_CHANNELS|
596                                     SND_PCM_NO_AUTO_FORMAT)) < 0) {
597                 pa_log_info("Couldn't open PCM device %s: %s", d, snd_strerror(err));
598                 break;
599             }
600
601             try_ss.channels = device_table[i].map.channels;
602             try_ss.rate = ss->rate;
603             try_ss.format = ss->format;
604
605             if ((err = pa_alsa_set_hw_params(pcm_handle, &try_ss, nfrags, period_size, tsched_size, use_mmap, use_tsched, TRUE)) < 0) {
606
607                 if (!pa_startswith(d, "plug:") && !pa_startswith(d, "plughw:")) {
608                     char *t;
609
610                     t = pa_sprintf_malloc("plug:%s", d);
611                     pa_xfree(d);
612                     d = t;
613
614                     snd_pcm_close(pcm_handle);
615                     continue;
616                 }
617
618                 pa_log_info("PCM device %s refused our hw parameters: %s", d, snd_strerror(err));
619                 snd_pcm_close(pcm_handle);
620                 break;
621             }
622
623             *ss = try_ss;
624             *map = device_table[i].map;
625             pa_assert(map->channels == ss->channels);
626             *dev = d;
627             return pcm_handle;
628         }
629
630         pa_xfree(d);
631     }
632
633     /* OK, we didn't find any good device, so let's try the raw plughw: stuff */
634
635     d = pa_sprintf_malloc("hw:%s", dev_id);
636     pa_log_debug("Trying %s as last resort...", d);
637     pcm_handle = pa_alsa_open_by_device_string(d, dev, ss, map, mode, nfrags, period_size, tsched_size, use_mmap, use_tsched);
638     pa_xfree(d);
639
640     return pcm_handle;
641 }
642
643 snd_pcm_t *pa_alsa_open_by_device_string(
644         const char *device,
645         char **dev,
646         pa_sample_spec *ss,
647         pa_channel_map* map,
648         int mode,
649         uint32_t *nfrags,
650         snd_pcm_uframes_t *period_size,
651         snd_pcm_uframes_t tsched_size,
652         pa_bool_t *use_mmap,
653         pa_bool_t *use_tsched) {
654
655     int err;
656     char *d;
657     snd_pcm_t *pcm_handle;
658
659     pa_assert(device);
660     pa_assert(dev);
661     pa_assert(ss);
662     pa_assert(map);
663     pa_assert(nfrags);
664     pa_assert(period_size);
665
666     d = pa_xstrdup(device);
667
668     for (;;) {
669         pa_log_debug("Trying %s...", d);
670
671         /* We don't pass SND_PCM_NONBLOCK here, since alsa-lib <=
672          * 1.0.17a would then ignore the SND_PCM_NO_xxx flags. Instead
673          * we enable nonblock mode afterwards via
674          * snd_pcm_nonblock(). Also see
675          * http://mailman.alsa-project.org/pipermail/alsa-devel/2008-August/010258.html */
676
677         if ((err = snd_pcm_open(&pcm_handle, d, mode,
678                                 /*SND_PCM_NONBLOCK|*/
679                                 SND_PCM_NO_AUTO_RESAMPLE|
680                                 SND_PCM_NO_AUTO_CHANNELS|
681                                 SND_PCM_NO_AUTO_FORMAT)) < 0) {
682             pa_log("Error opening PCM device %s: %s", d, snd_strerror(err));
683             pa_xfree(d);
684             return NULL;
685         }
686
687         if ((err = pa_alsa_set_hw_params(pcm_handle, ss, nfrags, period_size, tsched_size, use_mmap, use_tsched, FALSE)) < 0) {
688
689             /* Hmm, some hw is very exotic, so we retry with plug, if without it didn't work */
690
691             if (!pa_startswith(d, "plug:") && !pa_startswith(d, "plughw:")) {
692                 char *t;
693
694                 t = pa_sprintf_malloc("plug:%s", d);
695                 pa_xfree(d);
696                 d = t;
697
698                 snd_pcm_close(pcm_handle);
699                 continue;
700             }
701
702             pa_log("Failed to set hardware parameters on %s: %s", d, snd_strerror(err));
703             pa_xfree(d);
704             snd_pcm_close(pcm_handle);
705             return NULL;
706         }
707
708         *dev = d;
709
710         if (ss->channels != map->channels)
711             pa_channel_map_init_extend(map, ss->channels, PA_CHANNEL_MAP_ALSA);
712
713         return pcm_handle;
714     }
715 }
716
717 int pa_alsa_prepare_mixer(snd_mixer_t *mixer, const char *dev) {
718     int err;
719
720     pa_assert(mixer);
721     pa_assert(dev);
722
723     if ((err = snd_mixer_attach(mixer, dev)) < 0) {
724         pa_log_info("Unable to attach to mixer %s: %s", dev, snd_strerror(err));
725         return -1;
726     }
727
728     if ((err = snd_mixer_selem_register(mixer, NULL, NULL)) < 0) {
729         pa_log_warn("Unable to register mixer: %s", snd_strerror(err));
730         return -1;
731     }
732
733     if ((err = snd_mixer_load(mixer)) < 0) {
734         pa_log_warn("Unable to load mixer: %s", snd_strerror(err));
735         return -1;
736     }
737
738     pa_log_info("Successfully attached to mixer '%s'", dev);
739
740     return 0;
741 }
742
743 snd_mixer_elem_t *pa_alsa_find_elem(snd_mixer_t *mixer, const char *name, const char *fallback) {
744     snd_mixer_elem_t *elem;
745     snd_mixer_selem_id_t *sid = NULL;
746
747     snd_mixer_selem_id_alloca(&sid);
748
749     pa_assert(mixer);
750     pa_assert(name);
751
752     snd_mixer_selem_id_set_name(sid, name);
753
754     if (!(elem = snd_mixer_find_selem(mixer, sid))) {
755         pa_log_info("Cannot find mixer control \"%s\".", snd_mixer_selem_id_get_name(sid));
756
757         if (fallback) {
758             snd_mixer_selem_id_set_name(sid, fallback);
759
760             if (!(elem = snd_mixer_find_selem(mixer, sid)))
761                 pa_log_warn("Cannot find fallback mixer control \"%s\".", snd_mixer_selem_id_get_name(sid));
762         }
763     }
764
765     if (elem)
766         pa_log_info("Using mixer control \"%s\".", snd_mixer_selem_id_get_name(sid));
767
768     return elem;
769 }
770
771 static const snd_mixer_selem_channel_id_t alsa_channel_ids[PA_CHANNEL_POSITION_MAX] = {
772     [PA_CHANNEL_POSITION_MONO] = SND_MIXER_SCHN_MONO, /* The ALSA name is just an alias! */
773
774     [PA_CHANNEL_POSITION_FRONT_CENTER] = SND_MIXER_SCHN_FRONT_CENTER,
775     [PA_CHANNEL_POSITION_FRONT_LEFT] = SND_MIXER_SCHN_FRONT_LEFT,
776     [PA_CHANNEL_POSITION_FRONT_RIGHT] = SND_MIXER_SCHN_FRONT_RIGHT,
777
778     [PA_CHANNEL_POSITION_REAR_CENTER] = SND_MIXER_SCHN_REAR_CENTER,
779     [PA_CHANNEL_POSITION_REAR_LEFT] = SND_MIXER_SCHN_REAR_LEFT,
780     [PA_CHANNEL_POSITION_REAR_RIGHT] = SND_MIXER_SCHN_REAR_RIGHT,
781
782     [PA_CHANNEL_POSITION_LFE] = SND_MIXER_SCHN_WOOFER,
783
784     [PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER] = SND_MIXER_SCHN_UNKNOWN,
785     [PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER] = SND_MIXER_SCHN_UNKNOWN,
786
787     [PA_CHANNEL_POSITION_SIDE_LEFT] = SND_MIXER_SCHN_SIDE_LEFT,
788     [PA_CHANNEL_POSITION_SIDE_RIGHT] = SND_MIXER_SCHN_SIDE_RIGHT,
789
790     [PA_CHANNEL_POSITION_AUX0] = SND_MIXER_SCHN_UNKNOWN,
791     [PA_CHANNEL_POSITION_AUX1] = SND_MIXER_SCHN_UNKNOWN,
792     [PA_CHANNEL_POSITION_AUX2] = SND_MIXER_SCHN_UNKNOWN,
793     [PA_CHANNEL_POSITION_AUX3] = SND_MIXER_SCHN_UNKNOWN,
794     [PA_CHANNEL_POSITION_AUX4] = SND_MIXER_SCHN_UNKNOWN,
795     [PA_CHANNEL_POSITION_AUX5] = SND_MIXER_SCHN_UNKNOWN,
796     [PA_CHANNEL_POSITION_AUX6] = SND_MIXER_SCHN_UNKNOWN,
797     [PA_CHANNEL_POSITION_AUX7] = SND_MIXER_SCHN_UNKNOWN,
798     [PA_CHANNEL_POSITION_AUX8] = SND_MIXER_SCHN_UNKNOWN,
799     [PA_CHANNEL_POSITION_AUX9] =  SND_MIXER_SCHN_UNKNOWN,
800     [PA_CHANNEL_POSITION_AUX10] = SND_MIXER_SCHN_UNKNOWN,
801     [PA_CHANNEL_POSITION_AUX11] = SND_MIXER_SCHN_UNKNOWN,
802     [PA_CHANNEL_POSITION_AUX12] = SND_MIXER_SCHN_UNKNOWN,
803     [PA_CHANNEL_POSITION_AUX13] = SND_MIXER_SCHN_UNKNOWN,
804     [PA_CHANNEL_POSITION_AUX14] = SND_MIXER_SCHN_UNKNOWN,
805     [PA_CHANNEL_POSITION_AUX15] = SND_MIXER_SCHN_UNKNOWN,
806     [PA_CHANNEL_POSITION_AUX16] = SND_MIXER_SCHN_UNKNOWN,
807     [PA_CHANNEL_POSITION_AUX17] = SND_MIXER_SCHN_UNKNOWN,
808     [PA_CHANNEL_POSITION_AUX18] = SND_MIXER_SCHN_UNKNOWN,
809     [PA_CHANNEL_POSITION_AUX19] = SND_MIXER_SCHN_UNKNOWN,
810     [PA_CHANNEL_POSITION_AUX20] = SND_MIXER_SCHN_UNKNOWN,
811     [PA_CHANNEL_POSITION_AUX21] = SND_MIXER_SCHN_UNKNOWN,
812     [PA_CHANNEL_POSITION_AUX22] = SND_MIXER_SCHN_UNKNOWN,
813     [PA_CHANNEL_POSITION_AUX23] = SND_MIXER_SCHN_UNKNOWN,
814     [PA_CHANNEL_POSITION_AUX24] = SND_MIXER_SCHN_UNKNOWN,
815     [PA_CHANNEL_POSITION_AUX25] = SND_MIXER_SCHN_UNKNOWN,
816     [PA_CHANNEL_POSITION_AUX26] = SND_MIXER_SCHN_UNKNOWN,
817     [PA_CHANNEL_POSITION_AUX27] = SND_MIXER_SCHN_UNKNOWN,
818     [PA_CHANNEL_POSITION_AUX28] = SND_MIXER_SCHN_UNKNOWN,
819     [PA_CHANNEL_POSITION_AUX29] = SND_MIXER_SCHN_UNKNOWN,
820     [PA_CHANNEL_POSITION_AUX30] = SND_MIXER_SCHN_UNKNOWN,
821     [PA_CHANNEL_POSITION_AUX31] = SND_MIXER_SCHN_UNKNOWN,
822
823     [PA_CHANNEL_POSITION_TOP_CENTER] = SND_MIXER_SCHN_UNKNOWN,
824
825     [PA_CHANNEL_POSITION_TOP_FRONT_CENTER] = SND_MIXER_SCHN_UNKNOWN,
826     [PA_CHANNEL_POSITION_TOP_FRONT_LEFT] = SND_MIXER_SCHN_UNKNOWN,
827     [PA_CHANNEL_POSITION_TOP_FRONT_RIGHT] = SND_MIXER_SCHN_UNKNOWN,
828
829     [PA_CHANNEL_POSITION_TOP_REAR_CENTER] = SND_MIXER_SCHN_UNKNOWN,
830     [PA_CHANNEL_POSITION_TOP_REAR_LEFT] = SND_MIXER_SCHN_UNKNOWN,
831     [PA_CHANNEL_POSITION_TOP_REAR_RIGHT] = SND_MIXER_SCHN_UNKNOWN
832 };
833
834
835 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) {
836     unsigned i;
837     pa_bool_t alsa_channel_used[SND_MIXER_SCHN_LAST];
838     pa_bool_t mono_used = FALSE;
839
840     pa_assert(elem);
841     pa_assert(channel_map);
842     pa_assert(mixer_map);
843
844     memset(&alsa_channel_used, 0, sizeof(alsa_channel_used));
845
846     if (channel_map->channels > 1 &&
847         ((playback && snd_mixer_selem_has_playback_volume_joined(elem)) ||
848          (!playback && snd_mixer_selem_has_capture_volume_joined(elem)))) {
849         pa_log_info("ALSA device lacks independant volume controls for each channel.");
850         return -1;
851     }
852
853     for (i = 0; i < channel_map->channels; i++) {
854         snd_mixer_selem_channel_id_t id;
855         pa_bool_t is_mono;
856
857         is_mono = channel_map->map[i] == PA_CHANNEL_POSITION_MONO;
858         id = alsa_channel_ids[channel_map->map[i]];
859
860         if (!is_mono && id == SND_MIXER_SCHN_UNKNOWN) {
861             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]));
862             return -1;
863         }
864
865         if ((is_mono && mono_used) || (!is_mono && alsa_channel_used[id])) {
866             pa_log_info("Channel map has duplicate channel '%s', falling back to software volume control.", pa_channel_position_to_string(channel_map->map[i]));
867             return -1;
868         }
869
870         if ((playback && (!snd_mixer_selem_has_playback_channel(elem, id) || (is_mono && !snd_mixer_selem_is_playback_mono(elem)))) ||
871             (!playback && (!snd_mixer_selem_has_capture_channel(elem, id) || (is_mono && !snd_mixer_selem_is_capture_mono(elem))))) {
872
873             pa_log_info("ALSA device lacks separate volumes control for channel '%s'", pa_channel_position_to_string(channel_map->map[i]));
874             return -1;
875         }
876
877         if (is_mono) {
878             mixer_map[i] = SND_MIXER_SCHN_MONO;
879             mono_used = TRUE;
880         } else {
881             mixer_map[i] = id;
882             alsa_channel_used[id] = TRUE;
883         }
884     }
885
886     pa_log_info("All %u channels can be mapped to mixer channels.", channel_map->channels);
887
888     return 0;
889 }
890
891 void pa_alsa_dump(snd_pcm_t *pcm) {
892     int err;
893     snd_output_t *out;
894
895     pa_assert(pcm);
896
897     pa_assert_se(snd_output_buffer_open(&out) == 0);
898
899     if ((err = snd_pcm_dump(pcm, out)) < 0)
900         pa_log_debug("snd_pcm_dump(): %s", snd_strerror(err));
901     else {
902         char *s = NULL;
903         snd_output_buffer_string(out, &s);
904         pa_log_debug("snd_pcm_dump():\n%s", pa_strnull(s));
905     }
906
907     pa_assert_se(snd_output_close(out) == 0);
908 }
909
910 void pa_alsa_dump_status(snd_pcm_t *pcm) {
911     int err;
912     snd_output_t *out;
913     snd_pcm_status_t *status;
914
915     pa_assert(pcm);
916
917     snd_pcm_status_alloca(&status);
918
919     pa_assert_se(snd_output_buffer_open(&out) == 0);
920
921     pa_assert_se(snd_pcm_status(pcm, status) == 0);
922
923     if ((err = snd_pcm_status_dump(status, out)) < 0)
924         pa_log_debug("snd_pcm_dump(): %s", snd_strerror(err));
925     else {
926         char *s = NULL;
927         snd_output_buffer_string(out, &s);
928         pa_log_debug("snd_pcm_dump():\n%s", pa_strnull(s));
929     }
930
931     pa_assert_se(snd_output_close(out) == 0);
932 }
933
934 static void alsa_error_handler(const char *file, int line, const char *function, int err, const char *fmt,...) {
935     va_list ap;
936     char *alsa_file;
937
938     alsa_file = pa_sprintf_malloc("(alsa-lib)%s", file);
939
940     va_start(ap, fmt);
941
942     pa_log_levelv_meta(PA_LOG_INFO, alsa_file, line, function, fmt, ap);
943
944     va_end(ap);
945
946     pa_xfree(alsa_file);
947 }
948
949 static pa_atomic_t n_error_handler_installed = PA_ATOMIC_INIT(0);
950
951 void pa_alsa_redirect_errors_inc(void) {
952     /* This is not really thread safe, but we do our best */
953
954     if (pa_atomic_inc(&n_error_handler_installed) == 0)
955         snd_lib_error_set_handler(alsa_error_handler);
956 }
957
958 void pa_alsa_redirect_errors_dec(void) {
959     int r;
960
961     pa_assert_se((r = pa_atomic_dec(&n_error_handler_installed)) >= 1);
962
963     if (r == 1)
964         snd_lib_error_set_handler(NULL);
965 }
966
967 void pa_alsa_init_proplist(pa_proplist *p, snd_pcm_info_t *pcm_info) {
968
969     static const char * const alsa_class_table[SND_PCM_CLASS_LAST+1] = {
970         [SND_PCM_CLASS_GENERIC] = "generic",
971         [SND_PCM_CLASS_MULTI] = "multi",
972         [SND_PCM_CLASS_MODEM] = "modem",
973         [SND_PCM_CLASS_DIGITIZER] = "digitizer"
974     };
975     static const char * const class_table[SND_PCM_CLASS_LAST+1] = {
976         [SND_PCM_CLASS_GENERIC] = "sound",
977         [SND_PCM_CLASS_MULTI] = NULL,
978         [SND_PCM_CLASS_MODEM] = "modem",
979         [SND_PCM_CLASS_DIGITIZER] = NULL
980     };
981     static const char * const alsa_subclass_table[SND_PCM_SUBCLASS_LAST+1] = {
982         [SND_PCM_SUBCLASS_GENERIC_MIX] = "generic-mix",
983         [SND_PCM_SUBCLASS_MULTI_MIX] = "multi-mix"
984     };
985
986     snd_pcm_class_t class;
987     snd_pcm_subclass_t subclass;
988     const char *n, *id, *sdn;
989     char *cn = NULL, *lcn = NULL;
990     int card;
991
992     pa_assert(p);
993     pa_assert(pcm_info);
994
995     pa_proplist_sets(p, PA_PROP_DEVICE_API, "alsa");
996
997     class = snd_pcm_info_get_class(pcm_info);
998     if (class <= SND_PCM_CLASS_LAST) {
999         if (class_table[class])
1000             pa_proplist_sets(p, PA_PROP_DEVICE_CLASS, class_table[class]);
1001         if (alsa_class_table[class])
1002             pa_proplist_sets(p, "alsa.class", alsa_class_table[class]);
1003     }
1004     subclass = snd_pcm_info_get_subclass(pcm_info);
1005     if (subclass <= SND_PCM_SUBCLASS_LAST)
1006         if (alsa_subclass_table[subclass])
1007             pa_proplist_sets(p, "alsa.subclass", alsa_subclass_table[subclass]);
1008
1009     if ((n = snd_pcm_info_get_name(pcm_info)))
1010         pa_proplist_sets(p, "alsa.name", n);
1011
1012     if ((id = snd_pcm_info_get_id(pcm_info)))
1013         pa_proplist_sets(p, "alsa.id", id);
1014
1015     pa_proplist_setf(p, "alsa.subdevice", "%u", snd_pcm_info_get_subdevice(pcm_info));
1016     if ((sdn = snd_pcm_info_get_subdevice_name(pcm_info)))
1017         pa_proplist_sets(p, "alsa.subdevice_name", sdn);
1018
1019     pa_proplist_setf(p, "alsa.device", "%u", snd_pcm_info_get_device(pcm_info));
1020
1021     if ((card = snd_pcm_info_get_card(pcm_info)) >= 0) {
1022         pa_proplist_setf(p, "alsa.card", "%i", card);
1023
1024         if (snd_card_get_name(card, &cn) >= 0)
1025             pa_proplist_sets(p, "alsa.card_name", cn);
1026
1027         if (snd_card_get_longname(card, &lcn) >= 0)
1028             pa_proplist_sets(p, "alsa.long_card_name", lcn);
1029     }
1030
1031     if (cn && n)
1032         pa_proplist_setf(p, PA_PROP_DEVICE_DESCRIPTION, "%s - %s", cn, n);
1033     else if (cn)
1034         pa_proplist_sets(p, PA_PROP_DEVICE_DESCRIPTION, cn);
1035     else if (n)
1036         pa_proplist_sets(p, PA_PROP_DEVICE_DESCRIPTION, n);
1037
1038     free(lcn);
1039     free(cn);
1040 }
1041
1042 int pa_alsa_recover_from_poll(snd_pcm_t *pcm, int revents) {
1043     snd_pcm_state_t state;
1044     int err;
1045
1046     pa_assert(pcm);
1047
1048     if (revents & POLLERR)
1049         pa_log_warn("Got POLLERR from ALSA");
1050     if (revents & POLLNVAL)
1051         pa_log_warn("Got POLLNVAL from ALSA");
1052     if (revents & POLLHUP)
1053         pa_log_warn("Got POLLHUP from ALSA");
1054     if (revents & POLLPRI)
1055         pa_log_warn("Got POLLPRI from ALSA");
1056     if (revents & POLLIN)
1057         pa_log_warn("Got POLLIN from ALSA");
1058     if (revents & POLLOUT)
1059         pa_log_warn("Got POLLOUT 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, (unsigned) n);
1109     pollfd = pa_rtpoll_item_get_pollfd(item, NULL);
1110
1111     if ((err = snd_pcm_poll_descriptors(pcm, pollfd, (unsigned) 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 }
1119
1120 snd_pcm_sframes_t pa_alsa_safe_avail_update(snd_pcm_t *pcm, size_t hwbuf_size, const pa_sample_spec *ss) {
1121     snd_pcm_sframes_t n;
1122     size_t k;
1123
1124     pa_assert(pcm);
1125     pa_assert(hwbuf_size > 0);
1126     pa_assert(ss);
1127
1128     /* Some ALSA driver expose weird bugs, let's inform the user about
1129      * what is going on */
1130
1131     n = snd_pcm_avail_update(pcm);
1132
1133     if (n <= 0)
1134         return n;
1135
1136     k = (size_t) n * pa_frame_size(ss);
1137
1138     if (k >= hwbuf_size * 3 ||
1139         k >= pa_bytes_per_second(ss)*10)
1140         pa_log("snd_pcm_avail_update() returned a value that is exceptionally large: %lu bytes (%lu ms) "
1141                "Most likely this is an ALSA driver bug. Please report this issue to the PulseAudio developers.",
1142                (unsigned long) k, (unsigned long) pa_bytes_to_usec(k, ss) / PA_USEC_PER_MSEC);
1143
1144     return n;
1145 }
1146
1147 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) {
1148     int r;
1149     snd_pcm_uframes_t before;
1150     size_t k;
1151
1152     pa_assert(pcm);
1153     pa_assert(areas);
1154     pa_assert(offset);
1155     pa_assert(frames);
1156     pa_assert(hwbuf_size > 0);
1157     pa_assert(ss);
1158
1159     before = *frames;
1160
1161     r = snd_pcm_mmap_begin(pcm, areas, offset, frames);
1162
1163     if (r < 0)
1164         return r;
1165
1166     k = (size_t) *frames * pa_frame_size(ss);
1167
1168     if (*frames > before ||
1169         k >= hwbuf_size * 3 ||
1170         k >= pa_bytes_per_second(ss)*10)
1171
1172         pa_log("snd_pcm_mmap_begin() returned a value that is exceptionally large: %lu bytes (%lu ms) "
1173                "Most likely this is an ALSA driver bug. Please report this issue to the PulseAudio developers.",
1174                (unsigned long) k, (unsigned long) pa_bytes_to_usec(k, ss) / PA_USEC_PER_MSEC);
1175
1176     return r;
1177 }