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