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