]> code.delx.au - pulseaudio/blob - src/modules/module-alsa-source.c
fix two uninitialized memory accesses
[pulseaudio] / src / modules / module-alsa-source.c
1 /***
2 This file is part of PulseAudio.
3
4 Copyright 2004-2008 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 <stdio.h>
28
29 #include <asoundlib.h>
30
31 #include <pulse/xmalloc.h>
32 #include <pulse/util.h>
33 #include <pulse/timeval.h>
34
35 #include <pulsecore/core-error.h>
36 #include <pulsecore/core.h>
37 #include <pulsecore/module.h>
38 #include <pulsecore/memchunk.h>
39 #include <pulsecore/sink.h>
40 #include <pulsecore/modargs.h>
41 #include <pulsecore/core-util.h>
42 #include <pulsecore/sample-util.h>
43 #include <pulsecore/log.h>
44 #include <pulsecore/macro.h>
45 #include <pulsecore/thread.h>
46 #include <pulsecore/core-error.h>
47 #include <pulsecore/thread-mq.h>
48 #include <pulsecore/rtpoll.h>
49 #include <pulsecore/time-smoother.h>
50 #include <pulsecore/rtclock.h>
51
52 #include "alsa-util.h"
53 #include "module-alsa-source-symdef.h"
54
55 PA_MODULE_AUTHOR("Lennart Poettering");
56 PA_MODULE_DESCRIPTION("ALSA Source");
57 PA_MODULE_VERSION(PACKAGE_VERSION);
58 PA_MODULE_LOAD_ONCE(FALSE);
59 PA_MODULE_USAGE(
60 "source_name=<name for the source> "
61 "device=<ALSA device> "
62 "device_id=<ALSA card index> "
63 "format=<sample format> "
64 "rate=<sample rate> "
65 "channels=<number of channels> "
66 "channel_map=<channel map> "
67 "fragments=<number of fragments> "
68 "fragment_size=<fragment size> "
69 "mmap=<enable memory mapping?> "
70 "tsched=<enable system timer based scheduling mode?> "
71 "tsched_buffer_size=<buffer size when using timer based scheduling> "
72 "tsched_buffer_watermark=<upper fill watermark> "
73 "mixer_reset=<reset hw volume and mute settings to sane defaults when falling back to software?>");
74
75 static const char* const valid_modargs[] = {
76 "source_name",
77 "device",
78 "device_id",
79 "format",
80 "rate",
81 "channels",
82 "channel_map",
83 "fragments",
84 "fragment_size",
85 "mmap",
86 "tsched",
87 "tsched_buffer_size",
88 "tsched_buffer_watermark",
89 "mixer_reset",
90 NULL
91 };
92
93 #define DEFAULT_DEVICE "default"
94 #define DEFAULT_TSCHED_BUFFER_USEC (2*PA_USEC_PER_SEC) /* 2s */
95 #define DEFAULT_TSCHED_WATERMARK_USEC (20*PA_USEC_PER_MSEC) /* 20ms */
96 #define TSCHED_MIN_SLEEP_USEC (3*PA_USEC_PER_MSEC) /* 3ms */
97 #define TSCHED_MIN_WAKEUP_USEC (3*PA_USEC_PER_MSEC) /* 3ms */
98
99 struct userdata {
100 pa_core *core;
101 pa_module *module;
102 pa_source *source;
103
104 pa_thread *thread;
105 pa_thread_mq thread_mq;
106 pa_rtpoll *rtpoll;
107
108 snd_pcm_t *pcm_handle;
109
110 pa_alsa_fdlist *mixer_fdl;
111 snd_mixer_t *mixer_handle;
112 snd_mixer_elem_t *mixer_elem;
113 long hw_volume_max, hw_volume_min;
114 long hw_dB_max, hw_dB_min;
115 pa_bool_t hw_dB_supported;
116
117 size_t frame_size, fragment_size, hwbuf_size, tsched_watermark;
118 unsigned nfragments;
119
120 char *device_name;
121
122 pa_bool_t use_mmap, use_tsched;
123
124 pa_rtpoll_item *alsa_rtpoll_item;
125
126 snd_mixer_selem_channel_id_t mixer_map[SND_MIXER_SCHN_LAST];
127
128 pa_smoother *smoother;
129 int64_t frame_index;
130
131 snd_pcm_sframes_t hwbuf_unused_frames;
132 };
133
134 static void fix_tsched_watermark(struct userdata *u) {
135 size_t max_use;
136 size_t min_sleep, min_wakeup;
137 pa_assert(u);
138
139 max_use = u->hwbuf_size - u->hwbuf_unused_frames * u->frame_size;
140
141 min_sleep = pa_usec_to_bytes(TSCHED_MIN_SLEEP_USEC, &u->source->sample_spec);
142 min_wakeup = pa_usec_to_bytes(TSCHED_MIN_WAKEUP_USEC, &u->source->sample_spec);
143
144 if (min_sleep > max_use/2)
145 min_sleep = pa_frame_align(max_use/2, &u->source->sample_spec);
146 if (min_sleep < u->frame_size)
147 min_sleep = u->frame_size;
148
149 if (min_wakeup > max_use/2)
150 min_wakeup = pa_frame_align(max_use/2, &u->source->sample_spec);
151 if (min_wakeup < u->frame_size)
152 min_wakeup = u->frame_size;
153
154 if (u->tsched_watermark > max_use-min_sleep)
155 u->tsched_watermark = max_use-min_sleep;
156
157 if (u->tsched_watermark < min_wakeup)
158 u->tsched_watermark = min_wakeup;
159 }
160
161 static pa_usec_t hw_sleep_time(struct userdata *u, pa_usec_t *sleep_usec, pa_usec_t*process_usec) {
162 pa_usec_t wm, usec;
163
164 pa_assert(u);
165
166 usec = pa_source_get_requested_latency_within_thread(u->source);
167
168 if (usec == (pa_usec_t) -1)
169 usec = pa_bytes_to_usec(u->hwbuf_size, &u->source->sample_spec);
170
171 /* pa_log_debug("hw buffer time: %u ms", (unsigned) (usec / PA_USEC_PER_MSEC)); */
172
173 wm = pa_bytes_to_usec(u->tsched_watermark, &u->source->sample_spec);
174
175 if (usec >= wm) {
176 *sleep_usec = usec - wm;
177 *process_usec = wm;
178 } else
179 *process_usec = *sleep_usec = usec /= 2;
180
181 /* pa_log_debug("after watermark: %u ms", (unsigned) (*sleep_usec / PA_USEC_PER_MSEC)); */
182
183 return usec;
184 }
185
186 static int try_recover(struct userdata *u, const char *call, int err) {
187 pa_assert(u);
188 pa_assert(call);
189 pa_assert(err < 0);
190
191 pa_log_debug("%s: %s", call, snd_strerror(err));
192
193 pa_assert(err != -EAGAIN);
194
195 if (err == -EPIPE)
196 pa_log_debug("%s: Buffer overrun!", call);
197
198 if ((err = snd_pcm_recover(u->pcm_handle, err, 1)) == 0) {
199 snd_pcm_start(u->pcm_handle);
200 return 0;
201 }
202
203 pa_log("%s: %s", call, snd_strerror(err));
204 return -1;
205 }
206
207 static size_t check_left_to_record(struct userdata *u, snd_pcm_sframes_t n) {
208 size_t left_to_record;
209
210 if (n*u->frame_size < u->hwbuf_size)
211 left_to_record = u->hwbuf_size - (n*u->frame_size);
212 else
213 left_to_record = 0;
214
215 if (left_to_record > 0) {
216 /* pa_log_debug("%0.2f ms left to record", (double) pa_bytes_to_usec(left_to_record, &u->source->sample_spec) / PA_USEC_PER_MSEC); */
217 } else {
218 pa_log_info("Overrun!");
219
220 if (u->use_tsched) {
221 size_t old_watermark = u->tsched_watermark;
222
223 u->tsched_watermark *= 2;
224 fix_tsched_watermark(u);
225
226 if (old_watermark != u->tsched_watermark)
227 pa_log_notice("Increasing wakeup watermark to %0.2f ms",
228 (double) pa_bytes_to_usec(u->tsched_watermark, &u->source->sample_spec) / PA_USEC_PER_MSEC);
229 }
230 }
231
232 return left_to_record;
233 }
234
235 static int mmap_read(struct userdata *u, pa_usec_t *sleep_usec) {
236 int work_done = 0;
237 pa_usec_t max_sleep_usec = 0, process_usec = 0;
238 size_t left_to_record;
239
240 pa_assert(u);
241 pa_source_assert_ref(u->source);
242
243 if (u->use_tsched)
244 hw_sleep_time(u, &max_sleep_usec, &process_usec);
245
246 for (;;) {
247 snd_pcm_sframes_t n;
248 int r;
249
250 snd_pcm_hwsync(u->pcm_handle);
251
252 if (PA_UNLIKELY((n = snd_pcm_avail_update(u->pcm_handle)) < 0)) {
253
254 if ((r = try_recover(u, "snd_pcm_avail_update", n)) == 0)
255 continue;
256
257 return r;
258 }
259
260 left_to_record = check_left_to_record(u, n);
261
262 if (u->use_tsched)
263 if (pa_bytes_to_usec(left_to_record, &u->source->sample_spec) > process_usec+max_sleep_usec/2)
264 break;
265
266 if (PA_UNLIKELY(n <= 0))
267 break;
268
269 for (;;) {
270 int err;
271 const snd_pcm_channel_area_t *areas;
272 snd_pcm_uframes_t offset, frames = (snd_pcm_uframes_t) n;
273 pa_memchunk chunk;
274 void *p;
275
276 /* pa_log_debug("%lu frames to read", (unsigned long) frames); */
277
278 if (PA_UNLIKELY((err = snd_pcm_mmap_begin(u->pcm_handle, &areas, &offset, &frames)) < 0)) {
279
280 if ((r = try_recover(u, "snd_pcm_mmap_begin", err)) == 0)
281 continue;
282
283 return r;
284 }
285
286 /* Make sure that if these memblocks need to be copied they will fit into one slot */
287 if (frames > pa_mempool_block_size_max(u->source->core->mempool)/u->frame_size)
288 frames = pa_mempool_block_size_max(u->source->core->mempool)/u->frame_size;
289
290 /* Check these are multiples of 8 bit */
291 pa_assert((areas[0].first & 7) == 0);
292 pa_assert((areas[0].step & 7)== 0);
293
294 /* We assume a single interleaved memory buffer */
295 pa_assert((areas[0].first >> 3) == 0);
296 pa_assert((areas[0].step >> 3) == u->frame_size);
297
298 p = (uint8_t*) areas[0].addr + (offset * u->frame_size);
299
300 chunk.memblock = pa_memblock_new_fixed(u->core->mempool, p, frames * u->frame_size, TRUE);
301 chunk.length = pa_memblock_get_length(chunk.memblock);
302 chunk.index = 0;
303
304 pa_source_post(u->source, &chunk);
305 pa_memblock_unref_fixed(chunk.memblock);
306
307 if (PA_UNLIKELY((err = snd_pcm_mmap_commit(u->pcm_handle, offset, frames)) < 0)) {
308
309 if ((r = try_recover(u, "snd_pcm_mmap_commit", err)) == 0)
310 continue;
311
312 return r;
313 }
314
315 work_done = 1;
316
317 u->frame_index += frames;
318
319 /* pa_log_debug("read %lu frames", (unsigned long) frames); */
320
321 if (frames >= (snd_pcm_uframes_t) n)
322 break;
323
324 n -= frames;
325 }
326 }
327
328 *sleep_usec = pa_bytes_to_usec(left_to_record, &u->source->sample_spec) - process_usec;
329 return work_done;
330 }
331
332 static int unix_read(struct userdata *u, pa_usec_t *sleep_usec) {
333 int work_done = 0;
334 pa_usec_t max_sleep_usec = 0, process_usec = 0;
335 size_t left_to_record;
336
337 pa_assert(u);
338 pa_source_assert_ref(u->source);
339
340 if (u->use_tsched)
341 hw_sleep_time(u, &max_sleep_usec, &process_usec);
342
343 for (;;) {
344 snd_pcm_sframes_t n;
345 int r;
346
347 snd_pcm_hwsync(u->pcm_handle);
348
349 if (PA_UNLIKELY((n = snd_pcm_avail_update(u->pcm_handle)) < 0)) {
350
351 if ((r = try_recover(u, "snd_pcm_avail_update", n)) == 0)
352 continue;
353
354 return r;
355 }
356
357 left_to_record = check_left_to_record(u, n);
358
359 if (u->use_tsched)
360 if (pa_bytes_to_usec(left_to_record, &u->source->sample_spec) > process_usec+max_sleep_usec/2)
361 break;
362
363 if (PA_UNLIKELY(n <= 0))
364 return work_done;
365
366 for (;;) {
367 void *p;
368 snd_pcm_sframes_t frames;
369 pa_memchunk chunk;
370
371 chunk.memblock = pa_memblock_new(u->core->mempool, (size_t) -1);
372
373 frames = pa_memblock_get_length(chunk.memblock) / u->frame_size;
374
375 if (frames > n)
376 frames = n;
377
378 /* pa_log_debug("%lu frames to read", (unsigned long) n); */
379
380 p = pa_memblock_acquire(chunk.memblock);
381 frames = snd_pcm_readi(u->pcm_handle, (uint8_t*) p, frames);
382 pa_memblock_release(chunk.memblock);
383
384 pa_assert(frames != 0);
385
386 if (PA_UNLIKELY(frames < 0)) {
387 pa_memblock_unref(chunk.memblock);
388
389 if ((r = try_recover(u, "snd_pcm_readi", n)) == 0)
390 continue;
391
392 return r;
393 }
394
395 chunk.index = 0;
396 chunk.length = frames * u->frame_size;
397
398 pa_source_post(u->source, &chunk);
399 pa_memblock_unref(chunk.memblock);
400
401 work_done = 1;
402
403 u->frame_index += frames;
404
405 /* pa_log_debug("read %lu frames", (unsigned long) frames); */
406
407 if (frames >= n)
408 break;
409
410 n -= frames;
411 }
412 }
413
414 *sleep_usec = pa_bytes_to_usec(left_to_record, &u->source->sample_spec) - process_usec;
415 return work_done;
416 }
417
418 static void update_smoother(struct userdata *u) {
419 snd_pcm_sframes_t delay = 0;
420 int64_t frames;
421 int err;
422 pa_usec_t now1, now2;
423
424 pa_assert(u);
425 pa_assert(u->pcm_handle);
426
427 /* Let's update the time smoother */
428
429 snd_pcm_hwsync(u->pcm_handle);
430 snd_pcm_avail_update(u->pcm_handle);
431
432 if (PA_UNLIKELY((err = snd_pcm_delay(u->pcm_handle, &delay)) < 0)) {
433 pa_log_warn("Failed to get delay: %s", snd_strerror(err));
434 return;
435 }
436
437 frames = u->frame_index + delay;
438
439 now1 = pa_rtclock_usec();
440 now2 = pa_bytes_to_usec(frames * u->frame_size, &u->source->sample_spec);
441
442 pa_smoother_put(u->smoother, now1, now2);
443 }
444
445 static pa_usec_t source_get_latency(struct userdata *u) {
446 pa_usec_t r = 0;
447 int64_t delay;
448 pa_usec_t now1, now2;
449
450 pa_assert(u);
451
452 now1 = pa_rtclock_usec();
453 now2 = pa_smoother_get(u->smoother, now1);
454
455 delay = (int64_t) now2 - pa_bytes_to_usec(u->frame_index * u->frame_size, &u->source->sample_spec);
456
457 if (delay > 0)
458 r = (pa_usec_t) delay;
459
460 return r;
461 }
462
463 static int build_pollfd(struct userdata *u) {
464 pa_assert(u);
465 pa_assert(u->pcm_handle);
466
467 if (u->alsa_rtpoll_item)
468 pa_rtpoll_item_free(u->alsa_rtpoll_item);
469
470 if (!(u->alsa_rtpoll_item = pa_alsa_build_pollfd(u->pcm_handle, u->rtpoll)))
471 return -1;
472
473 return 0;
474 }
475
476 static int suspend(struct userdata *u) {
477 pa_assert(u);
478 pa_assert(u->pcm_handle);
479
480 pa_smoother_pause(u->smoother, pa_rtclock_usec());
481
482 /* Let's suspend */
483 snd_pcm_close(u->pcm_handle);
484 u->pcm_handle = NULL;
485
486 if (u->alsa_rtpoll_item) {
487 pa_rtpoll_item_free(u->alsa_rtpoll_item);
488 u->alsa_rtpoll_item = NULL;
489 }
490
491 pa_log_info("Device suspended...");
492
493 return 0;
494 }
495
496 static int update_sw_params(struct userdata *u) {
497 snd_pcm_uframes_t avail_min;
498 int err;
499
500 pa_assert(u);
501
502 /* Use the full buffer if noone asked us for anything specific */
503 u->hwbuf_unused_frames = 0;
504
505 if (u->use_tsched) {
506 pa_usec_t latency;
507
508 if ((latency = pa_source_get_requested_latency_within_thread(u->source)) != (pa_usec_t) -1) {
509 size_t b;
510
511 pa_log_debug("latency set to %0.2f", (double) latency / PA_USEC_PER_MSEC);
512
513 b = pa_usec_to_bytes(latency, &u->source->sample_spec);
514
515 /* We need at least one sample in our buffer */
516
517 if (PA_UNLIKELY(b < u->frame_size))
518 b = u->frame_size;
519
520 u->hwbuf_unused_frames =
521 PA_LIKELY(b < u->hwbuf_size) ?
522 ((u->hwbuf_size - b) / u->frame_size) : 0;
523
524 fix_tsched_watermark(u);
525 }
526 }
527
528 pa_log_debug("hwbuf_unused_frames=%lu", (unsigned long) u->hwbuf_unused_frames);
529
530 avail_min = 1;
531
532 if (u->use_tsched) {
533 pa_usec_t sleep_usec, process_usec;
534
535 hw_sleep_time(u, &sleep_usec, &process_usec);
536 avail_min += pa_usec_to_bytes(sleep_usec, &u->source->sample_spec);
537 }
538
539 pa_log_debug("setting avail_min=%lu", (unsigned long) avail_min);
540
541 if ((err = pa_alsa_set_sw_params(u->pcm_handle, avail_min)) < 0) {
542 pa_log("Failed to set software parameters: %s", snd_strerror(err));
543 return err;
544 }
545
546 return 0;
547 }
548
549 static int unsuspend(struct userdata *u) {
550 pa_sample_spec ss;
551 int err;
552 pa_bool_t b, d;
553 unsigned nfrags;
554 snd_pcm_uframes_t period_size;
555
556 pa_assert(u);
557 pa_assert(!u->pcm_handle);
558
559 pa_log_info("Trying resume...");
560
561 snd_config_update_free_global();
562 if ((err = snd_pcm_open(&u->pcm_handle, u->device_name, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK)) < 0) {
563 pa_log("Error opening PCM device %s: %s", u->device_name, snd_strerror(err));
564 goto fail;
565 }
566
567 ss = u->source->sample_spec;
568 nfrags = u->nfragments;
569 period_size = u->fragment_size / u->frame_size;
570 b = u->use_mmap;
571 d = u->use_tsched;
572
573 if ((err = pa_alsa_set_hw_params(u->pcm_handle, &ss, &nfrags, &period_size, u->hwbuf_size / u->frame_size, &b, &d, TRUE)) < 0) {
574 pa_log("Failed to set hardware parameters: %s", snd_strerror(err));
575 goto fail;
576 }
577
578 if (b != u->use_mmap || d != u->use_tsched) {
579 pa_log_warn("Resume failed, couldn't get original access mode.");
580 goto fail;
581 }
582
583 if (!pa_sample_spec_equal(&ss, &u->source->sample_spec)) {
584 pa_log_warn("Resume failed, couldn't restore original sample settings.");
585 goto fail;
586 }
587
588 if (nfrags != u->nfragments || period_size*u->frame_size != u->fragment_size) {
589 pa_log_warn("Resume failed, couldn't restore original fragment settings.");
590 goto fail;
591 }
592
593 if (update_sw_params(u) < 0)
594 goto fail;
595
596 if (build_pollfd(u) < 0)
597 goto fail;
598
599 /* FIXME: We need to reload the volume somehow */
600
601 snd_pcm_start(u->pcm_handle);
602 pa_smoother_resume(u->smoother, pa_rtclock_usec());
603
604 pa_log_info("Resumed successfully...");
605
606 return 0;
607
608 fail:
609 if (u->pcm_handle) {
610 snd_pcm_close(u->pcm_handle);
611 u->pcm_handle = NULL;
612 }
613
614 return -1;
615 }
616
617 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
618 struct userdata *u = PA_SOURCE(o)->userdata;
619
620 switch (code) {
621
622 case PA_SOURCE_MESSAGE_GET_LATENCY: {
623 pa_usec_t r = 0;
624
625 if (u->pcm_handle)
626 r = source_get_latency(u);
627
628 *((pa_usec_t*) data) = r;
629
630 return 0;
631 }
632
633 case PA_SOURCE_MESSAGE_SET_STATE:
634
635 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
636
637 case PA_SOURCE_SUSPENDED:
638 pa_assert(PA_SOURCE_IS_OPENED(u->source->thread_info.state));
639
640 if (suspend(u) < 0)
641 return -1;
642
643 break;
644
645 case PA_SOURCE_IDLE:
646 case PA_SOURCE_RUNNING:
647
648 if (u->source->thread_info.state == PA_SOURCE_INIT) {
649 if (build_pollfd(u) < 0)
650 return -1;
651
652 snd_pcm_start(u->pcm_handle);
653 }
654
655 if (u->source->thread_info.state == PA_SOURCE_SUSPENDED) {
656 if (unsuspend(u) < 0)
657 return -1;
658 }
659
660 break;
661
662 case PA_SOURCE_UNLINKED:
663 case PA_SOURCE_INIT:
664 ;
665 }
666
667 break;
668 }
669
670 return pa_source_process_msg(o, code, data, offset, chunk);
671 }
672
673 static int mixer_callback(snd_mixer_elem_t *elem, unsigned int mask) {
674 struct userdata *u = snd_mixer_elem_get_callback_private(elem);
675
676 pa_assert(u);
677 pa_assert(u->mixer_handle);
678
679 if (mask == SND_CTL_EVENT_MASK_REMOVE)
680 return 0;
681
682 if (mask & SND_CTL_EVENT_MASK_VALUE) {
683 pa_source_get_volume(u->source);
684 pa_source_get_mute(u->source);
685 }
686
687 return 0;
688 }
689
690 static int source_get_volume_cb(pa_source *s) {
691 struct userdata *u = s->userdata;
692 int err;
693 int i;
694
695 pa_assert(u);
696 pa_assert(u->mixer_elem);
697
698 for (i = 0; i < s->sample_spec.channels; i++) {
699 long alsa_vol;
700
701 pa_assert(snd_mixer_selem_has_capture_channel(u->mixer_elem, u->mixer_map[i]));
702
703 if (u->hw_dB_supported) {
704
705 if ((err = snd_mixer_selem_get_capture_dB(u->mixer_elem, u->mixer_map[i], &alsa_vol)) >= 0) {
706 s->volume.values[i] = pa_sw_volume_from_dB(alsa_vol / 100.0);
707 continue;
708 }
709
710 u->hw_dB_supported = FALSE;
711 }
712
713 if ((err = snd_mixer_selem_get_capture_volume(u->mixer_elem, u->mixer_map[i], &alsa_vol)) < 0)
714 goto fail;
715
716 s->volume.values[i] = (pa_volume_t) roundf(((float) (alsa_vol - u->hw_volume_min) * PA_VOLUME_NORM) / (u->hw_volume_max - u->hw_volume_min));
717 }
718
719 return 0;
720
721 fail:
722 pa_log_error("Unable to read volume: %s", snd_strerror(err));
723
724 return -1;
725 }
726
727 static int source_set_volume_cb(pa_source *s) {
728 struct userdata *u = s->userdata;
729 int err;
730 int i;
731
732 pa_assert(u);
733 pa_assert(u->mixer_elem);
734
735 for (i = 0; i < s->sample_spec.channels; i++) {
736 long alsa_vol;
737 pa_volume_t vol;
738
739 pa_assert(snd_mixer_selem_has_capture_channel(u->mixer_elem, u->mixer_map[i]));
740
741 vol = PA_MIN(s->volume.values[i], PA_VOLUME_NORM);
742
743 if (u->hw_dB_supported) {
744 alsa_vol = (long) (pa_sw_volume_to_dB(vol) * 100);
745 alsa_vol = PA_CLAMP_UNLIKELY(alsa_vol, u->hw_dB_min, u->hw_dB_max);
746
747
748 if ((err = snd_mixer_selem_set_capture_dB(u->mixer_elem, u->mixer_map[i], alsa_vol, -1)) >= 0) {
749
750 if (snd_mixer_selem_get_capture_dB(u->mixer_elem, u->mixer_map[i], &alsa_vol) >= 0)
751 s->volume.values[i] = pa_sw_volume_from_dB(alsa_vol / 100.0);
752
753 continue;
754 }
755
756 u->hw_dB_supported = FALSE;
757 }
758
759 alsa_vol = (long) roundf(((float) vol * (u->hw_volume_max - u->hw_volume_min)) / PA_VOLUME_NORM) + u->hw_volume_min;
760 alsa_vol = PA_CLAMP_UNLIKELY(alsa_vol, u->hw_volume_min, u->hw_volume_max);
761
762 if ((err = snd_mixer_selem_set_capture_volume(u->mixer_elem, u->mixer_map[i], alsa_vol)) < 0)
763 goto fail;
764
765 if (snd_mixer_selem_get_capture_volume(u->mixer_elem, u->mixer_map[i], &alsa_vol) >= 0)
766 s->volume.values[i] = (pa_volume_t) roundf(((float) (alsa_vol - u->hw_volume_min) * PA_VOLUME_NORM) / (u->hw_volume_max - u->hw_volume_min));
767 }
768
769 return 0;
770
771 fail:
772 pa_log_error("Unable to set volume: %s", snd_strerror(err));
773
774 return -1;
775 }
776
777 static int source_get_mute_cb(pa_source *s) {
778 struct userdata *u = s->userdata;
779 int err, sw;
780
781 pa_assert(u);
782 pa_assert(u->mixer_elem);
783
784 if ((err = snd_mixer_selem_get_capture_switch(u->mixer_elem, 0, &sw)) < 0) {
785 pa_log_error("Unable to get switch: %s", snd_strerror(err));
786 return -1;
787 }
788
789 s->muted = !sw;
790
791 return 0;
792 }
793
794 static int source_set_mute_cb(pa_source *s) {
795 struct userdata *u = s->userdata;
796 int err;
797
798 pa_assert(u);
799 pa_assert(u->mixer_elem);
800
801 if ((err = snd_mixer_selem_set_capture_switch_all(u->mixer_elem, !s->muted)) < 0) {
802 pa_log_error("Unable to set switch: %s", snd_strerror(err));
803 return -1;
804 }
805
806 return 0;
807 }
808
809 static void source_update_requested_latency_cb(pa_source *s) {
810 struct userdata *u = s->userdata;
811 pa_assert(u);
812
813 if (!u->pcm_handle)
814 return;
815
816 update_sw_params(u);
817 }
818
819 static void thread_func(void *userdata) {
820 struct userdata *u = userdata;
821
822 pa_assert(u);
823
824 pa_log_debug("Thread starting up");
825
826 if (u->core->realtime_scheduling)
827 pa_make_realtime(u->core->realtime_priority);
828
829 pa_thread_mq_install(&u->thread_mq);
830 pa_rtpoll_install(u->rtpoll);
831
832 for (;;) {
833 int ret;
834
835 /* pa_log_debug("loop"); */
836
837 /* Read some data and pass it to the sources */
838 if (PA_SOURCE_IS_OPENED(u->source->thread_info.state)) {
839 int work_done = 0;
840 pa_usec_t sleep_usec = 0;
841
842 if (u->use_mmap)
843 work_done = mmap_read(u, &sleep_usec);
844 else
845 work_done = unix_read(u, &sleep_usec);
846
847 if (work_done < 0)
848 goto fail;
849
850 /* pa_log_debug("work_done = %i", work_done); */
851
852 if (work_done)
853 update_smoother(u);
854
855 if (u->use_tsched) {
856 pa_usec_t cusec;
857
858 /* OK, the capture buffer is now empty, let's
859 * calculate when to wake up next */
860
861 /* pa_log_debug("Waking up in %0.2fms (sound card clock).", (double) sleep_usec / PA_USEC_PER_MSEC); */
862
863 /* Convert from the sound card time domain to the
864 * system time domain */
865 cusec = pa_smoother_translate(u->smoother, pa_rtclock_usec(), sleep_usec);
866
867 /* pa_log_debug("Waking up in %0.2fms (system clock).", (double) cusec / PA_USEC_PER_MSEC); */
868
869 /* We don't trust the conversion, so we wake up whatever comes first */
870 pa_rtpoll_set_timer_relative(u->rtpoll, PA_MIN(sleep_usec, cusec));
871 }
872 } else if (u->use_tsched)
873
874 /* OK, we're in an invalid state, let's disable our timers */
875 pa_rtpoll_set_timer_disabled(u->rtpoll);
876
877 /* Hmm, nothing to do. Let's sleep */
878 if ((ret = pa_rtpoll_run(u->rtpoll, 1)) < 0)
879 goto fail;
880
881 if (ret == 0)
882 goto finish;
883
884 /* Tell ALSA about this and process its response */
885 if (PA_SOURCE_IS_OPENED(u->source->thread_info.state)) {
886 struct pollfd *pollfd;
887 unsigned short revents = 0;
888 int err;
889 unsigned n;
890
891 pollfd = pa_rtpoll_item_get_pollfd(u->alsa_rtpoll_item, &n);
892
893 if ((err = snd_pcm_poll_descriptors_revents(u->pcm_handle, pollfd, n, &revents)) < 0) {
894 pa_log("snd_pcm_poll_descriptors_revents() failed: %s", snd_strerror(err));
895 goto fail;
896 }
897
898 if (revents & (POLLERR|POLLNVAL|POLLHUP)) {
899 if (pa_alsa_recover_from_poll(u->pcm_handle, revents) < 0)
900 goto fail;
901
902 snd_pcm_start(u->pcm_handle);
903 }
904
905 if (revents && u->use_tsched)
906 pa_log_debug("Wakeup from ALSA! (%i)", revents);
907 }
908 }
909
910 fail:
911 /* If this was no regular exit from the loop we have to continue
912 * processing messages until we received PA_MESSAGE_SHUTDOWN */
913 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
914 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
915
916 finish:
917 pa_log_debug("Thread shutting down");
918 }
919
920 int pa__init(pa_module*m) {
921
922 pa_modargs *ma = NULL;
923 struct userdata *u = NULL;
924 const char *dev_id;
925 pa_sample_spec ss;
926 pa_channel_map map;
927 uint32_t nfrags, hwbuf_size, frag_size, tsched_size, tsched_watermark;
928 snd_pcm_uframes_t period_frames, tsched_frames;
929 size_t frame_size;
930 snd_pcm_info_t *pcm_info = NULL;
931 int err;
932 const char *name;
933 char *name_buf = NULL;
934 pa_bool_t namereg_fail;
935 pa_bool_t use_mmap = TRUE, b, use_tsched = TRUE, d, mixer_reset = TRUE;
936 pa_source_new_data data;
937
938 snd_pcm_info_alloca(&pcm_info);
939
940 pa_assert(m);
941
942 pa_alsa_redirect_errors_inc();
943
944 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
945 pa_log("Failed to parse module arguments");
946 goto fail;
947 }
948
949 ss = m->core->default_sample_spec;
950 if (pa_modargs_get_sample_spec_and_channel_map(ma, &ss, &map, PA_CHANNEL_MAP_ALSA) < 0) {
951 pa_log("Failed to parse sample specification");
952 goto fail;
953 }
954
955 frame_size = pa_frame_size(&ss);
956
957 nfrags = m->core->default_n_fragments;
958 frag_size = pa_usec_to_bytes(m->core->default_fragment_size_msec*PA_USEC_PER_MSEC, &ss);
959 if (frag_size <= 0)
960 frag_size = frame_size;
961 tsched_size = pa_usec_to_bytes(DEFAULT_TSCHED_BUFFER_USEC, &ss);
962 tsched_watermark = pa_usec_to_bytes(DEFAULT_TSCHED_WATERMARK_USEC, &ss);
963
964 if (pa_modargs_get_value_u32(ma, "fragments", &nfrags) < 0 ||
965 pa_modargs_get_value_u32(ma, "fragment_size", &frag_size) < 0 ||
966 pa_modargs_get_value_u32(ma, "tsched_buffer_size", &tsched_size) < 0 ||
967 pa_modargs_get_value_u32(ma, "tsched_buffer_watermark", &tsched_watermark) < 0) {
968 pa_log("Failed to parse buffer metrics");
969 goto fail;
970 }
971
972 hwbuf_size = frag_size * nfrags;
973 period_frames = frag_size/frame_size;
974 tsched_frames = tsched_size/frame_size;
975
976 if (pa_modargs_get_value_boolean(ma, "mmap", &use_mmap) < 0) {
977 pa_log("Failed to parse mmap argument.");
978 goto fail;
979 }
980
981 if (pa_modargs_get_value_boolean(ma, "tsched", &use_tsched) < 0) {
982 pa_log("Failed to parse timer_scheduling argument.");
983 goto fail;
984 }
985
986 if (use_tsched && !pa_rtclock_hrtimer()) {
987 pa_log("Disabling timer-based scheduling because high-resolution timers are not available from the kernel.");
988 use_tsched = FALSE;
989 }
990
991 if (pa_modargs_get_value_boolean(ma, "mixer_reset", &mixer_reset) < 0) {
992 pa_log("Failed to parse mixer_reset argument.");
993 goto fail;
994 }
995
996 u = pa_xnew0(struct userdata, 1);
997 u->core = m->core;
998 u->module = m;
999 m->userdata = u;
1000 u->use_mmap = use_mmap;
1001 u->use_tsched = use_tsched;
1002 u->rtpoll = pa_rtpoll_new();
1003 pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll);
1004 u->alsa_rtpoll_item = NULL;
1005
1006 u->smoother = pa_smoother_new(DEFAULT_TSCHED_WATERMARK_USEC, DEFAULT_TSCHED_WATERMARK_USEC, TRUE, 5);
1007 pa_smoother_set_time_offset(u->smoother, pa_rtclock_usec());
1008
1009 snd_config_update_free_global();
1010
1011 b = use_mmap;
1012 d = use_tsched;
1013
1014 if ((dev_id = pa_modargs_get_value(ma, "device_id", NULL))) {
1015
1016 if (!(u->pcm_handle = pa_alsa_open_by_device_id(
1017 dev_id,
1018 &u->device_name,
1019 &ss, &map,
1020 SND_PCM_STREAM_CAPTURE,
1021 &nfrags, &period_frames, tsched_frames,
1022 &b, &d)))
1023 goto fail;
1024
1025 } else {
1026
1027 if (!(u->pcm_handle = pa_alsa_open_by_device_string(
1028 pa_modargs_get_value(ma, "device", DEFAULT_DEVICE),
1029 &u->device_name,
1030 &ss, &map,
1031 SND_PCM_STREAM_CAPTURE,
1032 &nfrags, &period_frames, tsched_frames,
1033 &b, &d)))
1034 goto fail;
1035 }
1036
1037 pa_assert(u->device_name);
1038 pa_log_info("Successfully opened device %s.", u->device_name);
1039
1040 if (use_mmap && !b) {
1041 pa_log_info("Device doesn't support mmap(), falling back to UNIX read/write mode.");
1042 u->use_mmap = use_mmap = FALSE;
1043 }
1044
1045 if (use_tsched && (!b || !d)) {
1046 pa_log_info("Cannot enabled timer-based scheduling, falling back to sound IRQ scheduling.");
1047 u->use_tsched = use_tsched = FALSE;
1048 }
1049
1050 if (u->use_mmap)
1051 pa_log_info("Successfully enabled mmap() mode.");
1052
1053 if (u->use_tsched)
1054 pa_log_info("Successfully enabled timer-based scheduling mode.");
1055
1056 if ((err = snd_pcm_info(u->pcm_handle, pcm_info)) < 0) {
1057 pa_log("Error fetching PCM info: %s", snd_strerror(err));
1058 goto fail;
1059 }
1060
1061 /* ALSA might tweak the sample spec, so recalculate the frame size */
1062 frame_size = pa_frame_size(&ss);
1063
1064 if ((err = snd_mixer_open(&u->mixer_handle, 0)) < 0)
1065 pa_log("Error opening mixer: %s", snd_strerror(err));
1066 else {
1067 pa_bool_t found = FALSE;
1068
1069 if (pa_alsa_prepare_mixer(u->mixer_handle, u->device_name) >= 0)
1070 found = TRUE;
1071 else {
1072 snd_pcm_info_t* info;
1073
1074 snd_pcm_info_alloca(&info);
1075
1076 if (snd_pcm_info(u->pcm_handle, info) >= 0) {
1077 char *md;
1078 int card;
1079
1080 if ((card = snd_pcm_info_get_card(info)) >= 0) {
1081
1082 md = pa_sprintf_malloc("hw:%i", card);
1083
1084 if (strcmp(u->device_name, md))
1085 if (pa_alsa_prepare_mixer(u->mixer_handle, md) >= 0)
1086 found = TRUE;
1087 pa_xfree(md);
1088 }
1089 }
1090 }
1091
1092 if (found)
1093 if (!(u->mixer_elem = pa_alsa_find_elem(u->mixer_handle, "Capture", "Mic")))
1094 found = FALSE;
1095
1096 if (!found) {
1097 snd_mixer_close(u->mixer_handle);
1098 u->mixer_handle = NULL;
1099 }
1100 }
1101
1102 if ((name = pa_modargs_get_value(ma, "source_name", NULL)))
1103 namereg_fail = TRUE;
1104 else {
1105 name = name_buf = pa_sprintf_malloc("alsa_input.%s", u->device_name);
1106 namereg_fail = FALSE;
1107 }
1108
1109 pa_source_new_data_init(&data);
1110 data.driver = __FILE__;
1111 data.module = m;
1112 pa_source_new_data_set_name(&data, name);
1113 data.namereg_fail = namereg_fail;
1114 pa_source_new_data_set_sample_spec(&data, &ss);
1115 pa_source_new_data_set_channel_map(&data, &map);
1116
1117 pa_alsa_init_proplist(data.proplist, pcm_info);
1118 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, u->device_name);
1119 pa_proplist_setf(data.proplist, PA_PROP_DEVICE_BUFFERING_BUFFER_SIZE, "%lu", (unsigned long) (period_frames * frame_size * nfrags));
1120 pa_proplist_setf(data.proplist, PA_PROP_DEVICE_BUFFERING_FRAGMENT_SIZE, "%lu", (unsigned long) (period_frames * frame_size));
1121 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_ACCESS_MODE, u->use_tsched ? "mmap+timer" : (u->use_mmap ? "mmap" : "serial"));
1122
1123 u->source = pa_source_new(m->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1124 pa_source_new_data_done(&data);
1125 pa_xfree(name_buf);
1126
1127 if (!u->source) {
1128 pa_log("Failed to create source object");
1129 goto fail;
1130 }
1131
1132 u->source->parent.process_msg = source_process_msg;
1133 u->source->update_requested_latency = source_update_requested_latency_cb;
1134 u->source->userdata = u;
1135
1136 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1137 pa_source_set_rtpoll(u->source, u->rtpoll);
1138
1139 u->frame_size = frame_size;
1140 u->fragment_size = frag_size = period_frames * frame_size;
1141 u->nfragments = nfrags;
1142 u->hwbuf_size = u->fragment_size * nfrags;
1143 u->hwbuf_unused_frames = 0;
1144 u->tsched_watermark = tsched_watermark;
1145 u->frame_index = 0;
1146 u->hw_dB_supported = FALSE;
1147 u->hw_dB_min = u->hw_dB_max = 0;
1148 u->hw_volume_min = u->hw_volume_max = 0;
1149
1150 if (use_tsched)
1151 fix_tsched_watermark(u);
1152
1153 pa_source_set_latency_range(u->source,
1154 !use_tsched ? pa_bytes_to_usec(u->hwbuf_size, &ss) : (pa_usec_t) -1,
1155 pa_bytes_to_usec(u->hwbuf_size, &ss));
1156
1157 pa_log_info("Using %u fragments of size %lu bytes, buffer time is %0.2fms",
1158 nfrags, (long unsigned) u->fragment_size,
1159 (double) pa_bytes_to_usec(u->hwbuf_size, &ss) / PA_USEC_PER_MSEC);
1160
1161 if (use_tsched)
1162 pa_log_info("Time scheduling watermark is %0.2fms",
1163 (double) pa_bytes_to_usec(u->tsched_watermark, &ss) / PA_USEC_PER_MSEC);
1164
1165 if (update_sw_params(u) < 0)
1166 goto fail;
1167
1168 if (u->mixer_handle) {
1169 pa_assert(u->mixer_elem);
1170
1171 if (snd_mixer_selem_has_capture_volume(u->mixer_elem))
1172 if (pa_alsa_calc_mixer_map(u->mixer_elem, &map, u->mixer_map, FALSE) >= 0 &&
1173 snd_mixer_selem_get_capture_volume_range(u->mixer_elem, &u->hw_volume_min, &u->hw_volume_max) >= 0) {
1174
1175 pa_bool_t suitable = TRUE;
1176
1177 pa_log_info("Volume ranges from %li to %li.", u->hw_volume_min, u->hw_volume_max);
1178
1179 if (u->hw_volume_min > u->hw_volume_max) {
1180
1181 pa_log_info("Minimal volume %li larger than maximum volume %li. Strange stuff Falling back to software volume control.", u->hw_volume_min, u->hw_volume_max);
1182 suitable = FALSE;
1183
1184 } else if (u->hw_volume_max - u->hw_volume_min < 3) {
1185
1186 pa_log_info("Device has less than 4 volume levels. Falling back to software volume control.");
1187 suitable = FALSE;
1188
1189 } else if (snd_mixer_selem_get_capture_dB_range(u->mixer_elem, &u->hw_dB_min, &u->hw_dB_max) >= 0) {
1190
1191 pa_log_info("Volume ranges from %0.2f dB to %0.2f dB.", u->hw_dB_min/100.0, u->hw_dB_max/100.0);
1192
1193 /* Let's see if this thing actually is useful for muting */
1194 if (u->hw_dB_min > -6000) {
1195 pa_log_info("Device cannot attenuate for more than -60 dB (only %0.2f dB supported), falling back to software volume control.", ((double) u->hw_dB_min) / 100);
1196
1197 suitable = FALSE;
1198 } else if (u->hw_dB_max < 0) {
1199
1200 pa_log_info("Device is still attenuated at maximum volume setting (%0.2f dB is maximum). Strange stuff. Falling back to software volume control.", ((double) u->hw_dB_max) / 100);
1201 suitable = FALSE;
1202
1203 } else if (u->hw_dB_min >= u->hw_dB_max) {
1204
1205 pa_log_info("Minimal dB (%0.2f) larger or equal to maximum dB (%0.2f). Strange stuff. Falling back to software volume control.", ((double) u->hw_dB_min) / 100, ((double) u->hw_dB_max) / 100);
1206 suitable = FALSE;
1207
1208 } else
1209 u->hw_dB_supported = TRUE;
1210 }
1211
1212 if (suitable) {
1213 u->source->get_volume = source_get_volume_cb;
1214 u->source->set_volume = source_set_volume_cb;
1215 u->source->flags |= PA_SOURCE_HW_VOLUME_CTRL | (u->hw_dB_supported ? PA_SOURCE_DECIBEL_VOLUME : 0);
1216 pa_log_info("Using hardware volume control. Hardware dB scale %s.", u->hw_dB_supported ? "supported" : "not supported");
1217
1218 } else if (mixer_reset) {
1219 pa_log_info("Using software volume control. Trying to reset sound card to 0 dB.");
1220 pa_alsa_0dB_capture(u->mixer_elem);
1221 } else
1222 pa_log_info("Using software volume control. Leaving hw mixer controls untouched.");
1223
1224 }
1225
1226
1227 if (snd_mixer_selem_has_capture_switch(u->mixer_elem)) {
1228 u->source->get_mute = source_get_mute_cb;
1229 u->source->set_mute = source_set_mute_cb;
1230 u->source->flags |= PA_SOURCE_HW_MUTE_CTRL;
1231 }
1232
1233 u->mixer_fdl = pa_alsa_fdlist_new();
1234
1235 if (pa_alsa_fdlist_set_mixer(u->mixer_fdl, u->mixer_handle, m->core->mainloop) < 0) {
1236 pa_log("Failed to initialize file descriptor monitoring");
1237 goto fail;
1238 }
1239
1240 snd_mixer_elem_set_callback(u->mixer_elem, mixer_callback);
1241 snd_mixer_elem_set_callback_private(u->mixer_elem, u);
1242 } else
1243 u->mixer_fdl = NULL;
1244
1245 pa_alsa_dump(u->pcm_handle);
1246
1247 if (!(u->thread = pa_thread_new(thread_func, u))) {
1248 pa_log("Failed to create thread.");
1249 goto fail;
1250 }
1251 /* Get initial mixer settings */
1252 if (data.volume_is_set) {
1253 if (u->source->set_volume)
1254 u->source->set_volume(u->source);
1255 } else {
1256 if (u->source->get_volume)
1257 u->source->get_volume(u->source);
1258 }
1259
1260 if (data.muted_is_set) {
1261 if (u->source->set_mute)
1262 u->source->set_mute(u->source);
1263 } else {
1264 if (u->source->get_mute)
1265 u->source->get_mute(u->source);
1266 }
1267
1268 pa_source_put(u->source);
1269
1270 pa_modargs_free(ma);
1271
1272 return 0;
1273
1274 fail:
1275
1276 if (ma)
1277 pa_modargs_free(ma);
1278
1279 pa__done(m);
1280
1281 return -1;
1282 }
1283
1284 void pa__done(pa_module*m) {
1285 struct userdata *u;
1286
1287 pa_assert(m);
1288
1289 if (!(u = m->userdata)) {
1290 pa_alsa_redirect_errors_dec();
1291 return;
1292 }
1293
1294 if (u->source)
1295 pa_source_unlink(u->source);
1296
1297 if (u->thread) {
1298 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1299 pa_thread_free(u->thread);
1300 }
1301
1302 pa_thread_mq_done(&u->thread_mq);
1303
1304 if (u->source)
1305 pa_source_unref(u->source);
1306
1307 if (u->alsa_rtpoll_item)
1308 pa_rtpoll_item_free(u->alsa_rtpoll_item);
1309
1310 if (u->rtpoll)
1311 pa_rtpoll_free(u->rtpoll);
1312
1313 if (u->mixer_fdl)
1314 pa_alsa_fdlist_free(u->mixer_fdl);
1315
1316 if (u->mixer_handle)
1317 snd_mixer_close(u->mixer_handle);
1318
1319 if (u->pcm_handle) {
1320 snd_pcm_drop(u->pcm_handle);
1321 snd_pcm_close(u->pcm_handle);
1322 }
1323
1324 if (u->smoother)
1325 pa_smoother_free(u->smoother);
1326
1327 pa_xfree(u->device_name);
1328 pa_xfree(u);
1329
1330 snd_config_update_free_global();
1331 pa_alsa_redirect_errors_dec();
1332 }