]> code.delx.au - pulseaudio/blob - src/modules/module-alsa-source.c
commit glitch-free work
[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 device id> "
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
76 #define DEFAULT_DEVICE "default"
77 #define DEFAULT_TSCHED_BUFFER_USEC (2*PA_USEC_PER_SEC)
78 #define DEFAULT_TSCHED_WATERMARK_USEC (10*PA_USEC_PER_MSEC)
79
80 struct userdata {
81 pa_core *core;
82 pa_module *module;
83 pa_source *source;
84
85 pa_thread *thread;
86 pa_thread_mq thread_mq;
87 pa_rtpoll *rtpoll;
88
89 snd_pcm_t *pcm_handle;
90
91 pa_alsa_fdlist *mixer_fdl;
92 snd_mixer_t *mixer_handle;
93 snd_mixer_elem_t *mixer_elem;
94 long hw_volume_max, hw_volume_min;
95
96 size_t frame_size, fragment_size, hwbuf_size, tsched_watermark;
97 unsigned nfragments;
98
99 char *device_name;
100
101 pa_bool_t use_mmap, use_tsched;
102
103 pa_rtpoll_item *alsa_rtpoll_item;
104
105 snd_mixer_selem_channel_id_t mixer_map[SND_MIXER_SCHN_LAST];
106
107 pa_smoother *smoother;
108 int64_t frame_index;
109 };
110
111 static const char* const valid_modargs[] = {
112 "source_name",
113 "device",
114 "device_id",
115 "format",
116 "rate",
117 "channels",
118 "channel_map",
119 "fragments",
120 "fragment_size",
121 "mmap",
122 "tsched",
123 "tsched_buffer_size",
124 "tsched_buffer_watermark",
125 NULL
126 };
127
128 static int mmap_read(struct userdata *u) {
129 int work_done = 0;
130
131 pa_assert(u);
132 pa_source_assert_ref(u->source);
133
134 for (;;) {
135 snd_pcm_sframes_t n;
136 int err;
137 const snd_pcm_channel_area_t *areas;
138 snd_pcm_uframes_t offset, frames;
139 pa_memchunk chunk;
140 void *p;
141
142 if (PA_UNLIKELY((n = snd_pcm_avail_update(u->pcm_handle)) < 0)) {
143
144 if (n == -EPIPE)
145 pa_log_debug("snd_pcm_avail_update: Buffer underrun!");
146
147 if ((err = snd_pcm_recover(u->pcm_handle, n, 1)) == 0)
148 continue;
149
150 if (err == -EAGAIN)
151 return work_done;
152
153 pa_log("snd_pcm_avail_update: %s", snd_strerror(err));
154 return -1;
155 }
156
157 if (PA_UNLIKELY(n <= 0))
158 return work_done;
159
160 frames = n;
161
162 if (PA_UNLIKELY((err = snd_pcm_mmap_begin(u->pcm_handle, &areas, &offset, &frames)) < 0)) {
163
164 if (err == -EPIPE)
165 pa_log_debug("snd_pcm_mmap_begin: Buffer underrun!");
166
167 if ((err = snd_pcm_recover(u->pcm_handle, err, 1)) == 0)
168 continue;
169
170 if (err == -EAGAIN)
171 return work_done;
172
173 pa_log("Failed to write data to DSP: %s", snd_strerror(err));
174 return -1;
175 }
176
177 /* Check these are multiples of 8 bit */
178 pa_assert((areas[0].first & 7) == 0);
179 pa_assert((areas[0].step & 7)== 0);
180
181 /* We assume a single interleaved memory buffer */
182 pa_assert((areas[0].first >> 3) == 0);
183 pa_assert((areas[0].step >> 3) == u->frame_size);
184
185 p = (uint8_t*) areas[0].addr + (offset * u->frame_size);
186
187 chunk.memblock = pa_memblock_new_fixed(u->core->mempool, p, frames * u->frame_size, 1);
188 chunk.length = pa_memblock_get_length(chunk.memblock);
189 chunk.index = 0;
190
191 pa_source_post(u->source, &chunk);
192
193 /* FIXME: Maybe we can do something to keep this memory block
194 * a little bit longer around? */
195 pa_memblock_unref_fixed(chunk.memblock);
196
197 if (PA_UNLIKELY((err = snd_pcm_mmap_commit(u->pcm_handle, offset, frames)) < 0)) {
198
199 if (err == -EPIPE)
200 pa_log_debug("snd_pcm_mmap_commit: Buffer underrun!");
201
202 if ((err = snd_pcm_recover(u->pcm_handle, err, 1)) == 0)
203 continue;
204
205 if (err == -EAGAIN)
206 return work_done;
207
208 pa_log("Failed to write data to DSP: %s", snd_strerror(err));
209 return -1;
210 }
211
212 work_done = 1;
213
214 u->frame_index += frames;
215
216 if (PA_LIKELY(frames >= (snd_pcm_uframes_t) n))
217 return work_done;
218 }
219 }
220
221 static int unix_read(struct userdata *u) {
222 snd_pcm_status_t *status;
223 int work_done = 0;
224
225 snd_pcm_status_alloca(&status);
226
227 pa_assert(u);
228 pa_source_assert_ref(u->source);
229
230 for (;;) {
231 void *p;
232 snd_pcm_sframes_t n, frames;
233 int err;
234 pa_memchunk chunk;
235
236 if (PA_UNLIKELY((err = snd_pcm_status(u->pcm_handle, status)) < 0)) {
237 pa_log("Failed to query DSP status data: %s", snd_strerror(err));
238 return -1;
239 }
240
241 if (PA_UNLIKELY(snd_pcm_status_get_avail_max(status)*u->frame_size >= u->hwbuf_size))
242 pa_log_debug("Buffer overrun!");
243
244 n = snd_pcm_status_get_avail(status);
245
246 if (PA_UNLIKELY(n <= 0))
247 return work_done;
248
249 chunk.memblock = pa_memblock_new(u->core->mempool, (size_t) -1);
250
251 frames = pa_memblock_get_length(chunk.memblock) / u->frame_size;
252
253 if (frames > n)
254 frames = n;
255
256 p = pa_memblock_acquire(chunk.memblock);
257 frames = snd_pcm_readi(u->pcm_handle, (uint8_t*) p, frames);
258 pa_memblock_release(chunk.memblock);
259
260 pa_assert(frames != 0);
261
262 if (PA_UNLIKELY(frames < 0)) {
263 pa_memblock_unref(chunk.memblock);
264
265 if ((frames = snd_pcm_recover(u->pcm_handle, frames, 1)) == 0)
266 continue;
267
268 if (frames == -EAGAIN)
269 return work_done;
270
271 pa_log("Failed to read data from DSP: %s", snd_strerror(frames));
272 return -1;
273 }
274
275 chunk.index = 0;
276 chunk.length = frames * u->frame_size;
277
278 pa_source_post(u->source, &chunk);
279 pa_memblock_unref(chunk.memblock);
280
281 work_done = 1;
282
283 u->frame_index += frames;
284
285 if (PA_LIKELY(frames >= n))
286 return work_done;
287 }
288 }
289
290 static int update_smoother(struct userdata *u) {
291 snd_pcm_status_t *status;
292 int64_t frames;
293 int err;
294
295 pa_assert(u);
296 pa_assert(u->pcm_handle);
297
298 snd_pcm_status_alloca(&status);
299
300 /* Let's update the time smoother */
301
302 if (PA_UNLIKELY((err = snd_pcm_status(u->pcm_handle, status)) < 0)) {
303 pa_log("Failed to get delay: %s", snd_strerror(err));
304 return -1;
305 }
306
307 frames = u->frame_index + snd_pcm_status_get_delay(status);
308
309 pa_smoother_put(u->smoother, pa_rtclock_usec(), pa_bytes_to_usec(frames * u->frame_size, &u->source->sample_spec));
310
311 return 0;
312 }
313
314 static pa_usec_t source_get_latency(struct userdata *u) {
315 pa_usec_t r = 0;
316 int64_t delay;
317
318 pa_assert(u);
319
320 delay = pa_smoother_get(u->smoother, pa_rtclock_usec()) - u->frame_index;
321
322 if (delay > 0)
323 r = pa_bytes_to_usec(delay * u->frame_size, &u->source->sample_spec);
324
325 return r;
326 }
327
328 static int build_pollfd(struct userdata *u) {
329 int err;
330 struct pollfd *pollfd;
331 int n;
332
333 pa_assert(u);
334 pa_assert(u->pcm_handle);
335
336 if ((n = snd_pcm_poll_descriptors_count(u->pcm_handle)) < 0) {
337 pa_log("snd_pcm_poll_descriptors_count() failed: %s", snd_strerror(n));
338 return -1;
339 }
340
341 if (u->alsa_rtpoll_item)
342 pa_rtpoll_item_free(u->alsa_rtpoll_item);
343
344 u->alsa_rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, n);
345 pollfd = pa_rtpoll_item_get_pollfd(u->alsa_rtpoll_item, NULL);
346
347 if ((err = snd_pcm_poll_descriptors(u->pcm_handle, pollfd, n)) < 0) {
348 pa_log("snd_pcm_poll_descriptors() failed: %s", snd_strerror(err));
349 return -1;
350 }
351
352 return 0;
353 }
354
355 static int suspend(struct userdata *u) {
356 pa_assert(u);
357 pa_assert(u->pcm_handle);
358
359 pa_smoother_pause(u->smoother, pa_rtclock_usec());
360
361 /* Let's suspend */
362 snd_pcm_close(u->pcm_handle);
363 u->pcm_handle = NULL;
364
365 if (u->alsa_rtpoll_item) {
366 pa_rtpoll_item_free(u->alsa_rtpoll_item);
367 u->alsa_rtpoll_item = NULL;
368 }
369
370 pa_log_info("Device suspended...");
371
372 return 0;
373 }
374
375 static pa_usec_t hw_sleep_time(struct userdata *u) {
376 pa_usec_t usec;
377
378 pa_assert(u);
379
380 usec = pa_source_get_requested_latency(u->source);
381
382 if (usec <= 0)
383 usec = pa_bytes_to_usec(u->hwbuf_size, &u->source->sample_spec);
384
385 if (usec >= u->tsched_watermark)
386 usec -= u->tsched_watermark;
387 else
388 usec /= 2;
389
390 return usec;
391 }
392
393 static int update_sw_params(struct userdata *u) {
394 size_t avail_min;
395 int err;
396
397 pa_assert(u);
398
399 if (u->use_tsched) {
400 pa_usec_t usec;
401
402 usec = hw_sleep_time(u);
403
404 avail_min = pa_usec_to_bytes(usec, &u->source->sample_spec);
405
406 if (avail_min <= 0)
407 avail_min = 1;
408
409 } else
410 avail_min = 1;
411
412 if ((err = pa_alsa_set_sw_params(u->pcm_handle, avail_min)) < 0) {
413 pa_log("Failed to set software parameters: %s", snd_strerror(err));
414 return err;
415 }
416
417 return 0;
418 }
419
420 static int unsuspend(struct userdata *u) {
421 pa_sample_spec ss;
422 int err;
423 pa_bool_t b, d;
424 unsigned nfrags;
425 snd_pcm_uframes_t period_size;
426
427 pa_assert(u);
428 pa_assert(!u->pcm_handle);
429
430 pa_log_info("Trying resume...");
431
432 snd_config_update_free_global();
433 if ((err = snd_pcm_open(&u->pcm_handle, u->device_name, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK)) < 0) {
434 pa_log("Error opening PCM device %s: %s", u->device_name, snd_strerror(err));
435 goto fail;
436 }
437
438 ss = u->source->sample_spec;
439 nfrags = u->nfragments;
440 period_size = u->fragment_size / u->frame_size;
441 b = u->use_mmap;
442 d = u->use_tsched;
443
444 if ((err = pa_alsa_set_hw_params(u->pcm_handle, &ss, &nfrags, &period_size, u->hwbuf_size / u->frame_size, &b, &d, TRUE)) < 0) {
445 pa_log("Failed to set hardware parameters: %s", snd_strerror(err));
446 goto fail;
447 }
448
449 if (b != u->use_mmap || d != u->use_tsched) {
450 pa_log_warn("Resume failed, couldn't get original access mode.");
451 goto fail;
452 }
453
454 if (!pa_sample_spec_equal(&ss, &u->source->sample_spec)) {
455 pa_log_warn("Resume failed, couldn't restore original sample settings.");
456 goto fail;
457 }
458
459 if (nfrags != u->nfragments || period_size*u->frame_size != u->fragment_size) {
460 pa_log_warn("Resume failed, couldn't restore original fragment settings.");
461 goto fail;
462 }
463
464 if (update_sw_params(u) < 0)
465 goto fail;
466
467 if (build_pollfd(u) < 0)
468 goto fail;
469
470 /* FIXME: We need to reload the volume somehow */
471
472 snd_pcm_start(u->pcm_handle);
473
474 pa_smoother_resume(u->smoother, pa_rtclock_usec());
475
476 pa_log_info("Resumed successfully...");
477
478 return 0;
479
480 fail:
481 if (u->pcm_handle) {
482 snd_pcm_close(u->pcm_handle);
483 u->pcm_handle = NULL;
484 }
485
486 return -1;
487 }
488
489 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
490 struct userdata *u = PA_SOURCE(o)->userdata;
491
492 switch (code) {
493
494 case PA_SOURCE_MESSAGE_GET_LATENCY: {
495 pa_usec_t r = 0;
496
497 if (u->pcm_handle)
498 r = source_get_latency(u);
499
500 *((pa_usec_t*) data) = r;
501
502 return 0;
503 }
504
505 case PA_SOURCE_MESSAGE_SET_STATE:
506
507 switch ((pa_source_state_t) PA_PTR_TO_UINT(data)) {
508
509 case PA_SOURCE_SUSPENDED:
510 pa_assert(PA_SOURCE_OPENED(u->source->thread_info.state));
511
512 if (suspend(u) < 0)
513 return -1;
514
515 break;
516
517 case PA_SOURCE_IDLE:
518 case PA_SOURCE_RUNNING:
519
520 if (u->source->thread_info.state == PA_SOURCE_INIT) {
521 if (build_pollfd(u) < 0)
522 return -1;
523
524 snd_pcm_start(u->pcm_handle);
525 }
526
527 if (u->source->thread_info.state == PA_SOURCE_SUSPENDED) {
528 if (unsuspend(u) < 0)
529 return -1;
530 }
531
532 break;
533
534 case PA_SOURCE_UNLINKED:
535 case PA_SOURCE_INIT:
536 ;
537 }
538
539 break;
540 }
541
542 return pa_source_process_msg(o, code, data, offset, chunk);
543 }
544
545 static int mixer_callback(snd_mixer_elem_t *elem, unsigned int mask) {
546 struct userdata *u = snd_mixer_elem_get_callback_private(elem);
547
548 pa_assert(u);
549 pa_assert(u->mixer_handle);
550
551 if (mask == SND_CTL_EVENT_MASK_REMOVE)
552 return 0;
553
554 if (mask & SND_CTL_EVENT_MASK_VALUE) {
555 pa_source_get_volume(u->source);
556 pa_source_get_mute(u->source);
557 }
558
559 return 0;
560 }
561
562 static int source_get_volume_cb(pa_source *s) {
563 struct userdata *u = s->userdata;
564 int err;
565 int i;
566
567 pa_assert(u);
568 pa_assert(u->mixer_elem);
569
570 for (i = 0; i < s->sample_spec.channels; i++) {
571 long set_vol, vol;
572
573 pa_assert(snd_mixer_selem_has_capture_channel(u->mixer_elem, u->mixer_map[i]));
574
575 if ((err = snd_mixer_selem_get_capture_volume(u->mixer_elem, u->mixer_map[i], &vol)) < 0)
576 goto fail;
577
578 set_vol = (long) roundf(((float) s->volume.values[i] * (u->hw_volume_max - u->hw_volume_min)) / PA_VOLUME_NORM) + u->hw_volume_min;
579
580 /* Try to avoid superfluous volume changes */
581 if (set_vol != vol)
582 s->volume.values[i] = (pa_volume_t) roundf(((float) (vol - u->hw_volume_min) * PA_VOLUME_NORM) / (u->hw_volume_max - u->hw_volume_min));
583 }
584
585 return 0;
586
587 fail:
588 pa_log_error("Unable to read volume: %s", snd_strerror(err));
589
590 s->get_volume = NULL;
591 s->set_volume = NULL;
592 return -1;
593 }
594
595 static int source_set_volume_cb(pa_source *s) {
596 struct userdata *u = s->userdata;
597 int err;
598 int i;
599
600 pa_assert(u);
601 pa_assert(u->mixer_elem);
602
603 for (i = 0; i < s->sample_spec.channels; i++) {
604 long alsa_vol;
605 pa_volume_t vol;
606
607 pa_assert(snd_mixer_selem_has_capture_channel(u->mixer_elem, u->mixer_map[i]));
608
609 vol = s->volume.values[i];
610
611 if (vol > PA_VOLUME_NORM)
612 vol = PA_VOLUME_NORM;
613
614 alsa_vol = (long) roundf(((float) vol * (u->hw_volume_max - u->hw_volume_min)) / PA_VOLUME_NORM) + u->hw_volume_min;
615
616 if ((err = snd_mixer_selem_set_capture_volume(u->mixer_elem, u->mixer_map[i], alsa_vol)) < 0)
617 goto fail;
618 }
619
620 return 0;
621
622 fail:
623 pa_log_error("Unable to set volume: %s", snd_strerror(err));
624
625 s->get_volume = NULL;
626 s->set_volume = NULL;
627 return -1;
628 }
629
630 static int source_get_mute_cb(pa_source *s) {
631 struct userdata *u = s->userdata;
632 int err, sw;
633
634 pa_assert(u);
635 pa_assert(u->mixer_elem);
636
637 if ((err = snd_mixer_selem_get_capture_switch(u->mixer_elem, 0, &sw)) < 0) {
638 pa_log_error("Unable to get switch: %s", snd_strerror(err));
639
640 s->get_mute = NULL;
641 s->set_mute = NULL;
642 return -1;
643 }
644
645 s->muted = !sw;
646
647 return 0;
648 }
649
650 static int source_set_mute_cb(pa_source *s) {
651 struct userdata *u = s->userdata;
652 int err;
653
654 pa_assert(u);
655 pa_assert(u->mixer_elem);
656
657 if ((err = snd_mixer_selem_set_capture_switch_all(u->mixer_elem, !s->muted)) < 0) {
658 pa_log_error("Unable to set switch: %s", snd_strerror(err));
659
660 s->get_mute = NULL;
661 s->set_mute = NULL;
662 return -1;
663 }
664
665 return 0;
666 }
667
668 static void thread_func(void *userdata) {
669 struct userdata *u = userdata;
670
671 pa_assert(u);
672
673 pa_log_debug("Thread starting up");
674
675 if (u->core->realtime_scheduling)
676 pa_make_realtime(u->core->realtime_priority);
677
678 pa_thread_mq_install(&u->thread_mq);
679 pa_rtpoll_install(u->rtpoll);
680
681 for (;;) {
682 int ret;
683
684 /* Read some data and pass it to the sources */
685 if (PA_SOURCE_OPENED(u->source->thread_info.state)) {
686 int work_done = 0;
687
688 if (u->use_mmap) {
689 if ((work_done = mmap_read(u)) < 0)
690 goto fail;
691
692 } else {
693 if ((work_done = unix_read(u) < 0))
694 goto fail;
695 }
696
697 if (update_smoother(u) < 0)
698 goto fail;
699
700 if (u->use_tsched && work_done) {
701 pa_usec_t usec, cusec;
702
703 /* OK, the capture buffer is now empty, let's
704 * calculate when to wake up next */
705
706 usec = hw_sleep_time(u);
707
708 pa_log_debug("Waking up in %0.2fms (sound card clock).", (double) usec / PA_USEC_PER_MSEC);
709
710 /* Convert from the sound card time domain to the
711 * system time domain */
712 cusec = pa_smoother_translate(u->smoother, pa_rtclock_usec(), usec);
713
714 pa_log_debug("Waking up in %0.2fms (system clock).", (double) cusec / PA_USEC_PER_MSEC);
715
716 /* We don't trust the conversion, so we wake up whatever comes first */
717 pa_rtpoll_set_timer_relative(u->rtpoll, PA_MIN(usec, cusec));
718 }
719 }
720
721 /* Hmm, nothing to do. Let's sleep */
722 if ((ret = pa_rtpoll_run(u->rtpoll, 1)) < 0)
723 goto fail;
724
725 if (ret == 0)
726 goto finish;
727
728 /* Tell ALSA about this and process its response */
729 if (PA_SOURCE_OPENED(u->source->thread_info.state)) {
730 struct pollfd *pollfd;
731 unsigned short revents = 0;
732 int err;
733 unsigned n;
734
735 pollfd = pa_rtpoll_item_get_pollfd(u->alsa_rtpoll_item, &n);
736
737 if ((err = snd_pcm_poll_descriptors_revents(u->pcm_handle, pollfd, n, &revents)) < 0) {
738 pa_log("snd_pcm_poll_descriptors_revents() failed: %s", snd_strerror(err));
739 goto fail;
740 }
741
742 if (revents & (POLLERR|POLLNVAL|POLLHUP)) {
743
744 if (revents & POLLERR)
745 pa_log_warn("Got POLLERR from ALSA");
746 if (revents & POLLNVAL)
747 pa_log_warn("Got POLLNVAL from ALSA");
748 if (revents & POLLHUP)
749 pa_log_warn("Got POLLHUP from ALSA");
750
751 /* Try to recover from this error */
752
753 switch (snd_pcm_state(u->pcm_handle)) {
754
755 case SND_PCM_STATE_XRUN:
756 if ((err = snd_pcm_recover(u->pcm_handle, -EPIPE, 1)) != 0) {
757 pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP and XRUN: %s", snd_strerror(err));
758 goto fail;
759 }
760 break;
761
762 case SND_PCM_STATE_SUSPENDED:
763 if ((err = snd_pcm_recover(u->pcm_handle, -ESTRPIPE, 1)) != 0) {
764 pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP and SUSPENDED: %s", snd_strerror(err));
765 goto fail;
766 }
767 break;
768
769 default:
770
771 snd_pcm_drop(u->pcm_handle);
772
773 if ((err = snd_pcm_prepare(u->pcm_handle)) < 0) {
774 pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP with snd_pcm_prepare(): %s", snd_strerror(err));
775 goto fail;
776 }
777 break;
778 }
779 }
780 }
781 }
782
783 fail:
784 /* If this was no regular exit from the loop we have to continue
785 * processing messages until we received PA_MESSAGE_SHUTDOWN */
786 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
787 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
788
789 finish:
790 pa_log_debug("Thread shutting down");
791 }
792
793 int pa__init(pa_module*m) {
794
795 pa_modargs *ma = NULL;
796 struct userdata *u = NULL;
797 const char *dev_id;
798 pa_sample_spec ss;
799 pa_channel_map map;
800 uint32_t nfrags, frag_size, tsched_size, tsched_watermark;
801 snd_pcm_uframes_t period_frames, tsched_frames;
802 size_t frame_size;
803 snd_pcm_info_t *pcm_info = NULL;
804 int err;
805 const char *name;
806 char *name_buf = NULL;
807 pa_bool_t namereg_fail;
808 pa_bool_t use_mmap = TRUE, b, use_tsched = TRUE, d;
809 pa_source_new_data data;
810 static const char * const class_table[SND_PCM_CLASS_LAST+1] = {
811 [SND_PCM_CLASS_GENERIC] = "sound",
812 [SND_PCM_CLASS_MULTI] = NULL,
813 [SND_PCM_CLASS_MODEM] = "modem",
814 [SND_PCM_CLASS_DIGITIZER] = NULL
815 };
816
817 snd_pcm_info_alloca(&pcm_info);
818
819 pa_assert(m);
820
821 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
822 pa_log("Failed to parse module arguments");
823 goto fail;
824 }
825
826 ss = m->core->default_sample_spec;
827 if (pa_modargs_get_sample_spec_and_channel_map(ma, &ss, &map, PA_CHANNEL_MAP_ALSA) < 0) {
828 pa_log("Failed to parse sample specification");
829 goto fail;
830 }
831
832 frame_size = pa_frame_size(&ss);
833
834 nfrags = m->core->default_n_fragments;
835 frag_size = pa_usec_to_bytes(m->core->default_fragment_size_msec*PA_USEC_PER_MSEC, &ss);
836 if (frag_size <= 0)
837 frag_size = frame_size;
838 tsched_size = pa_usec_to_bytes(DEFAULT_TSCHED_BUFFER_USEC, &ss);
839 tsched_watermark = pa_usec_to_bytes(DEFAULT_TSCHED_WATERMARK_USEC, &ss);
840
841 if (pa_modargs_get_value_u32(ma, "fragments", &nfrags) < 0 ||
842 pa_modargs_get_value_u32(ma, "fragment_size", &frag_size) < 0 ||
843 pa_modargs_get_value_u32(ma, "tsched_buffer_size", &tsched_size) < 0 ||
844 pa_modargs_get_value_u32(ma, "tsched_buffer_watermark", &tsched_watermark) < 0) {
845 pa_log("Failed to parse buffer metrics");
846 goto fail;
847 }
848
849 period_frames = frag_size/frame_size;
850 tsched_frames = tsched_size/frame_size;
851
852 if (pa_modargs_get_value_boolean(ma, "mmap", &use_mmap) < 0) {
853 pa_log("Failed to parse mmap argument.");
854 goto fail;
855 }
856
857 if (pa_modargs_get_value_boolean(ma, "tsched", &use_tsched) < 0) {
858 pa_log("Failed to parse timer_scheduling argument.");
859 goto fail;
860 }
861
862 if (use_tsched && !pa_rtclock_hrtimer()) {
863 pa_log("Disabling timer-based scheduling because high-resolution timers are not available from the kernel.");
864 use_tsched = FALSE;
865 }
866
867 u = pa_xnew0(struct userdata, 1);
868 u->core = m->core;
869 u->module = m;
870 m->userdata = u;
871 u->use_mmap = use_mmap;
872 u->use_tsched = use_tsched;
873 pa_thread_mq_init(&u->thread_mq, m->core->mainloop);
874 u->rtpoll = pa_rtpoll_new();
875 u->alsa_rtpoll_item = NULL;
876 pa_rtpoll_item_new_asyncmsgq(u->rtpoll, PA_RTPOLL_EARLY, u->thread_mq.inq);
877 u->smoother = pa_smoother_new(DEFAULT_TSCHED_WATERMARK_USEC, DEFAULT_TSCHED_WATERMARK_USEC, TRUE);
878 pa_smoother_set_time_offset(u->smoother, pa_rtclock_usec());
879
880 snd_config_update_free_global();
881
882 b = use_mmap;
883 d = use_tsched;
884
885 if ((dev_id = pa_modargs_get_value(ma, "device_id", NULL))) {
886
887 if (!(u->pcm_handle = pa_alsa_open_by_device_id(
888 dev_id,
889 &u->device_name,
890 &ss, &map,
891 SND_PCM_STREAM_CAPTURE,
892 &nfrags, &period_frames, tsched_frames,
893 &b, &d)))
894 goto fail;
895
896 } else {
897
898 if (!(u->pcm_handle = pa_alsa_open_by_device_string(
899 pa_modargs_get_value(ma, "device", DEFAULT_DEVICE),
900 &u->device_name,
901 &ss, &map,
902 SND_PCM_STREAM_CAPTURE,
903 &nfrags, &period_frames, tsched_frames,
904 &b, &d)))
905 goto fail;
906 }
907
908 pa_assert(u->device_name);
909 pa_log_info("Successfully opened device %s.", u->device_name);
910
911 if (use_mmap && !b) {
912 pa_log_info("Device doesn't support mmap(), falling back to UNIX read/write mode.");
913 u->use_mmap = use_mmap = b;
914 }
915
916 if (use_tsched && (!b || !d)) {
917 pa_log_info("Cannot enabled timer-based scheduling, falling back to sound IRQ scheduling.");
918 u->use_tsched = use_tsched = FALSE;
919 }
920
921 if (u->use_mmap)
922 pa_log_info("Successfully enabled mmap() mode.");
923
924 if (u->use_tsched)
925 pa_log_info("Successfully enabled timer-based scheduling mode.");
926
927 if ((err = snd_pcm_info(u->pcm_handle, pcm_info)) < 0) {
928 pa_log("Error fetching PCM info: %s", snd_strerror(err));
929 goto fail;
930 }
931
932 if (update_sw_params(u) < 0)
933 goto fail;
934
935 /* ALSA might tweak the sample spec, so recalculate the frame size */
936 frame_size = pa_frame_size(&ss);
937
938 if ((err = snd_mixer_open(&u->mixer_handle, 0)) < 0)
939 pa_log("Error opening mixer: %s", snd_strerror(err));
940 else {
941 pa_bool_t found = FALSE;
942
943 if (pa_alsa_prepare_mixer(u->mixer_handle, u->device_name) >= 0)
944 found = TRUE;
945 else {
946 char *md = pa_sprintf_malloc("hw:%s", dev_id);
947
948 if (strcmp(u->device_name, md))
949 if (pa_alsa_prepare_mixer(u->mixer_handle, md) >= 0)
950 found = TRUE;
951
952 pa_xfree(md);
953 }
954
955 if (found)
956 if (!(u->mixer_elem = pa_alsa_find_elem(u->mixer_handle, "Capture", "Mic")))
957 found = FALSE;
958
959 if (!found) {
960 snd_mixer_close(u->mixer_handle);
961 u->mixer_handle = NULL;
962 }
963 }
964
965 if ((name = pa_modargs_get_value(ma, "source_name", NULL)))
966 namereg_fail = TRUE;
967 else {
968 name = name_buf = pa_sprintf_malloc("alsa_input.%s", u->device_name);
969 namereg_fail = FALSE;
970 }
971
972 pa_source_new_data_init(&data);
973 data.driver = __FILE__;
974 data.module = m;
975 pa_source_new_data_set_name(&data, name);
976 data.namereg_fail = namereg_fail;
977 pa_source_new_data_set_sample_spec(&data, &ss);
978 pa_source_new_data_set_channel_map(&data, &map);
979
980 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, u->device_name);
981 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "alsa");
982 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, snd_pcm_info_get_name(pcm_info));
983
984 if (class_table[snd_pcm_info_get_class(pcm_info)])
985 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, class_table[snd_pcm_info_get_class(pcm_info)]);
986
987 pa_proplist_sets(data.proplist, PA_PROP_DEVICE_ACCESS_MODE, u->use_tsched ? "mmap_rewrite" : (u->use_mmap ? "mmap" : "serial"));
988
989 u->source = pa_source_new(m->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
990 pa_source_new_data_done(&data);
991 pa_xfree(name_buf);
992
993 if (!u->source) {
994 pa_log("Failed to create source object");
995 goto fail;
996 }
997
998 u->source->parent.process_msg = source_process_msg;
999 u->source->userdata = u;
1000
1001 pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1002 pa_source_set_rtpoll(u->source, u->rtpoll);
1003
1004 u->frame_size = frame_size;
1005 u->fragment_size = frag_size = period_frames * frame_size;
1006 u->nfragments = nfrags;
1007 u->hwbuf_size = u->fragment_size * nfrags;
1008 u->tsched_watermark = tsched_watermark;
1009 u->frame_index = 0;
1010
1011 pa_log_info("Using %u fragments of size %lu bytes.", nfrags, (long unsigned) u->fragment_size);
1012
1013 if (u->mixer_handle) {
1014 pa_assert(u->mixer_elem);
1015
1016 if (snd_mixer_selem_has_capture_volume(u->mixer_elem))
1017 if (pa_alsa_calc_mixer_map(u->mixer_elem, &map, u->mixer_map, FALSE) >= 0) {
1018 u->source->get_volume = source_get_volume_cb;
1019 u->source->set_volume = source_set_volume_cb;
1020 snd_mixer_selem_get_capture_volume_range(u->mixer_elem, &u->hw_volume_min, &u->hw_volume_max);
1021 u->source->flags |= PA_SOURCE_HW_VOLUME_CTRL;
1022 }
1023
1024 if (snd_mixer_selem_has_capture_switch(u->mixer_elem)) {
1025 u->source->get_mute = source_get_mute_cb;
1026 u->source->set_mute = source_set_mute_cb;
1027 u->source->flags |= PA_SOURCE_HW_VOLUME_CTRL;
1028 }
1029
1030 u->mixer_fdl = pa_alsa_fdlist_new();
1031
1032 if (pa_alsa_fdlist_set_mixer(u->mixer_fdl, u->mixer_handle, m->core->mainloop) < 0) {
1033 pa_log("Failed to initialize file descriptor monitoring");
1034 goto fail;
1035 }
1036
1037 snd_mixer_elem_set_callback(u->mixer_elem, mixer_callback);
1038 snd_mixer_elem_set_callback_private(u->mixer_elem, u);
1039 } else
1040 u->mixer_fdl = NULL;
1041
1042 if (!(u->thread = pa_thread_new(thread_func, u))) {
1043 pa_log("Failed to create thread.");
1044 goto fail;
1045 }
1046 /* Get initial mixer settings */
1047 if (u->source->get_volume)
1048 u->source->get_volume(u->source);
1049 if (u->source->get_mute)
1050 u->source->get_mute(u->source);
1051
1052 pa_source_put(u->source);
1053
1054 pa_modargs_free(ma);
1055
1056 return 0;
1057
1058 fail:
1059
1060 if (ma)
1061 pa_modargs_free(ma);
1062
1063 pa__done(m);
1064
1065 return -1;
1066 }
1067
1068 void pa__done(pa_module*m) {
1069 struct userdata *u;
1070
1071 pa_assert(m);
1072
1073 if (!(u = m->userdata))
1074 return;
1075
1076 if (u->source)
1077 pa_source_unlink(u->source);
1078
1079 if (u->thread) {
1080 pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1081 pa_thread_free(u->thread);
1082 }
1083
1084 pa_thread_mq_done(&u->thread_mq);
1085
1086 if (u->source)
1087 pa_source_unref(u->source);
1088
1089 if (u->alsa_rtpoll_item)
1090 pa_rtpoll_item_free(u->alsa_rtpoll_item);
1091
1092 if (u->rtpoll)
1093 pa_rtpoll_free(u->rtpoll);
1094
1095 if (u->mixer_fdl)
1096 pa_alsa_fdlist_free(u->mixer_fdl);
1097
1098 if (u->mixer_handle)
1099 snd_mixer_close(u->mixer_handle);
1100
1101 if (u->pcm_handle) {
1102 snd_pcm_drop(u->pcm_handle);
1103 snd_pcm_close(u->pcm_handle);
1104 }
1105
1106 if (u->smoother)
1107 pa_smoother_free(u->smoother);
1108
1109 pa_xfree(u->device_name);
1110 pa_xfree(u);
1111
1112 snd_config_update_free_global();
1113 }