2 * QEMU ALSA audio driver
4 * Copyright (c) 2005 Vassili Karpov (malc)
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
26 #include <alsa/asoundlib.h>
27 #include "qemu/main-loop.h"
28 #include "qemu/module.h"
32 #pragma GCC diagnostic ignored "-Waddress"
34 #define AUDIO_CAP "alsa"
35 #include "audio_int.h"
47 typedef struct ALSAVoiceOut {
50 struct pollhlp pollhlp;
54 typedef struct ALSAVoiceIn {
57 struct pollhlp pollhlp;
61 struct alsa_params_req {
67 struct alsa_params_obt {
72 snd_pcm_uframes_t samples;
75 static void G_GNUC_PRINTF (2, 3) alsa_logerr (int err, const char *fmt, ...)
80 AUD_vlog (AUDIO_CAP, fmt, ap);
83 AUD_log (AUDIO_CAP, "Reason: %s\n", snd_strerror (err));
86 static void G_GNUC_PRINTF (3, 4) alsa_logerr2 (
95 AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
98 AUD_vlog (AUDIO_CAP, fmt, ap);
101 AUD_log (AUDIO_CAP, "Reason: %s\n", snd_strerror (err));
104 static void alsa_fini_poll (struct pollhlp *hlp)
107 struct pollfd *pfds = hlp->pfds;
110 for (i = 0; i < hlp->count; ++i) {
111 qemu_set_fd_handler (pfds[i].fd, NULL, NULL, NULL);
120 static void alsa_anal_close1 (snd_pcm_t **handlep)
122 int err = snd_pcm_close (*handlep);
124 alsa_logerr (err, "Failed to close PCM handle %p\n", *handlep);
129 static void alsa_anal_close (snd_pcm_t **handlep, struct pollhlp *hlp)
131 alsa_fini_poll (hlp);
132 alsa_anal_close1 (handlep);
135 static int alsa_recover (snd_pcm_t *handle)
137 int err = snd_pcm_prepare (handle);
139 alsa_logerr (err, "Failed to prepare handle %p\n", handle);
145 static int alsa_resume (snd_pcm_t *handle)
147 int err = snd_pcm_resume (handle);
149 alsa_logerr (err, "Failed to resume handle %p\n", handle);
155 static void alsa_poll_handler (void *opaque)
158 snd_pcm_state_t state;
159 struct pollhlp *hlp = opaque;
160 unsigned short revents;
162 count = poll (hlp->pfds, hlp->count, 0);
164 dolog ("alsa_poll_handler: poll %s\n", strerror (errno));
172 /* XXX: ALSA example uses initial count, not the one returned by
174 err = snd_pcm_poll_descriptors_revents (hlp->handle, hlp->pfds,
175 hlp->count, &revents);
177 alsa_logerr (err, "snd_pcm_poll_descriptors_revents");
181 if (!(revents & hlp->mask)) {
182 trace_alsa_revents(revents);
186 state = snd_pcm_state (hlp->handle);
188 case SND_PCM_STATE_SETUP:
189 alsa_recover (hlp->handle);
192 case SND_PCM_STATE_XRUN:
193 alsa_recover (hlp->handle);
196 case SND_PCM_STATE_SUSPENDED:
197 alsa_resume (hlp->handle);
200 case SND_PCM_STATE_PREPARED:
201 audio_run(hlp->s, "alsa run (prepared)");
204 case SND_PCM_STATE_RUNNING:
205 audio_run(hlp->s, "alsa run (running)");
209 dolog ("Unexpected state %d\n", state);
213 static int alsa_poll_helper (snd_pcm_t *handle, struct pollhlp *hlp, int mask)
218 count = snd_pcm_poll_descriptors_count (handle);
220 dolog ("Could not initialize poll mode\n"
221 "Invalid number of poll descriptors %d\n", count);
225 pfds = g_new0(struct pollfd, count);
227 err = snd_pcm_poll_descriptors (handle, pfds, count);
229 alsa_logerr (err, "Could not initialize poll mode\n"
230 "Could not obtain poll descriptors\n");
235 for (i = 0; i < count; ++i) {
236 if (pfds[i].events & POLLIN) {
237 qemu_set_fd_handler (pfds[i].fd, alsa_poll_handler, NULL, hlp);
239 if (pfds[i].events & POLLOUT) {
240 trace_alsa_pollout(i, pfds[i].fd);
241 qemu_set_fd_handler (pfds[i].fd, NULL, alsa_poll_handler, hlp);
243 trace_alsa_set_handler(pfds[i].events, i, pfds[i].fd, err);
248 hlp->handle = handle;
253 static int alsa_poll_out (HWVoiceOut *hw)
255 ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
257 return alsa_poll_helper (alsa->handle, &alsa->pollhlp, POLLOUT);
260 static int alsa_poll_in (HWVoiceIn *hw)
262 ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
264 return alsa_poll_helper (alsa->handle, &alsa->pollhlp, POLLIN);
267 static snd_pcm_format_t aud_to_alsafmt (AudioFormat fmt, int endianness)
270 case AUDIO_FORMAT_S8:
271 return SND_PCM_FORMAT_S8;
273 case AUDIO_FORMAT_U8:
274 return SND_PCM_FORMAT_U8;
276 case AUDIO_FORMAT_S16:
278 return SND_PCM_FORMAT_S16_BE;
280 return SND_PCM_FORMAT_S16_LE;
283 case AUDIO_FORMAT_U16:
285 return SND_PCM_FORMAT_U16_BE;
287 return SND_PCM_FORMAT_U16_LE;
290 case AUDIO_FORMAT_S32:
292 return SND_PCM_FORMAT_S32_BE;
294 return SND_PCM_FORMAT_S32_LE;
297 case AUDIO_FORMAT_U32:
299 return SND_PCM_FORMAT_U32_BE;
301 return SND_PCM_FORMAT_U32_LE;
304 case AUDIO_FORMAT_F32:
306 return SND_PCM_FORMAT_FLOAT_BE;
308 return SND_PCM_FORMAT_FLOAT_LE;
312 dolog ("Internal logic error: Bad audio format %d\n", fmt);
316 return SND_PCM_FORMAT_U8;
320 static int alsa_to_audfmt (snd_pcm_format_t alsafmt, AudioFormat *fmt,
324 case SND_PCM_FORMAT_S8:
326 *fmt = AUDIO_FORMAT_S8;
329 case SND_PCM_FORMAT_U8:
331 *fmt = AUDIO_FORMAT_U8;
334 case SND_PCM_FORMAT_S16_LE:
336 *fmt = AUDIO_FORMAT_S16;
339 case SND_PCM_FORMAT_U16_LE:
341 *fmt = AUDIO_FORMAT_U16;
344 case SND_PCM_FORMAT_S16_BE:
346 *fmt = AUDIO_FORMAT_S16;
349 case SND_PCM_FORMAT_U16_BE:
351 *fmt = AUDIO_FORMAT_U16;
354 case SND_PCM_FORMAT_S32_LE:
356 *fmt = AUDIO_FORMAT_S32;
359 case SND_PCM_FORMAT_U32_LE:
361 *fmt = AUDIO_FORMAT_U32;
364 case SND_PCM_FORMAT_S32_BE:
366 *fmt = AUDIO_FORMAT_S32;
369 case SND_PCM_FORMAT_U32_BE:
371 *fmt = AUDIO_FORMAT_U32;
374 case SND_PCM_FORMAT_FLOAT_LE:
376 *fmt = AUDIO_FORMAT_F32;
379 case SND_PCM_FORMAT_FLOAT_BE:
381 *fmt = AUDIO_FORMAT_F32;
385 dolog ("Unrecognized audio format %d\n", alsafmt);
392 static void alsa_dump_info (struct alsa_params_req *req,
393 struct alsa_params_obt *obt,
394 snd_pcm_format_t obtfmt,
395 AudiodevAlsaPerDirectionOptions *apdo)
397 dolog("parameter | requested value | obtained value\n");
398 dolog("format | %10d | %10d\n", req->fmt, obtfmt);
399 dolog("channels | %10d | %10d\n",
400 req->nchannels, obt->nchannels);
401 dolog("frequency | %10d | %10d\n", req->freq, obt->freq);
402 dolog("============================================\n");
403 dolog("requested: buffer len %" PRId32 " period len %" PRId32 "\n",
404 apdo->buffer_length, apdo->period_length);
405 dolog("obtained: samples %ld\n", obt->samples);
408 static void alsa_set_threshold (snd_pcm_t *handle, snd_pcm_uframes_t threshold)
411 snd_pcm_sw_params_t *sw_params;
413 snd_pcm_sw_params_alloca (&sw_params);
415 err = snd_pcm_sw_params_current (handle, sw_params);
417 dolog ("Could not fully initialize DAC\n");
418 alsa_logerr (err, "Failed to get current software parameters\n");
422 err = snd_pcm_sw_params_set_start_threshold (handle, sw_params, threshold);
424 dolog ("Could not fully initialize DAC\n");
425 alsa_logerr (err, "Failed to set software threshold to %ld\n",
430 err = snd_pcm_sw_params (handle, sw_params);
432 dolog ("Could not fully initialize DAC\n");
433 alsa_logerr (err, "Failed to set software parameters\n");
438 static int alsa_open(bool in, struct alsa_params_req *req,
439 struct alsa_params_obt *obt, snd_pcm_t **handlep,
442 AudiodevAlsaOptions *aopts = &dev->u.alsa;
443 AudiodevAlsaPerDirectionOptions *apdo = in ? aopts->in : aopts->out;
445 snd_pcm_hw_params_t *hw_params;
447 unsigned int freq, nchannels;
448 const char *pcm_name = apdo->dev ?: "default";
449 snd_pcm_uframes_t obt_buffer_size;
450 const char *typ = in ? "ADC" : "DAC";
451 snd_pcm_format_t obtfmt;
454 nchannels = req->nchannels;
456 snd_pcm_hw_params_alloca (&hw_params);
461 in ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
465 alsa_logerr2 (err, typ, "Failed to open `%s':\n", pcm_name);
469 err = snd_pcm_hw_params_any (handle, hw_params);
471 alsa_logerr2 (err, typ, "Failed to initialize hardware parameters\n");
475 err = snd_pcm_hw_params_set_access (
478 SND_PCM_ACCESS_RW_INTERLEAVED
481 alsa_logerr2 (err, typ, "Failed to set access type\n");
485 err = snd_pcm_hw_params_set_format (handle, hw_params, req->fmt);
487 alsa_logerr2 (err, typ, "Failed to set format %d\n", req->fmt);
490 err = snd_pcm_hw_params_set_rate_near (handle, hw_params, &freq, 0);
492 alsa_logerr2 (err, typ, "Failed to set frequency %d\n", req->freq);
496 err = snd_pcm_hw_params_set_channels_near (
502 alsa_logerr2 (err, typ, "Failed to set number of channels %d\n",
507 if (apdo->buffer_length) {
509 unsigned int btime = apdo->buffer_length;
511 err = snd_pcm_hw_params_set_buffer_time_near(
512 handle, hw_params, &btime, &dir);
515 alsa_logerr2(err, typ, "Failed to set buffer time to %" PRId32 "\n",
516 apdo->buffer_length);
520 if (apdo->has_buffer_length && btime != apdo->buffer_length) {
521 dolog("Requested buffer time %" PRId32
522 " was rejected, using %u\n", apdo->buffer_length, btime);
526 if (apdo->period_length) {
528 unsigned int ptime = apdo->period_length;
530 err = snd_pcm_hw_params_set_period_time_near(handle, hw_params, &ptime,
534 alsa_logerr2(err, typ, "Failed to set period time to %" PRId32 "\n",
535 apdo->period_length);
539 if (apdo->has_period_length && ptime != apdo->period_length) {
540 dolog("Requested period time %" PRId32 " was rejected, using %d\n",
541 apdo->period_length, ptime);
545 err = snd_pcm_hw_params (handle, hw_params);
547 alsa_logerr2 (err, typ, "Failed to apply audio parameters\n");
551 err = snd_pcm_hw_params_get_buffer_size (hw_params, &obt_buffer_size);
553 alsa_logerr2 (err, typ, "Failed to get buffer size\n");
557 err = snd_pcm_hw_params_get_format (hw_params, &obtfmt);
559 alsa_logerr2 (err, typ, "Failed to get format\n");
563 if (alsa_to_audfmt (obtfmt, &obt->fmt, &obt->endianness)) {
564 dolog ("Invalid format was returned %d\n", obtfmt);
568 err = snd_pcm_prepare (handle);
570 alsa_logerr2 (err, typ, "Could not prepare handle %p\n", handle);
574 if (!in && aopts->has_threshold && aopts->threshold) {
575 struct audsettings as = { .freq = freq };
578 audio_buffer_frames(qapi_AudiodevAlsaPerDirectionOptions_base(apdo),
579 &as, aopts->threshold));
582 obt->nchannels = nchannels;
584 obt->samples = obt_buffer_size;
588 if (DEBUG_ALSA || obtfmt != req->fmt ||
589 obt->nchannels != req->nchannels || obt->freq != req->freq) {
590 dolog ("Audio parameters for %s\n", typ);
591 alsa_dump_info(req, obt, obtfmt, apdo);
597 alsa_anal_close1 (&handle);
601 static size_t alsa_buffer_get_free(HWVoiceOut *hw)
603 ALSAVoiceOut *alsa = (ALSAVoiceOut *)hw;
604 snd_pcm_sframes_t avail;
605 size_t alsa_free, generic_free, generic_in_use;
607 avail = snd_pcm_avail_update(alsa->handle);
609 if (avail == -EPIPE) {
610 if (!alsa_recover(alsa->handle)) {
611 avail = snd_pcm_avail_update(alsa->handle);
616 "Could not obtain number of available frames\n");
621 alsa_free = avail * hw->info.bytes_per_frame;
622 generic_free = audio_generic_buffer_get_free(hw);
623 generic_in_use = hw->samples * hw->info.bytes_per_frame - generic_free;
624 if (generic_in_use) {
626 * This code can only be reached in the unlikely case that
627 * snd_pcm_avail_update() returned a larger number of frames
628 * than snd_pcm_writei() could write. Make sure that all
629 * remaining bytes in the generic buffer can be written.
631 alsa_free = alsa_free > generic_in_use ? alsa_free - generic_in_use : 0;
637 static size_t alsa_write(HWVoiceOut *hw, void *buf, size_t len)
639 ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
641 size_t len_frames = len / hw->info.bytes_per_frame;
644 char *src = advance(buf, pos);
645 snd_pcm_sframes_t written;
647 written = snd_pcm_writei(alsa->handle, src, len_frames);
652 trace_alsa_wrote_zero(len_frames);
656 if (alsa_recover(alsa->handle)) {
657 alsa_logerr(written, "Failed to write %zu frames\n",
661 trace_alsa_xrun_out();
666 * stream is suspended and waiting for an application
669 if (alsa_resume(alsa->handle)) {
670 alsa_logerr(written, "Failed to write %zu frames\n",
674 trace_alsa_resume_out();
681 alsa_logerr(written, "Failed to write %zu frames from %p\n",
687 pos += written * hw->info.bytes_per_frame;
688 if (written < len_frames) {
691 len_frames -= written;
697 static void alsa_fini_out (HWVoiceOut *hw)
699 ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
701 ldebug ("alsa_fini\n");
702 alsa_anal_close (&alsa->handle, &alsa->pollhlp);
705 static int alsa_init_out(HWVoiceOut *hw, struct audsettings *as,
708 ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
709 struct alsa_params_req req;
710 struct alsa_params_obt obt;
712 struct audsettings obt_as;
713 Audiodev *dev = drv_opaque;
715 req.fmt = aud_to_alsafmt (as->fmt, as->endianness);
717 req.nchannels = as->nchannels;
719 if (alsa_open(0, &req, &obt, &handle, dev)) {
723 obt_as.freq = obt.freq;
724 obt_as.nchannels = obt.nchannels;
725 obt_as.fmt = obt.fmt;
726 obt_as.endianness = obt.endianness;
728 audio_pcm_init_info (&hw->info, &obt_as);
729 hw->samples = obt.samples;
731 alsa->pollhlp.s = hw->s;
732 alsa->handle = handle;
737 #define VOICE_CTL_PAUSE 0
738 #define VOICE_CTL_PREPARE 1
739 #define VOICE_CTL_START 2
741 static int alsa_voice_ctl (snd_pcm_t *handle, const char *typ, int ctl)
745 if (ctl == VOICE_CTL_PAUSE) {
746 err = snd_pcm_drop (handle);
748 alsa_logerr (err, "Could not stop %s\n", typ);
752 err = snd_pcm_prepare (handle);
754 alsa_logerr (err, "Could not prepare handle for %s\n", typ);
757 if (ctl == VOICE_CTL_START) {
758 err = snd_pcm_start(handle);
760 alsa_logerr (err, "Could not start handle for %s\n", typ);
769 static void alsa_enable_out(HWVoiceOut *hw, bool enable)
771 ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
772 AudiodevAlsaPerDirectionOptions *apdo = alsa->dev->u.alsa.out;
775 bool poll_mode = apdo->try_poll;
777 ldebug("enabling voice\n");
778 if (poll_mode && alsa_poll_out(hw)) {
781 hw->poll_mode = poll_mode;
782 alsa_voice_ctl(alsa->handle, "playback", VOICE_CTL_PREPARE);
784 ldebug("disabling voice\n");
787 alsa_fini_poll(&alsa->pollhlp);
789 alsa_voice_ctl(alsa->handle, "playback", VOICE_CTL_PAUSE);
793 static int alsa_init_in(HWVoiceIn *hw, struct audsettings *as, void *drv_opaque)
795 ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
796 struct alsa_params_req req;
797 struct alsa_params_obt obt;
799 struct audsettings obt_as;
800 Audiodev *dev = drv_opaque;
802 req.fmt = aud_to_alsafmt (as->fmt, as->endianness);
804 req.nchannels = as->nchannels;
806 if (alsa_open(1, &req, &obt, &handle, dev)) {
810 obt_as.freq = obt.freq;
811 obt_as.nchannels = obt.nchannels;
812 obt_as.fmt = obt.fmt;
813 obt_as.endianness = obt.endianness;
815 audio_pcm_init_info (&hw->info, &obt_as);
816 hw->samples = obt.samples;
818 alsa->pollhlp.s = hw->s;
819 alsa->handle = handle;
824 static void alsa_fini_in (HWVoiceIn *hw)
826 ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
828 alsa_anal_close (&alsa->handle, &alsa->pollhlp);
831 static size_t alsa_read(HWVoiceIn *hw, void *buf, size_t len)
833 ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
837 void *dst = advance(buf, pos);
838 snd_pcm_sframes_t nread;
840 nread = snd_pcm_readi(
841 alsa->handle, dst, len / hw->info.bytes_per_frame);
846 trace_alsa_read_zero(len);
850 if (alsa_recover(alsa->handle)) {
851 alsa_logerr(nread, "Failed to read %zu frames\n", len);
854 trace_alsa_xrun_in();
861 alsa_logerr(nread, "Failed to read %zu frames to %p\n",
867 pos += nread * hw->info.bytes_per_frame;
868 len -= nread * hw->info.bytes_per_frame;
874 static void alsa_enable_in(HWVoiceIn *hw, bool enable)
876 ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
877 AudiodevAlsaPerDirectionOptions *apdo = alsa->dev->u.alsa.in;
880 bool poll_mode = apdo->try_poll;
882 ldebug("enabling voice\n");
883 if (poll_mode && alsa_poll_in(hw)) {
886 hw->poll_mode = poll_mode;
888 alsa_voice_ctl(alsa->handle, "capture", VOICE_CTL_START);
890 ldebug ("disabling voice\n");
893 alsa_fini_poll(&alsa->pollhlp);
895 alsa_voice_ctl(alsa->handle, "capture", VOICE_CTL_PAUSE);
899 static void alsa_init_per_direction(AudiodevAlsaPerDirectionOptions *apdo)
901 if (!apdo->has_try_poll) {
902 apdo->try_poll = true;
903 apdo->has_try_poll = true;
907 static void *alsa_audio_init(Audiodev *dev, Error **errp)
909 AudiodevAlsaOptions *aopts;
910 assert(dev->driver == AUDIODEV_DRIVER_ALSA);
912 aopts = &dev->u.alsa;
913 alsa_init_per_direction(aopts->in);
914 alsa_init_per_direction(aopts->out);
916 /* don't set has_* so alsa_open can identify it wasn't set by the user */
917 if (!dev->u.alsa.out->has_period_length) {
918 /* 256 frames assuming 44100Hz */
919 dev->u.alsa.out->period_length = 5805;
921 if (!dev->u.alsa.out->has_buffer_length) {
922 /* 4096 frames assuming 44100Hz */
923 dev->u.alsa.out->buffer_length = 92880;
926 if (!dev->u.alsa.in->has_period_length) {
927 /* 256 frames assuming 44100Hz */
928 dev->u.alsa.in->period_length = 5805;
930 if (!dev->u.alsa.in->has_buffer_length) {
931 /* 4096 frames assuming 44100Hz */
932 dev->u.alsa.in->buffer_length = 92880;
938 static void alsa_audio_fini (void *opaque)
942 static struct audio_pcm_ops alsa_pcm_ops = {
943 .init_out = alsa_init_out,
944 .fini_out = alsa_fini_out,
946 .buffer_get_free = alsa_buffer_get_free,
947 .run_buffer_out = audio_generic_run_buffer_out,
948 .enable_out = alsa_enable_out,
950 .init_in = alsa_init_in,
951 .fini_in = alsa_fini_in,
953 .run_buffer_in = audio_generic_run_buffer_in,
954 .enable_in = alsa_enable_in,
957 static struct audio_driver alsa_audio_driver = {
959 .descr = "ALSA http://www.alsa-project.org",
960 .init = alsa_audio_init,
961 .fini = alsa_audio_fini,
962 .pcm_ops = &alsa_pcm_ops,
963 .max_voices_out = INT_MAX,
964 .max_voices_in = INT_MAX,
965 .voice_size_out = sizeof (ALSAVoiceOut),
966 .voice_size_in = sizeof (ALSAVoiceIn)
969 static void register_audio_alsa(void)
971 audio_driver_register(&alsa_audio_driver);
973 type_init(register_audio_alsa);