4 This file is part of PulseAudio.
6 Copyright 2004-2006 Lennart Poettering
7 Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
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.
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.
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
31 #include <asoundlib.h>
33 #include <pulse/xmalloc.h>
34 #include <pulse/util.h>
35 #include <pulse/timeval.h>
37 #include <pulsecore/core.h>
38 #include <pulsecore/module.h>
39 #include <pulsecore/memchunk.h>
40 #include <pulsecore/sink.h>
41 #include <pulsecore/modargs.h>
42 #include <pulsecore/core-util.h>
43 #include <pulsecore/sample-util.h>
44 #include <pulsecore/log.h>
45 #include <pulsecore/macro.h>
46 #include <pulsecore/thread.h>
47 #include <pulsecore/core-error.h>
48 #include <pulsecore/thread-mq.h>
49 #include <pulsecore/rtpoll.h>
50 #include <pulsecore/rtclock.h>
51 #include <pulsecore/time-smoother.h>
53 #include "alsa-util.h"
54 #include "module-alsa-sink-symdef.h"
56 PA_MODULE_AUTHOR("Lennart Poettering");
57 PA_MODULE_DESCRIPTION("ALSA Sink");
58 PA_MODULE_VERSION(PACKAGE_VERSION
);
59 PA_MODULE_LOAD_ONCE(FALSE
);
61 "sink_name=<name for the sink> "
62 "device=<ALSA device> "
63 "device_id=<ALSA card index> "
64 "format=<sample format> "
66 "channels=<number of channels> "
67 "channel_map=<channel map> "
68 "fragments=<number of fragments> "
69 "fragment_size=<fragment size> "
70 "mmap=<enable memory mapping?> "
71 "tsched=<enable system timer based scheduling mode?> "
72 "tsched_buffer_size=<buffer size when using timer based scheduling> "
73 "tsched_buffer_watermark=<lower fill watermark> "
74 "mixer_reset=<reset hw volume and mute settings to sane defaults when falling back to software?>");
76 static const char* const valid_modargs
[] = {
89 "tsched_buffer_watermark",
94 #define DEFAULT_DEVICE "default"
95 #define DEFAULT_TSCHED_BUFFER_USEC (10*PA_USEC_PER_SEC) /* 10s */
96 #define DEFAULT_TSCHED_WATERMARK_USEC (20*PA_USEC_PER_MSEC) /* 20ms */
104 pa_thread_mq thread_mq
;
107 snd_pcm_t
*pcm_handle
;
109 pa_alsa_fdlist
*mixer_fdl
;
110 snd_mixer_t
*mixer_handle
;
111 snd_mixer_elem_t
*mixer_elem
;
112 long hw_volume_max
, hw_volume_min
;
113 long hw_dB_max
, hw_dB_min
;
114 pa_bool_t hw_dB_supported
;
116 size_t frame_size
, fragment_size
, hwbuf_size
, tsched_watermark
;
118 pa_memchunk memchunk
;
122 pa_bool_t use_mmap
, use_tsched
;
126 pa_rtpoll_item
*alsa_rtpoll_item
;
128 snd_mixer_selem_channel_id_t mixer_map
[SND_MIXER_SCHN_LAST
];
130 pa_smoother
*smoother
;
133 snd_pcm_sframes_t hwbuf_unused_frames
;
134 snd_pcm_sframes_t avail_min_frames
;
137 static int mmap_write(struct userdata
*u
) {
141 pa_sink_assert_ref(u
->sink
);
148 const snd_pcm_channel_area_t
*areas
;
149 snd_pcm_uframes_t offset
, frames
;
152 snd_pcm_hwsync(u
->pcm_handle
);
154 /* First we determine how many samples are missing to fill the
155 * buffer up to 100% */
157 if (PA_UNLIKELY((n
= snd_pcm_avail_update(u
->pcm_handle
)) < 0)) {
159 pa_log_debug("snd_pcm_avail_update: %s", snd_strerror(n
));
161 if (err
== -EAGAIN
) {
162 pa_log_debug("EAGAIN");
167 pa_log_debug("snd_pcm_avail_update: Buffer underrun!");
169 if ((err
= snd_pcm_recover(u
->pcm_handle
, n
, 1)) == 0) {
174 pa_log("snd_pcm_recover: %s", snd_strerror(err
));
178 /* We only use part of the buffer that matches our
179 * dynamically requested latency */
181 if (PA_UNLIKELY(n
<= u
->hwbuf_unused_frames
))
184 if (n
*u
->frame_size
< u
->hwbuf_size
)
185 left_to_play
= u
->hwbuf_size
- (n
*u
->frame_size
);
189 pa_log_debug("%0.2f ms left to play", (double) pa_bytes_to_usec(left_to_play
, &u
->sink
->sample_spec
) / PA_USEC_PER_MSEC
);
191 if (left_to_play
<= 0 && !u
->first
) {
192 u
->tsched_watermark
*=2;
194 if (u
->tsched_watermark
>= u
->hwbuf_size
)
195 u
->tsched_watermark
= u
->hwbuf_size
-u
->frame_size
;
197 pa_log_notice("Underrun! Increasing wakeup watermark to %0.2f", (double) pa_bytes_to_usec(u
->tsched_watermark
, &u
->sink
->sample_spec
) / PA_USEC_PER_MSEC
);
200 frames
= n
= n
- u
->hwbuf_unused_frames
;
202 pa_log_debug("%llu frames to write", (unsigned long long) frames
);
204 if (PA_UNLIKELY((err
= snd_pcm_mmap_begin(u
->pcm_handle
, &areas
, &offset
, &frames
)) < 0)) {
206 pa_log_debug("snd_pcm_mmap_begin: %s", snd_strerror(err
));
208 if (err
== -EAGAIN
) {
209 pa_log_debug("EAGAIN");
214 pa_log_debug("snd_pcm_mmap_begin: Buffer underrun!");
216 if ((err
= snd_pcm_recover(u
->pcm_handle
, err
, 1)) == 0) {
221 pa_log("Failed to write data to DSP: %s", snd_strerror(err
));
225 /* Check these are multiples of 8 bit */
226 pa_assert((areas
[0].first
& 7) == 0);
227 pa_assert((areas
[0].step
& 7)== 0);
229 /* We assume a single interleaved memory buffer */
230 pa_assert((areas
[0].first
>> 3) == 0);
231 pa_assert((areas
[0].step
>> 3) == u
->frame_size
);
233 p
= (uint8_t*) areas
[0].addr
+ (offset
* u
->frame_size
);
235 chunk
.memblock
= pa_memblock_new_fixed(u
->core
->mempool
, p
, frames
* u
->frame_size
, 1);
236 chunk
.length
= pa_memblock_get_length(chunk
.memblock
);
239 pa_sink_render_into_full(u
->sink
, &chunk
);
241 /* FIXME: Maybe we can do something to keep this memory block
242 * a little bit longer around? */
243 pa_memblock_unref_fixed(chunk
.memblock
);
245 if (PA_UNLIKELY((err
= snd_pcm_mmap_commit(u
->pcm_handle
, offset
, frames
)) < 0)) {
247 pa_log_debug("snd_pcm_mmap_commit: %s", snd_strerror(err
));
249 if (err
== -EAGAIN
) {
250 pa_log_debug("EAGAIN");
255 pa_log_debug("snd_pcm_mmap_commit: Buffer underrun!");
257 if ((err
= snd_pcm_recover(u
->pcm_handle
, err
, 1)) == 0) {
262 pa_log("Failed to write data to DSP: %s", snd_strerror(err
));
268 u
->frame_index
+= frames
;
270 pa_log_debug("wrote %llu frames", (unsigned long long) frames
);
272 if (PA_LIKELY(frames
>= (snd_pcm_uframes_t
) n
))
277 static int unix_write(struct userdata
*u
) {
278 snd_pcm_status_t
*status
;
281 snd_pcm_status_alloca(&status
);
284 pa_sink_assert_ref(u
->sink
);
288 snd_pcm_sframes_t n
, frames
;
291 snd_pcm_hwsync(u
->pcm_handle
);
292 snd_pcm_avail_update(u
->pcm_handle
);
294 if (PA_UNLIKELY((err
= snd_pcm_status(u
->pcm_handle
, status
)) < 0)) {
295 pa_log("Failed to query DSP status data: %s", snd_strerror(err
));
299 if (PA_UNLIKELY(snd_pcm_status_get_avail_max(status
)*u
->frame_size
>= u
->hwbuf_size
))
300 pa_log_debug("Buffer underrun!");
302 n
= snd_pcm_status_get_avail(status
);
304 /* We only use part of the buffer that matches our
305 * dynamically requested latency */
307 if (PA_UNLIKELY(n
<= u
->hwbuf_unused_frames
))
310 n
-= u
->hwbuf_unused_frames
;
312 if (u
->memchunk
.length
<= 0)
313 pa_sink_render(u
->sink
, n
* u
->frame_size
, &u
->memchunk
);
315 pa_assert(u
->memchunk
.length
> 0);
317 frames
= u
->memchunk
.length
/ u
->frame_size
;
322 p
= pa_memblock_acquire(u
->memchunk
.memblock
);
323 frames
= snd_pcm_writei(u
->pcm_handle
, (const uint8_t*) p
+ u
->memchunk
.index
, frames
);
324 pa_memblock_release(u
->memchunk
.memblock
);
326 pa_assert(frames
!= 0);
328 if (PA_UNLIKELY(frames
< 0)) {
330 if (frames
== -EAGAIN
) {
331 pa_log_debug("EAGAIN");
335 if (frames
== -EPIPE
)
336 pa_log_debug("snd_pcm_avail_update: Buffer underrun!");
338 if ((frames
= snd_pcm_recover(u
->pcm_handle
, frames
, 1)) == 0) {
343 pa_log("Failed to write data to DSP: %s", snd_strerror(frames
));
347 u
->memchunk
.index
+= frames
* u
->frame_size
;
348 u
->memchunk
.length
-= frames
* u
->frame_size
;
350 if (u
->memchunk
.length
<= 0) {
351 pa_memblock_unref(u
->memchunk
.memblock
);
352 pa_memchunk_reset(&u
->memchunk
);
357 u
->frame_index
+= frames
;
359 if (PA_LIKELY(frames
>= n
))
364 static void update_smoother(struct userdata
*u
) {
365 snd_pcm_sframes_t delay
= 0;
368 pa_usec_t now1
, now2
;
369 /* struct timeval timestamp; */
370 snd_pcm_status_t
*status
;
372 snd_pcm_status_alloca(&status
);
375 pa_assert(u
->pcm_handle
);
377 /* Let's update the time smoother */
379 snd_pcm_hwsync(u
->pcm_handle
);
380 snd_pcm_avail_update(u
->pcm_handle
);
382 /* if (PA_UNLIKELY((err = snd_pcm_status(u->pcm_handle, status)) < 0)) { */
383 /* pa_log("Failed to query DSP status data: %s", snd_strerror(err)); */
387 /* delay = snd_pcm_status_get_delay(status); */
389 if (PA_UNLIKELY((err
= snd_pcm_delay(u
->pcm_handle
, &delay
)) < 0)) {
390 pa_log("Failed to query DSP status data: %s", snd_strerror(err
));
395 frames
= u
->frame_index
- delay
;
396 /* pa_log_debug("frame_index = %llu, delay = %llu, p = %llu", (unsigned long long) u->frame_index, (unsigned long long) delay, (unsigned long long) frames); */
398 /* snd_pcm_status_get_tstamp(status, ×tamp); */
399 /* pa_rtclock_from_wallclock(×tamp); */
400 /* now1 = pa_timeval_load(×tamp); */
402 now1
= pa_rtclock_usec();
403 now2
= pa_bytes_to_usec(frames
* u
->frame_size
, &u
->sink
->sample_spec
);
404 pa_smoother_put(u
->smoother
, now1
, now2
);
407 static pa_usec_t
sink_get_latency(struct userdata
*u
) {
413 delay
= u
->frame_index
- pa_smoother_get(u
->smoother
, pa_rtclock_usec());
416 r
= pa_bytes_to_usec(delay
* u
->frame_size
, &u
->sink
->sample_spec
);
418 if (u
->memchunk
.memblock
)
419 r
+= pa_bytes_to_usec(u
->memchunk
.length
, &u
->sink
->sample_spec
);
424 static int build_pollfd(struct userdata
*u
) {
426 struct pollfd
*pollfd
;
430 pa_assert(u
->pcm_handle
);
432 if ((n
= snd_pcm_poll_descriptors_count(u
->pcm_handle
)) < 0) {
433 pa_log("snd_pcm_poll_descriptors_count() failed: %s", snd_strerror(n
));
437 if (u
->alsa_rtpoll_item
)
438 pa_rtpoll_item_free(u
->alsa_rtpoll_item
);
440 u
->alsa_rtpoll_item
= pa_rtpoll_item_new(u
->rtpoll
, PA_RTPOLL_NEVER
, n
);
441 pollfd
= pa_rtpoll_item_get_pollfd(u
->alsa_rtpoll_item
, NULL
);
443 if ((err
= snd_pcm_poll_descriptors(u
->pcm_handle
, pollfd
, n
)) < 0) {
444 pa_log("snd_pcm_poll_descriptors() failed: %s", snd_strerror(err
));
451 static int suspend(struct userdata
*u
) {
453 pa_assert(u
->pcm_handle
);
455 pa_smoother_pause(u
->smoother
, pa_rtclock_usec());
458 snd_pcm_drain(u
->pcm_handle
);
459 snd_pcm_close(u
->pcm_handle
);
460 u
->pcm_handle
= NULL
;
462 if (u
->alsa_rtpoll_item
) {
463 pa_rtpoll_item_free(u
->alsa_rtpoll_item
);
464 u
->alsa_rtpoll_item
= NULL
;
467 pa_log_info("Device suspended...");
472 static pa_usec_t
hw_sleep_time(struct userdata
*u
) {
477 usec
= pa_sink_get_requested_latency_within_thread(u
->sink
);
479 if (usec
== (pa_usec_t
) -1)
480 usec
= pa_bytes_to_usec(u
->hwbuf_size
, &u
->sink
->sample_spec
);
482 /* pa_log_debug("hw buffer time: %u ms", (unsigned) (usec / PA_USEC_PER_MSEC)); */
484 wm
= pa_bytes_to_usec(u
->tsched_watermark
, &u
->sink
->sample_spec
);
492 pa_log_debug("Decreasing wakeup time for the first iteration by half.");
496 /* pa_log_debug("after watermark: %u ms", (unsigned) (usec / PA_USEC_PER_MSEC)); */
501 static int update_sw_params(struct userdata
*u
) {
507 /* Use the full buffer if noone asked us for anything specific */
508 u
->hwbuf_unused_frames
= 0;
511 if ((latency
= pa_sink_get_requested_latency_within_thread(u
->sink
)) != (pa_usec_t
) -1) {
514 pa_log_debug("latency set to %llu", (unsigned long long) latency
);
516 b
= pa_usec_to_bytes(latency
, &u
->sink
->sample_spec
);
518 /* We need at least one sample in our buffer */
520 if (PA_UNLIKELY(b
< u
->frame_size
))
523 u
->hwbuf_unused_frames
=
524 PA_LIKELY(b
< u
->hwbuf_size
) ?
525 ((u
->hwbuf_size
- b
) / u
->frame_size
) : 0;
528 pa_log_debug("hwbuf_unused_frames=%lu", (unsigned long) u
->hwbuf_unused_frames
);
530 /* We need at last one frame in the used part of the buffer */
531 u
->avail_min_frames
= u
->hwbuf_unused_frames
+ 1;
536 usec
= hw_sleep_time(u
);
538 u
->avail_min_frames
+= (pa_usec_to_bytes(usec
, &u
->sink
->sample_spec
) / u
->frame_size
);
541 pa_log_debug("setting avail_min=%lu", (unsigned long) u
->avail_min_frames
);
543 if ((err
= pa_alsa_set_sw_params(u
->pcm_handle
, u
->avail_min_frames
)) < 0) {
544 pa_log("Failed to set software parameters: %s", snd_strerror(err
));
551 static int unsuspend(struct userdata
*u
) {
556 snd_pcm_uframes_t period_size
;
559 pa_assert(!u
->pcm_handle
);
561 pa_log_info("Trying resume...");
563 snd_config_update_free_global();
564 if ((err
= snd_pcm_open(&u
->pcm_handle
, u
->device_name
, SND_PCM_STREAM_PLAYBACK
, SND_PCM_NONBLOCK
)) < 0) {
565 pa_log("Error opening PCM device %s: %s", u
->device_name
, snd_strerror(err
));
569 ss
= u
->sink
->sample_spec
;
570 nfrags
= u
->nfragments
;
571 period_size
= u
->fragment_size
/ u
->frame_size
;
575 if ((err
= pa_alsa_set_hw_params(u
->pcm_handle
, &ss
, &nfrags
, &period_size
, u
->hwbuf_size
/ u
->frame_size
, &b
, &d
, TRUE
)) < 0) {
576 pa_log("Failed to set hardware parameters: %s", snd_strerror(err
));
580 if (b
!= u
->use_mmap
|| d
!= u
->use_tsched
) {
581 pa_log_warn("Resume failed, couldn't get original access mode.");
585 if (!pa_sample_spec_equal(&ss
, &u
->sink
->sample_spec
)) {
586 pa_log_warn("Resume failed, couldn't restore original sample settings.");
590 if (nfrags
!= u
->nfragments
|| period_size
*u
->frame_size
!= u
->fragment_size
) {
591 pa_log_warn("Resume failed, couldn't restore original fragment settings.");
595 if (update_sw_params(u
) < 0)
598 if (build_pollfd(u
) < 0)
601 /* FIXME: We need to reload the volume somehow */
605 pa_log_info("Resumed successfully...");
611 snd_pcm_close(u
->pcm_handle
);
612 u
->pcm_handle
= NULL
;
618 static int sink_process_msg(pa_msgobject
*o
, int code
, void *data
, int64_t offset
, pa_memchunk
*chunk
) {
619 struct userdata
*u
= PA_SINK(o
)->userdata
;
623 case PA_SINK_MESSAGE_GET_LATENCY
: {
627 r
= sink_get_latency(u
);
629 *((pa_usec_t
*) data
) = r
;
634 case PA_SINK_MESSAGE_SET_STATE
:
636 switch ((pa_sink_state_t
) PA_PTR_TO_UINT(data
)) {
638 case PA_SINK_SUSPENDED
:
639 pa_assert(PA_SINK_OPENED(u
->sink
->thread_info
.state
));
647 case PA_SINK_RUNNING
:
649 if (u
->sink
->thread_info
.state
== PA_SINK_INIT
) {
650 if (build_pollfd(u
) < 0)
654 if (u
->sink
->thread_info
.state
== PA_SINK_SUSPENDED
) {
655 if (unsuspend(u
) < 0)
661 case PA_SINK_UNLINKED
:
668 /* case PA_SINK_MESSAGE_ADD_INPUT: */
669 /* case PA_SINK_MESSAGE_REMOVE_INPUT: */
670 /* case PA_SINK_MESSAGE_REMOVE_INPUT_AND_BUFFER: { */
671 /* int r = pa_sink_process_msg(o, code, data, offset, chunk); */
672 /* update_hwbuf_unused_frames(u); */
677 return pa_sink_process_msg(o
, code
, data
, offset
, chunk
);
680 static int mixer_callback(snd_mixer_elem_t
*elem
, unsigned int mask
) {
681 struct userdata
*u
= snd_mixer_elem_get_callback_private(elem
);
684 pa_assert(u
->mixer_handle
);
686 if (mask
== SND_CTL_EVENT_MASK_REMOVE
)
689 if (mask
& SND_CTL_EVENT_MASK_VALUE
) {
690 pa_sink_get_volume(u
->sink
);
691 pa_sink_get_mute(u
->sink
);
697 static int sink_get_volume_cb(pa_sink
*s
) {
698 struct userdata
*u
= s
->userdata
;
703 pa_assert(u
->mixer_elem
);
705 for (i
= 0; i
< s
->sample_spec
.channels
; i
++) {
708 pa_assert(snd_mixer_selem_has_playback_channel(u
->mixer_elem
, u
->mixer_map
[i
]));
710 if (u
->hw_dB_supported
) {
712 if ((err
= snd_mixer_selem_get_playback_dB(u
->mixer_elem
, u
->mixer_map
[i
], &alsa_vol
)) >= 0) {
713 s
->volume
.values
[i
] = pa_sw_volume_from_dB(alsa_vol
/ 100.0);
717 u
->hw_dB_supported
= FALSE
;
720 if ((err
= snd_mixer_selem_get_playback_volume(u
->mixer_elem
, u
->mixer_map
[i
], &alsa_vol
)) < 0)
723 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
));
729 pa_log_error("Unable to read volume: %s", snd_strerror(err
));
734 static int sink_set_volume_cb(pa_sink
*s
) {
735 struct userdata
*u
= s
->userdata
;
740 pa_assert(u
->mixer_elem
);
742 for (i
= 0; i
< s
->sample_spec
.channels
; i
++) {
746 pa_assert(snd_mixer_selem_has_playback_channel(u
->mixer_elem
, u
->mixer_map
[i
]));
748 vol
= PA_MIN(s
->volume
.values
[i
], PA_VOLUME_NORM
);
750 if (u
->hw_dB_supported
) {
751 alsa_vol
= (long) (pa_sw_volume_to_dB(vol
) * 100);
752 alsa_vol
= PA_CLAMP_UNLIKELY(alsa_vol
, u
->hw_dB_min
, u
->hw_dB_max
);
754 if ((err
= snd_mixer_selem_set_playback_dB(u
->mixer_elem
, u
->mixer_map
[i
], alsa_vol
, -1)) >= 0) {
756 if (snd_mixer_selem_get_playback_dB(u
->mixer_elem
, u
->mixer_map
[i
], &alsa_vol
) >= 0)
757 s
->volume
.values
[i
] = pa_sw_volume_from_dB(alsa_vol
/ 100.0);
762 u
->hw_dB_supported
= FALSE
;
766 alsa_vol
= (long) roundf(((float) vol
* (u
->hw_volume_max
- u
->hw_volume_min
)) / PA_VOLUME_NORM
) + u
->hw_volume_min
;
767 alsa_vol
= PA_CLAMP_UNLIKELY(alsa_vol
, u
->hw_volume_min
, u
->hw_volume_max
);
769 if ((err
= snd_mixer_selem_set_playback_volume(u
->mixer_elem
, u
->mixer_map
[i
], alsa_vol
)) < 0)
772 if (snd_mixer_selem_get_playback_volume(u
->mixer_elem
, u
->mixer_map
[i
], &alsa_vol
) >= 0)
773 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
));
779 pa_log_error("Unable to set volume: %s", snd_strerror(err
));
784 static int sink_get_mute_cb(pa_sink
*s
) {
785 struct userdata
*u
= s
->userdata
;
789 pa_assert(u
->mixer_elem
);
791 if ((err
= snd_mixer_selem_get_playback_switch(u
->mixer_elem
, 0, &sw
)) < 0) {
792 pa_log_error("Unable to get switch: %s", snd_strerror(err
));
801 static int sink_set_mute_cb(pa_sink
*s
) {
802 struct userdata
*u
= s
->userdata
;
806 pa_assert(u
->mixer_elem
);
808 if ((err
= snd_mixer_selem_set_playback_switch_all(u
->mixer_elem
, !s
->muted
)) < 0) {
809 pa_log_error("Unable to set switch: %s", snd_strerror(err
));
816 static void sink_update_requested_latency_cb(pa_sink
*s
) {
817 struct userdata
*u
= s
->userdata
;
824 static void thread_func(void *userdata
) {
825 struct userdata
*u
= userdata
;
829 pa_log_debug("Thread starting up");
831 if (u
->core
->realtime_scheduling
)
832 pa_make_realtime(u
->core
->realtime_priority
);
834 pa_thread_mq_install(&u
->thread_mq
);
835 pa_rtpoll_install(u
->rtpoll
);
840 /* pa_log_debug("loop"); */
842 /* Render some data and write it to the dsp */
843 if (PA_SINK_OPENED(u
->sink
->thread_info
.state
)) {
846 if (u
->sink
->thread_info
.rewind_nbytes
> 0) {
847 snd_pcm_sframes_t unused
;
848 size_t rewind_nbytes
, unused_nbytes
, limit_nbytes
;
850 rewind_nbytes
= u
->sink
->thread_info
.rewind_nbytes
;
851 u
->sink
->thread_info
.rewind_nbytes
= 0;
853 pa_log_debug("Requested to rewind %lu bytes.", (unsigned long) rewind_nbytes
);
855 snd_pcm_hwsync(u
->pcm_handle
);
856 if ((unused
= snd_pcm_avail_update(u
->pcm_handle
)) < 0) {
857 pa_log("snd_pcm_avail_update() failed: %s", snd_strerror(unused
));
861 unused_nbytes
= u
->tsched_watermark
+ (size_t) unused
* u
->frame_size
;
863 if (u
->hwbuf_size
> unused_nbytes
)
864 limit_nbytes
= u
->hwbuf_size
- unused_nbytes
;
868 if (rewind_nbytes
> limit_nbytes
)
869 rewind_nbytes
= limit_nbytes
;
871 if (rewind_nbytes
> 0) {
872 snd_pcm_sframes_t in_frames
, out_frames
;
874 pa_log_debug("Limited to %lu bytes.", (unsigned long) rewind_nbytes
);
876 in_frames
= (snd_pcm_sframes_t
) rewind_nbytes
/ u
->frame_size
;
877 pa_log_debug("before: %lu", (unsigned long) in_frames
);
878 if ((out_frames
= snd_pcm_rewind(u
->pcm_handle
, in_frames
)) < 0) {
879 pa_log("snd_pcm_rewind() failed: %s", snd_strerror(out_frames
));
882 pa_log_debug("after: %lu", (unsigned long) out_frames
);
884 if (out_frames
> in_frames
) {
885 snd_pcm_sframes_t sfix
;
886 pa_log("FUCK, device rewound %lu frames more than we wanted. What a mess!", (unsigned long) (out_frames
-in_frames
));
888 if ((sfix
= snd_pcm_forward(u
->pcm_handle
, out_frames
-in_frames
)) < 0) {
889 pa_log("snd_pcm_forward() failed: %s", snd_strerror(sfix
));
893 pa_log("Could fix by %lu", (unsigned long) sfix
);
897 rewind_nbytes
= out_frames
* u
->frame_size
;
899 if (rewind_nbytes
<= 0)
900 pa_log_info("Tried rewind, but was apparently not possible.");
902 u
->frame_index
-= out_frames
;
903 pa_log_debug("Rewound %lu bytes.", (unsigned long) rewind_nbytes
);
904 pa_sink_process_rewind(u
->sink
, rewind_nbytes
);
907 pa_log_debug("Mhmm, actually there is nothing to rewind.");
912 if ((work_done
= mmap_write(u
)) < 0)
915 if ((work_done
= unix_write(u
)) < 0)
919 /* pa_log_debug("work_done = %i", work_done); */
924 pa_log_info("Starting playback.");
925 snd_pcm_start(u
->pcm_handle
);
927 pa_smoother_resume(u
->smoother
, pa_rtclock_usec());
934 pa_usec_t usec
, cusec
;
936 /* OK, the playback buffer is now full, let's
937 * calculate when to wake up next */
939 usec
= hw_sleep_time(u
);
941 /* pa_log_debug("Waking up in %0.2fms (sound card clock).", (double) usec / PA_USEC_PER_MSEC); */
943 /* Convert from the sound card time domain to the
944 * system time domain */
945 cusec
= pa_smoother_translate(u
->smoother
, pa_rtclock_usec(), usec
);
947 /* pa_log_debug("Waking up in %0.2fms (system clock).", (double) cusec / PA_USEC_PER_MSEC); */
949 /* We don't trust the conversion, so we wake up whatever comes first */
950 pa_rtpoll_set_timer_relative(u
->rtpoll
, PA_MIN(usec
, cusec
));
955 } else if (u
->use_tsched
)
957 /* OK, we're in an invalid state, let's disable our timers */
958 pa_rtpoll_set_timer_disabled(u
->rtpoll
);
960 /* Hmm, nothing to do. Let's sleep */
961 if ((ret
= pa_rtpoll_run(u
->rtpoll
, 1)) < 0)
967 /* Tell ALSA about this and process its response */
968 if (PA_SINK_OPENED(u
->sink
->thread_info
.state
)) {
969 struct pollfd
*pollfd
;
970 unsigned short revents
= 0;
974 pollfd
= pa_rtpoll_item_get_pollfd(u
->alsa_rtpoll_item
, &n
);
976 if ((err
= snd_pcm_poll_descriptors_revents(u
->pcm_handle
, pollfd
, n
, &revents
)) < 0) {
977 pa_log("snd_pcm_poll_descriptors_revents() failed: %s", snd_strerror(err
));
981 if (revents
& (POLLERR
|POLLNVAL
|POLLHUP
)) {
982 snd_pcm_state_t state
;
984 if (revents
& POLLERR
)
985 pa_log_warn("Got POLLERR from ALSA");
986 if (revents
& POLLNVAL
)
987 pa_log_warn("Got POLLNVAL from ALSA");
988 if (revents
& POLLHUP
)
989 pa_log_warn("Got POLLHUP from ALSA");
991 state
= snd_pcm_state(u
->pcm_handle
);
992 pa_log_warn("PCM state is %s", snd_pcm_state_name(state
));
994 /* Try to recover from this error */
998 case SND_PCM_STATE_XRUN
:
999 if ((err
= snd_pcm_recover(u
->pcm_handle
, -EPIPE
, 1)) != 0) {
1000 pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP and XRUN: %s", snd_strerror(err
));
1005 case SND_PCM_STATE_SUSPENDED
:
1006 if ((err
= snd_pcm_recover(u
->pcm_handle
, -ESTRPIPE
, 1)) != 0) {
1007 pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP and SUSPENDED: %s", snd_strerror(err
));
1014 snd_pcm_drop(u
->pcm_handle
);
1016 if ((err
= snd_pcm_prepare(u
->pcm_handle
)) < 0) {
1017 pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP with snd_pcm_prepare(): %s", snd_strerror(err
));
1027 pa_log_debug("Wakeup from ALSA! (%i)", revents
);
1032 /* If this was no regular exit from the loop we have to continue
1033 * processing messages until we received PA_MESSAGE_SHUTDOWN */
1034 pa_asyncmsgq_post(u
->thread_mq
.outq
, PA_MSGOBJECT(u
->core
), PA_CORE_MESSAGE_UNLOAD_MODULE
, u
->module
, 0, NULL
, NULL
);
1035 pa_asyncmsgq_wait_for(u
->thread_mq
.inq
, PA_MESSAGE_SHUTDOWN
);
1038 pa_log_debug("Thread shutting down");
1041 int pa__init(pa_module
*m
) {
1043 pa_modargs
*ma
= NULL
;
1044 struct userdata
*u
= NULL
;
1048 uint32_t nfrags
, hwbuf_size
, frag_size
, tsched_size
, tsched_watermark
;
1049 snd_pcm_uframes_t period_frames
, tsched_frames
;
1051 snd_pcm_info_t
*pcm_info
= NULL
;
1054 char *name_buf
= NULL
;
1055 pa_bool_t namereg_fail
;
1056 pa_bool_t use_mmap
= TRUE
, b
, use_tsched
= TRUE
, d
, mixer_reset
= TRUE
;
1058 pa_sink_new_data data
;
1060 snd_pcm_info_alloca(&pcm_info
);
1064 pa_alsa_redirect_errors_inc();
1066 if (!(ma
= pa_modargs_new(m
->argument
, valid_modargs
))) {
1067 pa_log("Failed to parse module arguments");
1071 ss
= m
->core
->default_sample_spec
;
1072 if (pa_modargs_get_sample_spec_and_channel_map(ma
, &ss
, &map
, PA_CHANNEL_MAP_ALSA
) < 0) {
1073 pa_log("Failed to parse sample specification and channel map");
1077 frame_size
= pa_frame_size(&ss
);
1079 nfrags
= m
->core
->default_n_fragments
;
1080 frag_size
= pa_usec_to_bytes(m
->core
->default_fragment_size_msec
*PA_USEC_PER_MSEC
, &ss
);
1082 frag_size
= frame_size
;
1083 tsched_size
= pa_usec_to_bytes(DEFAULT_TSCHED_BUFFER_USEC
, &ss
);
1084 tsched_watermark
= pa_usec_to_bytes(DEFAULT_TSCHED_WATERMARK_USEC
, &ss
);
1086 if (pa_modargs_get_value_u32(ma
, "fragments", &nfrags
) < 0 ||
1087 pa_modargs_get_value_u32(ma
, "fragment_size", &frag_size
) < 0 ||
1088 pa_modargs_get_value_u32(ma
, "tsched_buffer_size", &tsched_size
) < 0 ||
1089 pa_modargs_get_value_u32(ma
, "tsched_buffer_watermark", &tsched_watermark
) < 0) {
1090 pa_log("Failed to parse buffer metrics");
1094 hwbuf_size
= frag_size
* nfrags
;
1095 period_frames
= frag_size
/frame_size
;
1096 tsched_frames
= tsched_size
/frame_size
;
1098 if (pa_modargs_get_value_boolean(ma
, "mmap", &use_mmap
) < 0) {
1099 pa_log("Failed to parse mmap argument.");
1103 if (pa_modargs_get_value_boolean(ma
, "tsched", &use_tsched
) < 0) {
1104 pa_log("Failed to parse timer_scheduling argument.");
1108 if (use_tsched
&& !pa_rtclock_hrtimer()) {
1109 pa_log("Disabling timer-based scheduling because high-resolution timers are not available from the kernel.");
1113 if (pa_modargs_get_value_boolean(ma
, "mixer_reset", &mixer_reset
) < 0) {
1114 pa_log("Failed to parse mixer_reset argument.");
1118 u
= pa_xnew0(struct userdata
, 1);
1122 u
->use_mmap
= use_mmap
;
1123 u
->use_tsched
= use_tsched
;
1125 pa_thread_mq_init(&u
->thread_mq
, m
->core
->mainloop
);
1126 u
->rtpoll
= pa_rtpoll_new();
1127 u
->alsa_rtpoll_item
= NULL
;
1128 pa_rtpoll_item_new_asyncmsgq(u
->rtpoll
, PA_RTPOLL_EARLY
, u
->thread_mq
.inq
);
1130 u
->smoother
= pa_smoother_new(DEFAULT_TSCHED_BUFFER_USEC
*2, DEFAULT_TSCHED_BUFFER_USEC
*2, TRUE
);
1131 usec
= pa_rtclock_usec();
1132 pa_smoother_set_time_offset(u
->smoother
, usec
);
1133 pa_smoother_pause(u
->smoother
, usec
);
1135 snd_config_update_free_global();
1140 if ((dev_id
= pa_modargs_get_value(ma
, "device_id", NULL
))) {
1142 if (!(u
->pcm_handle
= pa_alsa_open_by_device_id(
1146 SND_PCM_STREAM_PLAYBACK
,
1147 &nfrags
, &period_frames
, tsched_frames
,
1154 if (!(u
->pcm_handle
= pa_alsa_open_by_device_string(
1155 pa_modargs_get_value(ma
, "device", DEFAULT_DEVICE
),
1158 SND_PCM_STREAM_PLAYBACK
,
1159 &nfrags
, &period_frames
, tsched_frames
,
1165 pa_assert(u
->device_name
);
1166 pa_log_info("Successfully opened device %s.", u
->device_name
);
1168 if (use_mmap
&& !b
) {
1169 pa_log_info("Device doesn't support mmap(), falling back to UNIX read/write mode.");
1170 u
->use_mmap
= use_mmap
= FALSE
;
1173 if (use_tsched
&& (!b
|| !d
)) {
1174 pa_log_info("Cannot enabled timer-based scheduling, falling back to sound IRQ scheduling.");
1175 u
->use_tsched
= use_tsched
= FALSE
;
1179 pa_log_info("Successfully enabled mmap() mode.");
1182 pa_log_info("Successfully enabled timer-based scheduling mode.");
1184 if ((err
= snd_pcm_info(u
->pcm_handle
, pcm_info
)) < 0) {
1185 pa_log("Error fetching PCM info: %s", snd_strerror(err
));
1189 /* ALSA might tweak the sample spec, so recalculate the frame size */
1190 frame_size
= pa_frame_size(&ss
);
1192 if ((err
= snd_mixer_open(&u
->mixer_handle
, 0)) < 0)
1193 pa_log_warn("Error opening mixer: %s", snd_strerror(err
));
1195 pa_bool_t found
= FALSE
;
1197 if (pa_alsa_prepare_mixer(u
->mixer_handle
, u
->device_name
) >= 0)
1200 snd_pcm_info_t
*info
;
1202 snd_pcm_info_alloca(&info
);
1204 if (snd_pcm_info(u
->pcm_handle
, info
) >= 0) {
1208 if ((card
= snd_pcm_info_get_card(info
)) >= 0) {
1210 md
= pa_sprintf_malloc("hw:%i", card
);
1212 if (strcmp(u
->device_name
, md
))
1213 if (pa_alsa_prepare_mixer(u
->mixer_handle
, md
) >= 0)
1221 if (!(u
->mixer_elem
= pa_alsa_find_elem(u
->mixer_handle
, "Master", "PCM")))
1225 snd_mixer_close(u
->mixer_handle
);
1226 u
->mixer_handle
= NULL
;
1230 if ((name
= pa_modargs_get_value(ma
, "sink_name", NULL
)))
1231 namereg_fail
= TRUE
;
1233 name
= name_buf
= pa_sprintf_malloc("alsa_output.%s", u
->device_name
);
1234 namereg_fail
= FALSE
;
1237 pa_sink_new_data_init(&data
);
1238 data
.driver
= __FILE__
;
1240 pa_sink_new_data_set_name(&data
, name
);
1241 data
.namereg_fail
= namereg_fail
;
1242 pa_sink_new_data_set_sample_spec(&data
, &ss
);
1243 pa_sink_new_data_set_channel_map(&data
, &map
);
1245 pa_alsa_init_proplist(data
.proplist
, pcm_info
);
1246 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_STRING
, u
->device_name
);
1247 pa_proplist_setf(data
.proplist
, PA_PROP_DEVICE_BUFFERING_BUFFER_SIZE
, "%lu", (unsigned long) (period_frames
* frame_size
* nfrags
));
1248 pa_proplist_setf(data
.proplist
, PA_PROP_DEVICE_BUFFERING_FRAGMENT_SIZE
, "%lu", (unsigned long) (period_frames
* frame_size
));
1249 pa_proplist_sets(data
.proplist
, PA_PROP_DEVICE_ACCESS_MODE
, u
->use_tsched
? "mmap+timer" : (u
->use_mmap
? "mmap" : "serial"));
1251 u
->sink
= pa_sink_new(m
->core
, &data
, PA_SINK_HARDWARE
|PA_SINK_LATENCY
);
1252 pa_sink_new_data_done(&data
);
1256 pa_log("Failed to create sink object");
1260 u
->sink
->parent
.process_msg
= sink_process_msg
;
1261 u
->sink
->update_requested_latency
= sink_update_requested_latency_cb
;
1262 u
->sink
->userdata
= u
;
1264 pa_sink_set_asyncmsgq(u
->sink
, u
->thread_mq
.inq
);
1265 pa_sink_set_rtpoll(u
->sink
, u
->rtpoll
);
1267 u
->frame_size
= frame_size
;
1268 u
->fragment_size
= frag_size
= period_frames
* frame_size
;
1269 u
->nfragments
= nfrags
;
1270 u
->hwbuf_size
= u
->fragment_size
* nfrags
;
1271 u
->hwbuf_unused_frames
= 0;
1272 u
->avail_min_frames
= 0;
1273 u
->tsched_watermark
= tsched_watermark
;
1275 u
->hw_dB_supported
= FALSE
;
1276 u
->hw_dB_min
= u
->hw_dB_max
= 0;
1277 u
->hw_volume_min
= u
->hw_volume_max
= 0;
1280 if (u
->tsched_watermark
>= u
->hwbuf_size
/2)
1281 u
->tsched_watermark
= pa_frame_align(u
->hwbuf_size
/2, &ss
);
1283 u
->sink
->thread_info
.max_rewind
= use_tsched
? u
->hwbuf_size
: 0;
1284 u
->sink
->max_latency
= pa_bytes_to_usec(u
->hwbuf_size
, &ss
);
1287 u
->sink
->min_latency
= u
->sink
->max_latency
;
1289 pa_log_info("Using %u fragments of size %lu bytes, buffer time is %0.2fms",
1290 nfrags
, (long unsigned) u
->fragment_size
,
1291 (double) pa_bytes_to_usec(u
->hwbuf_size
, &ss
) / PA_USEC_PER_MSEC
);
1294 pa_log_info("Time scheduling watermark is %0.2fms",
1295 (double) pa_bytes_to_usec(u
->tsched_watermark
, &ss
) / PA_USEC_PER_MSEC
);
1297 if (update_sw_params(u
) < 0)
1300 pa_memchunk_reset(&u
->memchunk
);
1302 if (u
->mixer_handle
) {
1303 pa_assert(u
->mixer_elem
);
1305 if (snd_mixer_selem_has_playback_volume(u
->mixer_elem
))
1307 if (pa_alsa_calc_mixer_map(u
->mixer_elem
, &map
, u
->mixer_map
, TRUE
) >= 0 &&
1308 snd_mixer_selem_get_playback_volume_range(u
->mixer_elem
, &u
->hw_volume_min
, &u
->hw_volume_max
) >= 0) {
1310 pa_bool_t suitable
= TRUE
;
1312 pa_log_info("Volume ranges from %li to %li.", u
->hw_volume_min
, u
->hw_volume_max
);
1314 if (u
->hw_volume_min
> u
->hw_volume_max
) {
1316 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
);
1319 } else if (u
->hw_volume_max
- u
->hw_volume_min
< 3) {
1321 pa_log_info("Device has less than 4 volume levels. Falling back to software volume control.");
1324 } else if (snd_mixer_selem_get_playback_dB_range(u
->mixer_elem
, &u
->hw_dB_min
, &u
->hw_dB_max
) >= 0) {
1326 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);
1328 /* Let's see if this thing actually is useful for muting */
1329 if (u
->hw_dB_min
> -6000) {
1330 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);
1333 } else if (u
->hw_dB_max
< 0) {
1335 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);
1338 } else if (u
->hw_dB_min
>= u
->hw_dB_max
) {
1340 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);
1345 if (u
->hw_dB_max
> 0) {
1346 /* dB > 0 means overamplification, and clipping, we don't want that here */
1347 pa_log_info("Device can do overamplification for %0.2f dB. Limiting to 0 db", ((double) u
->hw_dB_max
) / 100);
1351 u
->hw_dB_supported
= TRUE
;
1356 u
->sink
->get_volume
= sink_get_volume_cb
;
1357 u
->sink
->set_volume
= sink_set_volume_cb
;
1358 u
->sink
->flags
|= PA_SINK_HW_VOLUME_CTRL
| (u
->hw_dB_supported
? PA_SINK_DECIBEL_VOLUME
: 0);
1359 pa_log_info("Using hardware volume control. %s dB scale.", u
->hw_dB_supported
? "Using" : "Not using");
1361 } else if (mixer_reset
) {
1362 pa_log_info("Using software volume control. Trying to reset sound card to 0 dB.");
1363 pa_alsa_0dB_playback(u
->mixer_elem
);
1365 pa_log_info("Using software volume control. Leaving hw mixer controls untouched.");
1368 if (snd_mixer_selem_has_playback_switch(u
->mixer_elem
)) {
1369 u
->sink
->get_mute
= sink_get_mute_cb
;
1370 u
->sink
->set_mute
= sink_set_mute_cb
;
1371 u
->sink
->flags
|= PA_SINK_HW_MUTE_CTRL
;
1374 u
->mixer_fdl
= pa_alsa_fdlist_new();
1376 if (pa_alsa_fdlist_set_mixer(u
->mixer_fdl
, u
->mixer_handle
, m
->core
->mainloop
) < 0) {
1377 pa_log("Failed to initialize file descriptor monitoring");
1381 snd_mixer_elem_set_callback(u
->mixer_elem
, mixer_callback
);
1382 snd_mixer_elem_set_callback_private(u
->mixer_elem
, u
);
1384 u
->mixer_fdl
= NULL
;
1386 pa_alsa_dump(u
->pcm_handle
);
1388 if (!(u
->thread
= pa_thread_new(thread_func
, u
))) {
1389 pa_log("Failed to create thread.");
1393 /* Get initial mixer settings */
1394 if (data
.volume_is_set
) {
1395 if (u
->sink
->set_volume
)
1396 u
->sink
->set_volume(u
->sink
);
1398 if (u
->sink
->get_volume
)
1399 u
->sink
->get_volume(u
->sink
);
1402 if (data
.muted_is_set
) {
1403 if (u
->sink
->set_mute
)
1404 u
->sink
->set_mute(u
->sink
);
1406 if (u
->sink
->get_mute
)
1407 u
->sink
->get_mute(u
->sink
);
1410 pa_sink_put(u
->sink
);
1412 pa_modargs_free(ma
);
1419 pa_modargs_free(ma
);
1426 void pa__done(pa_module
*m
) {
1431 if (!(u
= m
->userdata
)) {
1432 pa_alsa_redirect_errors_dec();
1437 pa_sink_unlink(u
->sink
);
1440 pa_asyncmsgq_send(u
->thread_mq
.inq
, NULL
, PA_MESSAGE_SHUTDOWN
, NULL
, 0, NULL
);
1441 pa_thread_free(u
->thread
);
1444 pa_thread_mq_done(&u
->thread_mq
);
1447 pa_sink_unref(u
->sink
);
1449 if (u
->memchunk
.memblock
)
1450 pa_memblock_unref(u
->memchunk
.memblock
);
1452 if (u
->alsa_rtpoll_item
)
1453 pa_rtpoll_item_free(u
->alsa_rtpoll_item
);
1456 pa_rtpoll_free(u
->rtpoll
);
1459 pa_alsa_fdlist_free(u
->mixer_fdl
);
1461 if (u
->mixer_handle
)
1462 snd_mixer_close(u
->mixer_handle
);
1464 if (u
->pcm_handle
) {
1465 snd_pcm_drop(u
->pcm_handle
);
1466 snd_pcm_close(u
->pcm_handle
);
1470 pa_smoother_free(u
->smoother
);
1472 pa_xfree(u
->device_name
);
1475 snd_config_update_free_global();
1477 pa_alsa_redirect_errors_dec();