audio: allow returning an error from the driver init
[qemu/kevin.git] / audio / audio.c
blobfdc34a77520f7173c3bbbcb62945b5edf229ca68
1 /*
2 * QEMU Audio subsystem
4 * Copyright (c) 2003-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
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
26 #include "audio.h"
27 #include "migration/vmstate.h"
28 #include "monitor/monitor.h"
29 #include "qemu/timer.h"
30 #include "qapi/error.h"
31 #include "qapi/clone-visitor.h"
32 #include "qapi/qobject-input-visitor.h"
33 #include "qapi/qapi-visit-audio.h"
34 #include "qapi/qapi-commands-audio.h"
35 #include "qemu/cutils.h"
36 #include "qemu/error-report.h"
37 #include "qemu/log.h"
38 #include "qemu/module.h"
39 #include "qemu/help_option.h"
40 #include "sysemu/sysemu.h"
41 #include "sysemu/replay.h"
42 #include "sysemu/runstate.h"
43 #include "ui/qemu-spice.h"
44 #include "trace.h"
46 #define AUDIO_CAP "audio"
47 #include "audio_int.h"
49 /* #define DEBUG_LIVE */
50 /* #define DEBUG_OUT */
51 /* #define DEBUG_CAPTURE */
52 /* #define DEBUG_POLL */
54 #define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
57 /* Order of CONFIG_AUDIO_DRIVERS is import.
58 The 1st one is the one used by default, that is the reason
59 that we generate the list.
61 const char *audio_prio_list[] = {
62 "spice",
63 CONFIG_AUDIO_DRIVERS
64 "none",
65 "wav",
66 NULL
69 static QLIST_HEAD(, audio_driver) audio_drivers;
70 static AudiodevListHead audiodevs = QSIMPLEQ_HEAD_INITIALIZER(audiodevs);
72 void audio_driver_register(audio_driver *drv)
74 QLIST_INSERT_HEAD(&audio_drivers, drv, next);
77 audio_driver *audio_driver_lookup(const char *name)
79 struct audio_driver *d;
80 Error *local_err = NULL;
81 int rv;
83 QLIST_FOREACH(d, &audio_drivers, next) {
84 if (strcmp(name, d->name) == 0) {
85 return d;
88 rv = audio_module_load(name, &local_err);
89 if (rv > 0) {
90 QLIST_FOREACH(d, &audio_drivers, next) {
91 if (strcmp(name, d->name) == 0) {
92 return d;
95 } else if (rv < 0) {
96 error_report_err(local_err);
98 return NULL;
101 static QTAILQ_HEAD(AudioStateHead, AudioState) audio_states =
102 QTAILQ_HEAD_INITIALIZER(audio_states);
104 const struct mixeng_volume nominal_volume = {
105 .mute = 0,
106 #ifdef FLOAT_MIXENG
107 .r = 1.0,
108 .l = 1.0,
109 #else
110 .r = 1ULL << 32,
111 .l = 1ULL << 32,
112 #endif
115 static bool legacy_config = true;
117 int audio_bug (const char *funcname, int cond)
119 if (cond) {
120 static int shown;
122 AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
123 if (!shown) {
124 shown = 1;
125 AUD_log (NULL, "Save all your work and restart without audio\n");
126 AUD_log (NULL, "I am sorry\n");
128 AUD_log (NULL, "Context:\n");
131 return cond;
134 static inline int audio_bits_to_index (int bits)
136 switch (bits) {
137 case 8:
138 return 0;
140 case 16:
141 return 1;
143 case 32:
144 return 2;
146 default:
147 audio_bug ("bits_to_index", 1);
148 AUD_log (NULL, "invalid bits %d\n", bits);
149 return 0;
153 void AUD_vlog (const char *cap, const char *fmt, va_list ap)
155 if (cap) {
156 fprintf(stderr, "%s: ", cap);
159 vfprintf(stderr, fmt, ap);
162 void AUD_log (const char *cap, const char *fmt, ...)
164 va_list ap;
166 va_start (ap, fmt);
167 AUD_vlog (cap, fmt, ap);
168 va_end (ap);
171 static void audio_print_settings (struct audsettings *as)
173 dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
175 switch (as->fmt) {
176 case AUDIO_FORMAT_S8:
177 AUD_log (NULL, "S8");
178 break;
179 case AUDIO_FORMAT_U8:
180 AUD_log (NULL, "U8");
181 break;
182 case AUDIO_FORMAT_S16:
183 AUD_log (NULL, "S16");
184 break;
185 case AUDIO_FORMAT_U16:
186 AUD_log (NULL, "U16");
187 break;
188 case AUDIO_FORMAT_S32:
189 AUD_log (NULL, "S32");
190 break;
191 case AUDIO_FORMAT_U32:
192 AUD_log (NULL, "U32");
193 break;
194 case AUDIO_FORMAT_F32:
195 AUD_log (NULL, "F32");
196 break;
197 default:
198 AUD_log (NULL, "invalid(%d)", as->fmt);
199 break;
202 AUD_log (NULL, " endianness=");
203 switch (as->endianness) {
204 case 0:
205 AUD_log (NULL, "little");
206 break;
207 case 1:
208 AUD_log (NULL, "big");
209 break;
210 default:
211 AUD_log (NULL, "invalid");
212 break;
214 AUD_log (NULL, "\n");
217 static int audio_validate_settings (struct audsettings *as)
219 int invalid;
221 invalid = as->nchannels < 1;
222 invalid |= as->endianness != 0 && as->endianness != 1;
224 switch (as->fmt) {
225 case AUDIO_FORMAT_S8:
226 case AUDIO_FORMAT_U8:
227 case AUDIO_FORMAT_S16:
228 case AUDIO_FORMAT_U16:
229 case AUDIO_FORMAT_S32:
230 case AUDIO_FORMAT_U32:
231 case AUDIO_FORMAT_F32:
232 break;
233 default:
234 invalid = 1;
235 break;
238 invalid |= as->freq <= 0;
239 return invalid ? -1 : 0;
242 static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
244 int bits = 8;
245 bool is_signed = false, is_float = false;
247 switch (as->fmt) {
248 case AUDIO_FORMAT_S8:
249 is_signed = true;
250 /* fall through */
251 case AUDIO_FORMAT_U8:
252 break;
254 case AUDIO_FORMAT_S16:
255 is_signed = true;
256 /* fall through */
257 case AUDIO_FORMAT_U16:
258 bits = 16;
259 break;
261 case AUDIO_FORMAT_F32:
262 is_float = true;
263 /* fall through */
264 case AUDIO_FORMAT_S32:
265 is_signed = true;
266 /* fall through */
267 case AUDIO_FORMAT_U32:
268 bits = 32;
269 break;
271 default:
272 abort();
274 return info->freq == as->freq
275 && info->nchannels == as->nchannels
276 && info->is_signed == is_signed
277 && info->is_float == is_float
278 && info->bits == bits
279 && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
282 void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
284 int bits = 8, mul;
285 bool is_signed = false, is_float = false;
287 switch (as->fmt) {
288 case AUDIO_FORMAT_S8:
289 is_signed = true;
290 /* fall through */
291 case AUDIO_FORMAT_U8:
292 mul = 1;
293 break;
295 case AUDIO_FORMAT_S16:
296 is_signed = true;
297 /* fall through */
298 case AUDIO_FORMAT_U16:
299 bits = 16;
300 mul = 2;
301 break;
303 case AUDIO_FORMAT_F32:
304 is_float = true;
305 /* fall through */
306 case AUDIO_FORMAT_S32:
307 is_signed = true;
308 /* fall through */
309 case AUDIO_FORMAT_U32:
310 bits = 32;
311 mul = 4;
312 break;
314 default:
315 abort();
318 info->freq = as->freq;
319 info->bits = bits;
320 info->is_signed = is_signed;
321 info->is_float = is_float;
322 info->nchannels = as->nchannels;
323 info->bytes_per_frame = as->nchannels * mul;
324 info->bytes_per_second = info->freq * info->bytes_per_frame;
325 info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
328 void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
330 if (!len) {
331 return;
334 if (info->is_signed || info->is_float) {
335 memset(buf, 0x00, len * info->bytes_per_frame);
336 } else {
337 switch (info->bits) {
338 case 8:
339 memset(buf, 0x80, len * info->bytes_per_frame);
340 break;
342 case 16:
344 int i;
345 uint16_t *p = buf;
346 short s = INT16_MAX;
348 if (info->swap_endianness) {
349 s = bswap16 (s);
352 for (i = 0; i < len * info->nchannels; i++) {
353 p[i] = s;
356 break;
358 case 32:
360 int i;
361 uint32_t *p = buf;
362 int32_t s = INT32_MAX;
364 if (info->swap_endianness) {
365 s = bswap32 (s);
368 for (i = 0; i < len * info->nchannels; i++) {
369 p[i] = s;
372 break;
374 default:
375 AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
376 info->bits);
377 break;
383 * Capture
385 static CaptureVoiceOut *audio_pcm_capture_find_specific(AudioState *s,
386 struct audsettings *as)
388 CaptureVoiceOut *cap;
390 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
391 if (audio_pcm_info_eq (&cap->hw.info, as)) {
392 return cap;
395 return NULL;
398 static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
400 struct capture_callback *cb;
402 #ifdef DEBUG_CAPTURE
403 dolog ("notification %d sent\n", cmd);
404 #endif
405 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
406 cb->ops.notify (cb->opaque, cmd);
410 static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
412 if (cap->hw.enabled != enabled) {
413 audcnotification_e cmd;
414 cap->hw.enabled = enabled;
415 cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
416 audio_notify_capture (cap, cmd);
420 static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
422 HWVoiceOut *hw = &cap->hw;
423 SWVoiceOut *sw;
424 int enabled = 0;
426 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
427 if (sw->active) {
428 enabled = 1;
429 break;
432 audio_capture_maybe_changed (cap, enabled);
435 static void audio_detach_capture (HWVoiceOut *hw)
437 SWVoiceCap *sc = hw->cap_head.lh_first;
439 while (sc) {
440 SWVoiceCap *sc1 = sc->entries.le_next;
441 SWVoiceOut *sw = &sc->sw;
442 CaptureVoiceOut *cap = sc->cap;
443 int was_active = sw->active;
445 if (sw->rate) {
446 st_rate_stop (sw->rate);
447 sw->rate = NULL;
450 QLIST_REMOVE (sw, entries);
451 QLIST_REMOVE (sc, entries);
452 g_free (sc);
453 if (was_active) {
454 /* We have removed soft voice from the capture:
455 this might have changed the overall status of the capture
456 since this might have been the only active voice */
457 audio_recalc_and_notify_capture (cap);
459 sc = sc1;
463 static int audio_attach_capture (HWVoiceOut *hw)
465 AudioState *s = hw->s;
466 CaptureVoiceOut *cap;
468 audio_detach_capture (hw);
469 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
470 SWVoiceCap *sc;
471 SWVoiceOut *sw;
472 HWVoiceOut *hw_cap = &cap->hw;
474 sc = g_malloc0(sizeof(*sc));
476 sc->cap = cap;
477 sw = &sc->sw;
478 sw->hw = hw_cap;
479 sw->info = hw->info;
480 sw->empty = 1;
481 sw->active = hw->enabled;
482 sw->vol = nominal_volume;
483 sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
484 QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
485 QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
486 #ifdef DEBUG_CAPTURE
487 sw->name = g_strdup_printf ("for %p %d,%d,%d",
488 hw, sw->info.freq, sw->info.bits,
489 sw->info.nchannels);
490 dolog ("Added %s active = %d\n", sw->name, sw->active);
491 #endif
492 if (sw->active) {
493 audio_capture_maybe_changed (cap, 1);
496 return 0;
500 * Hard voice (capture)
502 static size_t audio_pcm_hw_find_min_in (HWVoiceIn *hw)
504 SWVoiceIn *sw;
505 size_t m = hw->total_samples_captured;
507 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
508 if (sw->active) {
509 m = MIN (m, sw->total_hw_samples_acquired);
512 return m;
515 static size_t audio_pcm_hw_get_live_in(HWVoiceIn *hw)
517 size_t live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
518 if (audio_bug(__func__, live > hw->conv_buf.size)) {
519 dolog("live=%zu hw->conv_buf.size=%zu\n", live, hw->conv_buf.size);
520 return 0;
522 return live;
525 static size_t audio_pcm_hw_conv_in(HWVoiceIn *hw, void *pcm_buf, size_t samples)
527 size_t conv = 0;
528 STSampleBuffer *conv_buf = &hw->conv_buf;
530 while (samples) {
531 uint8_t *src = advance(pcm_buf, conv * hw->info.bytes_per_frame);
532 size_t proc = MIN(samples, conv_buf->size - conv_buf->pos);
534 hw->conv(conv_buf->buffer + conv_buf->pos, src, proc);
535 conv_buf->pos = (conv_buf->pos + proc) % conv_buf->size;
536 samples -= proc;
537 conv += proc;
540 return conv;
544 * Soft voice (capture)
546 static void audio_pcm_sw_resample_in(SWVoiceIn *sw,
547 size_t frames_in_max, size_t frames_out_max,
548 size_t *total_in, size_t *total_out)
550 HWVoiceIn *hw = sw->hw;
551 struct st_sample *src, *dst;
552 size_t live, rpos, frames_in, frames_out;
554 live = hw->total_samples_captured - sw->total_hw_samples_acquired;
555 rpos = audio_ring_posb(hw->conv_buf.pos, live, hw->conv_buf.size);
557 /* resample conv_buf from rpos to end of buffer */
558 src = hw->conv_buf.buffer + rpos;
559 frames_in = MIN(frames_in_max, hw->conv_buf.size - rpos);
560 dst = sw->resample_buf.buffer;
561 frames_out = frames_out_max;
562 st_rate_flow(sw->rate, src, dst, &frames_in, &frames_out);
563 rpos += frames_in;
564 *total_in = frames_in;
565 *total_out = frames_out;
567 /* resample conv_buf from start of buffer if there are input frames left */
568 if (frames_in_max - frames_in && rpos == hw->conv_buf.size) {
569 src = hw->conv_buf.buffer;
570 frames_in = frames_in_max - frames_in;
571 dst += frames_out;
572 frames_out = frames_out_max - frames_out;
573 st_rate_flow(sw->rate, src, dst, &frames_in, &frames_out);
574 *total_in += frames_in;
575 *total_out += frames_out;
579 static size_t audio_pcm_sw_read(SWVoiceIn *sw, void *buf, size_t buf_len)
581 HWVoiceIn *hw = sw->hw;
582 size_t live, frames_out_max, total_in, total_out;
584 live = hw->total_samples_captured - sw->total_hw_samples_acquired;
585 if (!live) {
586 return 0;
588 if (audio_bug(__func__, live > hw->conv_buf.size)) {
589 dolog("live_in=%zu hw->conv_buf.size=%zu\n", live, hw->conv_buf.size);
590 return 0;
593 frames_out_max = MIN(buf_len / sw->info.bytes_per_frame,
594 sw->resample_buf.size);
596 audio_pcm_sw_resample_in(sw, live, frames_out_max, &total_in, &total_out);
598 if (!hw->pcm_ops->volume_in) {
599 mixeng_volume(sw->resample_buf.buffer, total_out, &sw->vol);
601 sw->clip(buf, sw->resample_buf.buffer, total_out);
603 sw->total_hw_samples_acquired += total_in;
604 return total_out * sw->info.bytes_per_frame;
608 * Hard voice (playback)
610 static size_t audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
612 SWVoiceOut *sw;
613 size_t m = SIZE_MAX;
614 int nb_live = 0;
616 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
617 if (sw->active || !sw->empty) {
618 m = MIN (m, sw->total_hw_samples_mixed);
619 nb_live += 1;
623 *nb_livep = nb_live;
624 return m;
627 static size_t audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
629 size_t smin;
630 int nb_live1;
632 smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
633 if (nb_live) {
634 *nb_live = nb_live1;
637 if (nb_live1) {
638 size_t live = smin;
640 if (audio_bug(__func__, live > hw->mix_buf.size)) {
641 dolog("live=%zu hw->mix_buf.size=%zu\n", live, hw->mix_buf.size);
642 return 0;
644 return live;
646 return 0;
649 static size_t audio_pcm_hw_get_free(HWVoiceOut *hw)
651 return (hw->pcm_ops->buffer_get_free ? hw->pcm_ops->buffer_get_free(hw) :
652 INT_MAX) / hw->info.bytes_per_frame;
655 static void audio_pcm_hw_clip_out(HWVoiceOut *hw, void *pcm_buf, size_t len)
657 size_t clipped = 0;
658 size_t pos = hw->mix_buf.pos;
660 while (len) {
661 st_sample *src = hw->mix_buf.buffer + pos;
662 uint8_t *dst = advance(pcm_buf, clipped * hw->info.bytes_per_frame);
663 size_t samples_till_end_of_buf = hw->mix_buf.size - pos;
664 size_t samples_to_clip = MIN(len, samples_till_end_of_buf);
666 hw->clip(dst, src, samples_to_clip);
668 pos = (pos + samples_to_clip) % hw->mix_buf.size;
669 len -= samples_to_clip;
670 clipped += samples_to_clip;
675 * Soft voice (playback)
677 static void audio_pcm_sw_resample_out(SWVoiceOut *sw,
678 size_t frames_in_max, size_t frames_out_max,
679 size_t *total_in, size_t *total_out)
681 HWVoiceOut *hw = sw->hw;
682 struct st_sample *src, *dst;
683 size_t live, wpos, frames_in, frames_out;
685 live = sw->total_hw_samples_mixed;
686 wpos = (hw->mix_buf.pos + live) % hw->mix_buf.size;
688 /* write to mix_buf from wpos to end of buffer */
689 src = sw->resample_buf.buffer;
690 frames_in = frames_in_max;
691 dst = hw->mix_buf.buffer + wpos;
692 frames_out = MIN(frames_out_max, hw->mix_buf.size - wpos);
693 st_rate_flow_mix(sw->rate, src, dst, &frames_in, &frames_out);
694 wpos += frames_out;
695 *total_in = frames_in;
696 *total_out = frames_out;
698 /* write to mix_buf from start of buffer if there are input frames left */
699 if (frames_in_max - frames_in > 0 && wpos == hw->mix_buf.size) {
700 src += frames_in;
701 frames_in = frames_in_max - frames_in;
702 dst = hw->mix_buf.buffer;
703 frames_out = frames_out_max - frames_out;
704 st_rate_flow_mix(sw->rate, src, dst, &frames_in, &frames_out);
705 *total_in += frames_in;
706 *total_out += frames_out;
710 static size_t audio_pcm_sw_write(SWVoiceOut *sw, void *buf, size_t buf_len)
712 HWVoiceOut *hw = sw->hw;
713 size_t live, dead, hw_free, sw_max, fe_max;
714 size_t frames_in_max, frames_out_max, total_in, total_out;
716 live = sw->total_hw_samples_mixed;
717 if (audio_bug(__func__, live > hw->mix_buf.size)) {
718 dolog("live=%zu hw->mix_buf.size=%zu\n", live, hw->mix_buf.size);
719 return 0;
722 if (live == hw->mix_buf.size) {
723 #ifdef DEBUG_OUT
724 dolog ("%s is full %zu\n", sw->name, live);
725 #endif
726 return 0;
729 dead = hw->mix_buf.size - live;
730 hw_free = audio_pcm_hw_get_free(hw);
731 hw_free = hw_free > live ? hw_free - live : 0;
732 frames_out_max = MIN(dead, hw_free);
733 sw_max = st_rate_frames_in(sw->rate, frames_out_max);
734 fe_max = MIN(buf_len / sw->info.bytes_per_frame + sw->resample_buf.pos,
735 sw->resample_buf.size);
736 frames_in_max = MIN(sw_max, fe_max);
738 if (!frames_in_max) {
739 return 0;
742 if (frames_in_max > sw->resample_buf.pos) {
743 sw->conv(sw->resample_buf.buffer + sw->resample_buf.pos,
744 buf, frames_in_max - sw->resample_buf.pos);
745 if (!sw->hw->pcm_ops->volume_out) {
746 mixeng_volume(sw->resample_buf.buffer + sw->resample_buf.pos,
747 frames_in_max - sw->resample_buf.pos, &sw->vol);
751 audio_pcm_sw_resample_out(sw, frames_in_max, frames_out_max,
752 &total_in, &total_out);
754 sw->total_hw_samples_mixed += total_out;
755 sw->empty = sw->total_hw_samples_mixed == 0;
758 * Upsampling may leave one audio frame in the resample buffer. Decrement
759 * total_in by one if there was a leftover frame from the previous resample
760 * pass in the resample buffer. Increment total_in by one if the current
761 * resample pass left one frame in the resample buffer.
763 if (frames_in_max - total_in == 1) {
764 /* copy one leftover audio frame to the beginning of the buffer */
765 *sw->resample_buf.buffer = *(sw->resample_buf.buffer + total_in);
766 total_in += 1 - sw->resample_buf.pos;
767 sw->resample_buf.pos = 1;
768 } else if (total_in >= sw->resample_buf.pos) {
769 total_in -= sw->resample_buf.pos;
770 sw->resample_buf.pos = 0;
773 #ifdef DEBUG_OUT
774 dolog (
775 "%s: write size %zu written %zu total mixed %zu\n",
776 SW_NAME(sw),
777 buf_len / sw->info.bytes_per_frame,
778 total_in,
779 sw->total_hw_samples_mixed
781 #endif
783 return total_in * sw->info.bytes_per_frame;
786 #ifdef DEBUG_AUDIO
787 static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
789 dolog("%s: bits %d, sign %d, float %d, freq %d, nchan %d\n",
790 cap, info->bits, info->is_signed, info->is_float, info->freq,
791 info->nchannels);
793 #endif
795 #define DAC
796 #include "audio_template.h"
797 #undef DAC
798 #include "audio_template.h"
801 * Timer
803 static int audio_is_timer_needed(AudioState *s)
805 HWVoiceIn *hwi = NULL;
806 HWVoiceOut *hwo = NULL;
808 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
809 if (!hwo->poll_mode) {
810 return 1;
813 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
814 if (!hwi->poll_mode) {
815 return 1;
818 return 0;
821 static void audio_reset_timer (AudioState *s)
823 if (audio_is_timer_needed(s)) {
824 timer_mod_anticipate_ns(s->ts,
825 qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
826 if (!s->timer_running) {
827 s->timer_running = true;
828 s->timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
829 trace_audio_timer_start(s->period_ticks / SCALE_MS);
831 } else {
832 timer_del(s->ts);
833 if (s->timer_running) {
834 s->timer_running = false;
835 trace_audio_timer_stop();
840 static void audio_timer (void *opaque)
842 int64_t now, diff;
843 AudioState *s = opaque;
845 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
846 diff = now - s->timer_last;
847 if (diff > s->period_ticks * 3 / 2) {
848 trace_audio_timer_delayed(diff / SCALE_MS);
850 s->timer_last = now;
852 audio_run(s, "timer");
853 audio_reset_timer(s);
857 * Public API
859 size_t AUD_write(SWVoiceOut *sw, void *buf, size_t size)
861 HWVoiceOut *hw;
863 if (!sw) {
864 /* XXX: Consider options */
865 return size;
867 hw = sw->hw;
869 if (!hw->enabled) {
870 dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
871 return 0;
874 if (audio_get_pdo_out(hw->s->dev)->mixing_engine) {
875 return audio_pcm_sw_write(sw, buf, size);
876 } else {
877 return hw->pcm_ops->write(hw, buf, size);
881 size_t AUD_read(SWVoiceIn *sw, void *buf, size_t size)
883 HWVoiceIn *hw;
885 if (!sw) {
886 /* XXX: Consider options */
887 return size;
889 hw = sw->hw;
891 if (!hw->enabled) {
892 dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
893 return 0;
896 if (audio_get_pdo_in(hw->s->dev)->mixing_engine) {
897 return audio_pcm_sw_read(sw, buf, size);
898 } else {
899 return hw->pcm_ops->read(hw, buf, size);
903 int AUD_get_buffer_size_out(SWVoiceOut *sw)
905 return sw->hw->samples * sw->hw->info.bytes_per_frame;
908 void AUD_set_active_out (SWVoiceOut *sw, int on)
910 HWVoiceOut *hw;
912 if (!sw) {
913 return;
916 hw = sw->hw;
917 if (sw->active != on) {
918 AudioState *s = sw->s;
919 SWVoiceOut *temp_sw;
920 SWVoiceCap *sc;
922 if (on) {
923 hw->pending_disable = 0;
924 if (!hw->enabled) {
925 hw->enabled = 1;
926 if (s->vm_running) {
927 if (hw->pcm_ops->enable_out) {
928 hw->pcm_ops->enable_out(hw, true);
930 audio_reset_timer (s);
933 } else {
934 if (hw->enabled) {
935 int nb_active = 0;
937 for (temp_sw = hw->sw_head.lh_first; temp_sw;
938 temp_sw = temp_sw->entries.le_next) {
939 nb_active += temp_sw->active != 0;
942 hw->pending_disable = nb_active == 1;
946 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
947 sc->sw.active = hw->enabled;
948 if (hw->enabled) {
949 audio_capture_maybe_changed (sc->cap, 1);
952 sw->active = on;
956 void AUD_set_active_in (SWVoiceIn *sw, int on)
958 HWVoiceIn *hw;
960 if (!sw) {
961 return;
964 hw = sw->hw;
965 if (sw->active != on) {
966 AudioState *s = sw->s;
967 SWVoiceIn *temp_sw;
969 if (on) {
970 if (!hw->enabled) {
971 hw->enabled = 1;
972 if (s->vm_running) {
973 if (hw->pcm_ops->enable_in) {
974 hw->pcm_ops->enable_in(hw, true);
976 audio_reset_timer (s);
979 sw->total_hw_samples_acquired = hw->total_samples_captured;
980 } else {
981 if (hw->enabled) {
982 int nb_active = 0;
984 for (temp_sw = hw->sw_head.lh_first; temp_sw;
985 temp_sw = temp_sw->entries.le_next) {
986 nb_active += temp_sw->active != 0;
989 if (nb_active == 1) {
990 hw->enabled = 0;
991 if (hw->pcm_ops->enable_in) {
992 hw->pcm_ops->enable_in(hw, false);
997 sw->active = on;
1001 static size_t audio_get_avail (SWVoiceIn *sw)
1003 size_t live;
1005 if (!sw) {
1006 return 0;
1009 live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
1010 if (audio_bug(__func__, live > sw->hw->conv_buf.size)) {
1011 dolog("live=%zu sw->hw->conv_buf.size=%zu\n", live,
1012 sw->hw->conv_buf.size);
1013 return 0;
1016 ldebug (
1017 "%s: get_avail live %zu frontend frames %u\n",
1018 SW_NAME (sw),
1019 live, st_rate_frames_out(sw->rate, live)
1022 return live;
1025 static size_t audio_get_free(SWVoiceOut *sw)
1027 size_t live, dead;
1029 if (!sw) {
1030 return 0;
1033 live = sw->total_hw_samples_mixed;
1035 if (audio_bug(__func__, live > sw->hw->mix_buf.size)) {
1036 dolog("live=%zu sw->hw->mix_buf.size=%zu\n", live,
1037 sw->hw->mix_buf.size);
1038 return 0;
1041 dead = sw->hw->mix_buf.size - live;
1043 #ifdef DEBUG_OUT
1044 dolog("%s: get_free live %zu dead %zu frontend frames %u\n",
1045 SW_NAME(sw), live, dead, st_rate_frames_in(sw->rate, dead));
1046 #endif
1048 return dead;
1051 static void audio_capture_mix_and_clear(HWVoiceOut *hw, size_t rpos,
1052 size_t samples)
1054 size_t n;
1056 if (hw->enabled) {
1057 SWVoiceCap *sc;
1059 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1060 SWVoiceOut *sw = &sc->sw;
1061 size_t rpos2 = rpos;
1063 n = samples;
1064 while (n) {
1065 size_t till_end_of_hw = hw->mix_buf.size - rpos2;
1066 size_t to_read = MIN(till_end_of_hw, n);
1067 size_t live, frames_in, frames_out;
1069 sw->resample_buf.buffer = hw->mix_buf.buffer + rpos2;
1070 sw->resample_buf.size = to_read;
1071 live = sw->total_hw_samples_mixed;
1073 audio_pcm_sw_resample_out(sw,
1074 to_read, sw->hw->mix_buf.size - live,
1075 &frames_in, &frames_out);
1077 sw->total_hw_samples_mixed += frames_out;
1078 sw->empty = sw->total_hw_samples_mixed == 0;
1080 if (to_read - frames_in) {
1081 dolog("Could not mix %zu frames into a capture "
1082 "buffer, mixed %zu\n",
1083 to_read, frames_in);
1084 break;
1086 n -= to_read;
1087 rpos2 = (rpos2 + to_read) % hw->mix_buf.size;
1092 n = MIN(samples, hw->mix_buf.size - rpos);
1093 mixeng_clear(hw->mix_buf.buffer + rpos, n);
1094 mixeng_clear(hw->mix_buf.buffer, samples - n);
1097 static size_t audio_pcm_hw_run_out(HWVoiceOut *hw, size_t live)
1099 size_t clipped = 0;
1101 while (live) {
1102 size_t size = live * hw->info.bytes_per_frame;
1103 size_t decr, proc;
1104 void *buf = hw->pcm_ops->get_buffer_out(hw, &size);
1106 if (size == 0) {
1107 break;
1110 decr = MIN(size / hw->info.bytes_per_frame, live);
1111 if (buf) {
1112 audio_pcm_hw_clip_out(hw, buf, decr);
1114 proc = hw->pcm_ops->put_buffer_out(hw, buf,
1115 decr * hw->info.bytes_per_frame) /
1116 hw->info.bytes_per_frame;
1118 live -= proc;
1119 clipped += proc;
1120 hw->mix_buf.pos = (hw->mix_buf.pos + proc) % hw->mix_buf.size;
1122 if (proc == 0 || proc < decr) {
1123 break;
1127 if (hw->pcm_ops->run_buffer_out) {
1128 hw->pcm_ops->run_buffer_out(hw);
1131 return clipped;
1134 static void audio_run_out (AudioState *s)
1136 HWVoiceOut *hw = NULL;
1137 SWVoiceOut *sw;
1139 while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1140 size_t played, live, prev_rpos;
1141 size_t hw_free = audio_pcm_hw_get_free(hw);
1142 int nb_live;
1144 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1145 /* there is exactly 1 sw for each hw with no mixeng */
1146 sw = hw->sw_head.lh_first;
1148 if (hw->pending_disable) {
1149 hw->enabled = 0;
1150 hw->pending_disable = 0;
1151 if (hw->pcm_ops->enable_out) {
1152 hw->pcm_ops->enable_out(hw, false);
1156 if (sw->active) {
1157 sw->callback.fn(sw->callback.opaque,
1158 hw_free * sw->info.bytes_per_frame);
1161 if (hw->pcm_ops->run_buffer_out) {
1162 hw->pcm_ops->run_buffer_out(hw);
1165 continue;
1168 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1169 if (sw->active) {
1170 size_t sw_free = audio_get_free(sw);
1171 size_t free;
1173 if (hw_free > sw->total_hw_samples_mixed) {
1174 free = st_rate_frames_in(sw->rate,
1175 MIN(sw_free, hw_free - sw->total_hw_samples_mixed));
1176 } else {
1177 free = 0;
1179 if (free > sw->resample_buf.pos) {
1180 free = MIN(free, sw->resample_buf.size)
1181 - sw->resample_buf.pos;
1182 sw->callback.fn(sw->callback.opaque,
1183 free * sw->info.bytes_per_frame);
1188 live = audio_pcm_hw_get_live_out (hw, &nb_live);
1189 if (!nb_live) {
1190 live = 0;
1193 if (audio_bug(__func__, live > hw->mix_buf.size)) {
1194 dolog("live=%zu hw->mix_buf.size=%zu\n", live, hw->mix_buf.size);
1195 continue;
1198 if (hw->pending_disable && !nb_live) {
1199 SWVoiceCap *sc;
1200 #ifdef DEBUG_OUT
1201 dolog ("Disabling voice\n");
1202 #endif
1203 hw->enabled = 0;
1204 hw->pending_disable = 0;
1205 if (hw->pcm_ops->enable_out) {
1206 hw->pcm_ops->enable_out(hw, false);
1208 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1209 sc->sw.active = 0;
1210 audio_recalc_and_notify_capture (sc->cap);
1212 continue;
1215 if (!live) {
1216 if (hw->pcm_ops->run_buffer_out) {
1217 hw->pcm_ops->run_buffer_out(hw);
1219 continue;
1222 prev_rpos = hw->mix_buf.pos;
1223 played = audio_pcm_hw_run_out(hw, live);
1224 replay_audio_out(&played);
1225 if (audio_bug(__func__, hw->mix_buf.pos >= hw->mix_buf.size)) {
1226 dolog("hw->mix_buf.pos=%zu hw->mix_buf.size=%zu played=%zu\n",
1227 hw->mix_buf.pos, hw->mix_buf.size, played);
1228 hw->mix_buf.pos = 0;
1231 #ifdef DEBUG_OUT
1232 dolog("played=%zu\n", played);
1233 #endif
1235 if (played) {
1236 hw->ts_helper += played;
1237 audio_capture_mix_and_clear (hw, prev_rpos, played);
1240 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1241 if (!sw->active && sw->empty) {
1242 continue;
1245 if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1246 dolog("played=%zu sw->total_hw_samples_mixed=%zu\n",
1247 played, sw->total_hw_samples_mixed);
1248 played = sw->total_hw_samples_mixed;
1251 sw->total_hw_samples_mixed -= played;
1253 if (!sw->total_hw_samples_mixed) {
1254 sw->empty = 1;
1260 static size_t audio_pcm_hw_run_in(HWVoiceIn *hw, size_t samples)
1262 size_t conv = 0;
1264 if (hw->pcm_ops->run_buffer_in) {
1265 hw->pcm_ops->run_buffer_in(hw);
1268 while (samples) {
1269 size_t proc;
1270 size_t size = samples * hw->info.bytes_per_frame;
1271 void *buf = hw->pcm_ops->get_buffer_in(hw, &size);
1273 assert(size % hw->info.bytes_per_frame == 0);
1274 if (size == 0) {
1275 break;
1278 proc = audio_pcm_hw_conv_in(hw, buf, size / hw->info.bytes_per_frame);
1280 samples -= proc;
1281 conv += proc;
1282 hw->pcm_ops->put_buffer_in(hw, buf, proc * hw->info.bytes_per_frame);
1285 return conv;
1288 static void audio_run_in (AudioState *s)
1290 HWVoiceIn *hw = NULL;
1292 if (!audio_get_pdo_in(s->dev)->mixing_engine) {
1293 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1294 /* there is exactly 1 sw for each hw with no mixeng */
1295 SWVoiceIn *sw = hw->sw_head.lh_first;
1296 if (sw->active) {
1297 sw->callback.fn(sw->callback.opaque, INT_MAX);
1300 return;
1303 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1304 SWVoiceIn *sw;
1305 size_t captured = 0, min;
1307 if (replay_mode != REPLAY_MODE_PLAY) {
1308 captured = audio_pcm_hw_run_in(
1309 hw, hw->conv_buf.size - audio_pcm_hw_get_live_in(hw));
1311 replay_audio_in(&captured, hw->conv_buf.buffer, &hw->conv_buf.pos,
1312 hw->conv_buf.size);
1314 min = audio_pcm_hw_find_min_in (hw);
1315 hw->total_samples_captured += captured - min;
1316 hw->ts_helper += captured;
1318 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1319 sw->total_hw_samples_acquired -= min;
1321 if (sw->active) {
1322 size_t sw_avail = audio_get_avail(sw);
1323 size_t avail;
1325 avail = st_rate_frames_out(sw->rate, sw_avail);
1326 if (avail > 0) {
1327 avail = MIN(avail, sw->resample_buf.size);
1328 sw->callback.fn(sw->callback.opaque,
1329 avail * sw->info.bytes_per_frame);
1336 static void audio_run_capture (AudioState *s)
1338 CaptureVoiceOut *cap;
1340 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1341 size_t live, rpos, captured;
1342 HWVoiceOut *hw = &cap->hw;
1343 SWVoiceOut *sw;
1345 captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1346 rpos = hw->mix_buf.pos;
1347 while (live) {
1348 size_t left = hw->mix_buf.size - rpos;
1349 size_t to_capture = MIN(live, left);
1350 struct st_sample *src;
1351 struct capture_callback *cb;
1353 src = hw->mix_buf.buffer + rpos;
1354 hw->clip (cap->buf, src, to_capture);
1355 mixeng_clear (src, to_capture);
1357 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1358 cb->ops.capture (cb->opaque, cap->buf,
1359 to_capture * hw->info.bytes_per_frame);
1361 rpos = (rpos + to_capture) % hw->mix_buf.size;
1362 live -= to_capture;
1364 hw->mix_buf.pos = rpos;
1366 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1367 if (!sw->active && sw->empty) {
1368 continue;
1371 if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1372 dolog("captured=%zu sw->total_hw_samples_mixed=%zu\n",
1373 captured, sw->total_hw_samples_mixed);
1374 captured = sw->total_hw_samples_mixed;
1377 sw->total_hw_samples_mixed -= captured;
1378 sw->empty = sw->total_hw_samples_mixed == 0;
1383 void audio_run(AudioState *s, const char *msg)
1385 audio_run_out(s);
1386 audio_run_in(s);
1387 audio_run_capture(s);
1389 #ifdef DEBUG_POLL
1391 static double prevtime;
1392 double currtime;
1393 struct timeval tv;
1395 if (gettimeofday (&tv, NULL)) {
1396 perror ("audio_run: gettimeofday");
1397 return;
1400 currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1401 dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1402 prevtime = currtime;
1404 #endif
1407 void audio_generic_run_buffer_in(HWVoiceIn *hw)
1409 if (unlikely(!hw->buf_emul)) {
1410 hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1411 hw->buf_emul = g_malloc(hw->size_emul);
1412 hw->pos_emul = hw->pending_emul = 0;
1415 while (hw->pending_emul < hw->size_emul) {
1416 size_t read_len = MIN(hw->size_emul - hw->pos_emul,
1417 hw->size_emul - hw->pending_emul);
1418 size_t read = hw->pcm_ops->read(hw, hw->buf_emul + hw->pos_emul,
1419 read_len);
1420 hw->pending_emul += read;
1421 hw->pos_emul = (hw->pos_emul + read) % hw->size_emul;
1422 if (read < read_len) {
1423 break;
1428 void *audio_generic_get_buffer_in(HWVoiceIn *hw, size_t *size)
1430 size_t start;
1432 start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1433 assert(start < hw->size_emul);
1435 *size = MIN(*size, hw->pending_emul);
1436 *size = MIN(*size, hw->size_emul - start);
1437 return hw->buf_emul + start;
1440 void audio_generic_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
1442 assert(size <= hw->pending_emul);
1443 hw->pending_emul -= size;
1446 size_t audio_generic_buffer_get_free(HWVoiceOut *hw)
1448 if (hw->buf_emul) {
1449 return hw->size_emul - hw->pending_emul;
1450 } else {
1451 return hw->samples * hw->info.bytes_per_frame;
1455 void audio_generic_run_buffer_out(HWVoiceOut *hw)
1457 while (hw->pending_emul) {
1458 size_t write_len, written, start;
1460 start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1461 assert(start < hw->size_emul);
1463 write_len = MIN(hw->pending_emul, hw->size_emul - start);
1465 written = hw->pcm_ops->write(hw, hw->buf_emul + start, write_len);
1466 hw->pending_emul -= written;
1468 if (written < write_len) {
1469 break;
1474 void *audio_generic_get_buffer_out(HWVoiceOut *hw, size_t *size)
1476 if (unlikely(!hw->buf_emul)) {
1477 hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1478 hw->buf_emul = g_malloc(hw->size_emul);
1479 hw->pos_emul = hw->pending_emul = 0;
1482 *size = MIN(hw->size_emul - hw->pending_emul,
1483 hw->size_emul - hw->pos_emul);
1484 return hw->buf_emul + hw->pos_emul;
1487 size_t audio_generic_put_buffer_out(HWVoiceOut *hw, void *buf, size_t size)
1489 assert(buf == hw->buf_emul + hw->pos_emul &&
1490 size + hw->pending_emul <= hw->size_emul);
1492 hw->pending_emul += size;
1493 hw->pos_emul = (hw->pos_emul + size) % hw->size_emul;
1495 return size;
1498 size_t audio_generic_write(HWVoiceOut *hw, void *buf, size_t size)
1500 size_t total = 0;
1502 if (hw->pcm_ops->buffer_get_free) {
1503 size_t free = hw->pcm_ops->buffer_get_free(hw);
1505 size = MIN(size, free);
1508 while (total < size) {
1509 size_t dst_size = size - total;
1510 size_t copy_size, proc;
1511 void *dst = hw->pcm_ops->get_buffer_out(hw, &dst_size);
1513 if (dst_size == 0) {
1514 break;
1517 copy_size = MIN(size - total, dst_size);
1518 if (dst) {
1519 memcpy(dst, (char *)buf + total, copy_size);
1521 proc = hw->pcm_ops->put_buffer_out(hw, dst, copy_size);
1522 total += proc;
1524 if (proc == 0 || proc < copy_size) {
1525 break;
1529 return total;
1532 size_t audio_generic_read(HWVoiceIn *hw, void *buf, size_t size)
1534 size_t total = 0;
1536 if (hw->pcm_ops->run_buffer_in) {
1537 hw->pcm_ops->run_buffer_in(hw);
1540 while (total < size) {
1541 size_t src_size = size - total;
1542 void *src = hw->pcm_ops->get_buffer_in(hw, &src_size);
1544 if (src_size == 0) {
1545 break;
1548 memcpy((char *)buf + total, src, src_size);
1549 hw->pcm_ops->put_buffer_in(hw, src, src_size);
1550 total += src_size;
1553 return total;
1556 static int audio_driver_init(AudioState *s, struct audio_driver *drv,
1557 bool msg, Audiodev *dev)
1559 Error *local_err = NULL;
1561 s->drv_opaque = drv->init(dev, &local_err);
1563 if (s->drv_opaque) {
1564 if (!drv->pcm_ops->get_buffer_in) {
1565 drv->pcm_ops->get_buffer_in = audio_generic_get_buffer_in;
1566 drv->pcm_ops->put_buffer_in = audio_generic_put_buffer_in;
1568 if (!drv->pcm_ops->get_buffer_out) {
1569 drv->pcm_ops->get_buffer_out = audio_generic_get_buffer_out;
1570 drv->pcm_ops->put_buffer_out = audio_generic_put_buffer_out;
1573 audio_init_nb_voices_out(s, drv);
1574 audio_init_nb_voices_in(s, drv);
1575 s->drv = drv;
1576 return 0;
1577 } else {
1578 if (!msg) {
1579 error_free(local_err);
1580 } else if (local_err) {
1581 error_report_err(local_err);
1582 } else {
1583 error_report("Could not init `%s' audio driver", drv->name);
1585 return -1;
1589 static void audio_vm_change_state_handler (void *opaque, bool running,
1590 RunState state)
1592 AudioState *s = opaque;
1593 HWVoiceOut *hwo = NULL;
1594 HWVoiceIn *hwi = NULL;
1596 s->vm_running = running;
1597 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
1598 if (hwo->pcm_ops->enable_out) {
1599 hwo->pcm_ops->enable_out(hwo, running);
1603 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
1604 if (hwi->pcm_ops->enable_in) {
1605 hwi->pcm_ops->enable_in(hwi, running);
1608 audio_reset_timer (s);
1611 static void free_audio_state(AudioState *s)
1613 HWVoiceOut *hwo, *hwon;
1614 HWVoiceIn *hwi, *hwin;
1616 QLIST_FOREACH_SAFE(hwo, &s->hw_head_out, entries, hwon) {
1617 SWVoiceCap *sc;
1619 if (hwo->enabled && hwo->pcm_ops->enable_out) {
1620 hwo->pcm_ops->enable_out(hwo, false);
1622 hwo->pcm_ops->fini_out (hwo);
1624 for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1625 CaptureVoiceOut *cap = sc->cap;
1626 struct capture_callback *cb;
1628 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1629 cb->ops.destroy (cb->opaque);
1632 QLIST_REMOVE(hwo, entries);
1635 QLIST_FOREACH_SAFE(hwi, &s->hw_head_in, entries, hwin) {
1636 if (hwi->enabled && hwi->pcm_ops->enable_in) {
1637 hwi->pcm_ops->enable_in(hwi, false);
1639 hwi->pcm_ops->fini_in (hwi);
1640 QLIST_REMOVE(hwi, entries);
1643 if (s->drv) {
1644 s->drv->fini (s->drv_opaque);
1645 s->drv = NULL;
1648 if (s->dev) {
1649 qapi_free_Audiodev(s->dev);
1650 s->dev = NULL;
1653 if (s->ts) {
1654 timer_free(s->ts);
1655 s->ts = NULL;
1658 g_free(s);
1661 void audio_cleanup(void)
1663 while (!QTAILQ_EMPTY(&audio_states)) {
1664 AudioState *s = QTAILQ_FIRST(&audio_states);
1665 QTAILQ_REMOVE(&audio_states, s, list);
1666 free_audio_state(s);
1670 static bool vmstate_audio_needed(void *opaque)
1673 * Never needed, this vmstate only exists in case
1674 * an old qemu sends it to us.
1676 return false;
1679 static const VMStateDescription vmstate_audio = {
1680 .name = "audio",
1681 .version_id = 1,
1682 .minimum_version_id = 1,
1683 .needed = vmstate_audio_needed,
1684 .fields = (VMStateField[]) {
1685 VMSTATE_END_OF_LIST()
1689 static void audio_validate_opts(Audiodev *dev, Error **errp);
1691 static AudiodevListEntry *audiodev_find(
1692 AudiodevListHead *head, const char *drvname)
1694 AudiodevListEntry *e;
1695 QSIMPLEQ_FOREACH(e, head, next) {
1696 if (strcmp(AudiodevDriver_str(e->dev->driver), drvname) == 0) {
1697 return e;
1701 return NULL;
1705 * if we have dev, this function was called because of an -audiodev argument =>
1706 * initialize a new state with it
1707 * if dev == NULL => legacy implicit initialization, return the already created
1708 * state or create a new one
1710 static AudioState *audio_init(Audiodev *dev, const char *name)
1712 static bool atexit_registered;
1713 size_t i;
1714 int done = 0;
1715 const char *drvname = NULL;
1716 VMChangeStateEntry *vmse;
1717 AudioState *s;
1718 struct audio_driver *driver;
1719 /* silence gcc warning about uninitialized variable */
1720 AudiodevListHead head = QSIMPLEQ_HEAD_INITIALIZER(head);
1722 if (using_spice) {
1724 * When using spice allow the spice audio driver being picked
1725 * as default.
1727 * Temporary hack. Using audio devices without explicit
1728 * audiodev= property is already deprecated. Same goes for
1729 * the -soundhw switch. Once this support gets finally
1730 * removed we can also drop the concept of a default audio
1731 * backend and this can go away.
1733 driver = audio_driver_lookup("spice");
1734 if (driver) {
1735 driver->can_be_default = 1;
1739 if (dev) {
1740 /* -audiodev option */
1741 legacy_config = false;
1742 drvname = AudiodevDriver_str(dev->driver);
1743 } else if (!QTAILQ_EMPTY(&audio_states)) {
1744 if (!legacy_config) {
1745 dolog("Device %s: audiodev default parameter is deprecated, please "
1746 "specify audiodev=%s\n", name,
1747 QTAILQ_FIRST(&audio_states)->dev->id);
1749 return QTAILQ_FIRST(&audio_states);
1750 } else {
1751 /* legacy implicit initialization */
1752 head = audio_handle_legacy_opts();
1754 * In case of legacy initialization, all Audiodevs in the list will have
1755 * the same configuration (except the driver), so it doesn't matter which
1756 * one we chose. We need an Audiodev to set up AudioState before we can
1757 * init a driver. Also note that dev at this point is still in the
1758 * list.
1760 dev = QSIMPLEQ_FIRST(&head)->dev;
1761 audio_validate_opts(dev, &error_abort);
1764 s = g_new0(AudioState, 1);
1765 s->dev = dev;
1767 QLIST_INIT (&s->hw_head_out);
1768 QLIST_INIT (&s->hw_head_in);
1769 QLIST_INIT (&s->cap_head);
1770 if (!atexit_registered) {
1771 atexit(audio_cleanup);
1772 atexit_registered = true;
1775 s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1777 s->nb_hw_voices_out = audio_get_pdo_out(dev)->voices;
1778 s->nb_hw_voices_in = audio_get_pdo_in(dev)->voices;
1780 if (s->nb_hw_voices_out < 1) {
1781 dolog ("Bogus number of playback voices %d, setting to 1\n",
1782 s->nb_hw_voices_out);
1783 s->nb_hw_voices_out = 1;
1786 if (s->nb_hw_voices_in < 0) {
1787 dolog ("Bogus number of capture voices %d, setting to 0\n",
1788 s->nb_hw_voices_in);
1789 s->nb_hw_voices_in = 0;
1792 if (drvname) {
1793 driver = audio_driver_lookup(drvname);
1794 if (driver) {
1795 done = !audio_driver_init(s, driver, true, dev);
1796 } else {
1797 dolog ("Unknown audio driver `%s'\n", drvname);
1799 if (!done) {
1800 free_audio_state(s);
1801 return NULL;
1803 } else {
1804 for (i = 0; audio_prio_list[i]; i++) {
1805 AudiodevListEntry *e = audiodev_find(&head, audio_prio_list[i]);
1806 driver = audio_driver_lookup(audio_prio_list[i]);
1808 if (e && driver) {
1809 s->dev = dev = e->dev;
1810 audio_validate_opts(dev, &error_abort);
1811 done = !audio_driver_init(s, driver, false, dev);
1812 if (done) {
1813 e->dev = NULL;
1814 break;
1819 audio_free_audiodev_list(&head);
1821 if (!done) {
1822 driver = audio_driver_lookup("none");
1823 done = !audio_driver_init(s, driver, false, dev);
1824 assert(done);
1825 dolog("warning: Using timer based audio emulation\n");
1828 if (dev->timer_period <= 0) {
1829 s->period_ticks = 1;
1830 } else {
1831 s->period_ticks = dev->timer_period * (int64_t)SCALE_US;
1834 vmse = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1835 if (!vmse) {
1836 dolog ("warning: Could not register change state handler\n"
1837 "(Audio can continue looping even after stopping the VM)\n");
1840 QTAILQ_INSERT_TAIL(&audio_states, s, list);
1841 QLIST_INIT (&s->card_head);
1842 vmstate_register (NULL, 0, &vmstate_audio, s);
1843 return s;
1846 void audio_free_audiodev_list(AudiodevListHead *head)
1848 AudiodevListEntry *e;
1849 while ((e = QSIMPLEQ_FIRST(head))) {
1850 QSIMPLEQ_REMOVE_HEAD(head, next);
1851 qapi_free_Audiodev(e->dev);
1852 g_free(e);
1856 void AUD_register_card (const char *name, QEMUSoundCard *card)
1858 if (!card->state) {
1859 card->state = audio_init(NULL, name);
1862 card->name = g_strdup (name);
1863 memset (&card->entries, 0, sizeof (card->entries));
1864 QLIST_INSERT_HEAD(&card->state->card_head, card, entries);
1867 void AUD_remove_card (QEMUSoundCard *card)
1869 QLIST_REMOVE (card, entries);
1870 g_free (card->name);
1873 static struct audio_pcm_ops capture_pcm_ops;
1875 CaptureVoiceOut *AUD_add_capture(
1876 AudioState *s,
1877 struct audsettings *as,
1878 struct audio_capture_ops *ops,
1879 void *cb_opaque
1882 CaptureVoiceOut *cap;
1883 struct capture_callback *cb;
1885 if (!s) {
1886 error_report("Capturing without setting an audiodev is not supported");
1887 abort();
1890 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1891 dolog("Can't capture with mixeng disabled\n");
1892 return NULL;
1895 if (audio_validate_settings (as)) {
1896 dolog ("Invalid settings were passed when trying to add capture\n");
1897 audio_print_settings (as);
1898 return NULL;
1901 cb = g_malloc0(sizeof(*cb));
1902 cb->ops = *ops;
1903 cb->opaque = cb_opaque;
1905 cap = audio_pcm_capture_find_specific(s, as);
1906 if (cap) {
1907 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1908 } else {
1909 HWVoiceOut *hw;
1911 cap = g_malloc0(sizeof(*cap));
1913 hw = &cap->hw;
1914 hw->s = s;
1915 hw->pcm_ops = &capture_pcm_ops;
1916 QLIST_INIT (&hw->sw_head);
1917 QLIST_INIT (&cap->cb_head);
1919 /* XXX find a more elegant way */
1920 hw->samples = 4096 * 4;
1921 audio_pcm_hw_alloc_resources_out(hw);
1923 audio_pcm_init_info (&hw->info, as);
1925 cap->buf = g_malloc0_n(hw->mix_buf.size, hw->info.bytes_per_frame);
1927 if (hw->info.is_float) {
1928 hw->clip = mixeng_clip_float[hw->info.nchannels == 2];
1929 } else {
1930 hw->clip = mixeng_clip
1931 [hw->info.nchannels == 2]
1932 [hw->info.is_signed]
1933 [hw->info.swap_endianness]
1934 [audio_bits_to_index(hw->info.bits)];
1937 QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1938 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1940 QLIST_FOREACH(hw, &s->hw_head_out, entries) {
1941 audio_attach_capture (hw);
1945 return cap;
1948 void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1950 struct capture_callback *cb;
1952 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1953 if (cb->opaque == cb_opaque) {
1954 cb->ops.destroy (cb_opaque);
1955 QLIST_REMOVE (cb, entries);
1956 g_free (cb);
1958 if (!cap->cb_head.lh_first) {
1959 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
1961 while (sw) {
1962 SWVoiceCap *sc = (SWVoiceCap *) sw;
1963 #ifdef DEBUG_CAPTURE
1964 dolog ("freeing %s\n", sw->name);
1965 #endif
1967 sw1 = sw->entries.le_next;
1968 if (sw->rate) {
1969 st_rate_stop (sw->rate);
1970 sw->rate = NULL;
1972 QLIST_REMOVE (sw, entries);
1973 QLIST_REMOVE (sc, entries);
1974 g_free (sc);
1975 sw = sw1;
1977 QLIST_REMOVE (cap, entries);
1978 g_free(cap->hw.mix_buf.buffer);
1979 g_free (cap->buf);
1980 g_free (cap);
1982 return;
1987 void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
1989 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1990 audio_set_volume_out(sw, &vol);
1993 void audio_set_volume_out(SWVoiceOut *sw, Volume *vol)
1995 if (sw) {
1996 HWVoiceOut *hw = sw->hw;
1998 sw->vol.mute = vol->mute;
1999 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
2000 sw->vol.r = nominal_volume.l * vol->vol[vol->channels > 1 ? 1 : 0] /
2001 255;
2003 if (hw->pcm_ops->volume_out) {
2004 hw->pcm_ops->volume_out(hw, vol);
2009 void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
2011 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
2012 audio_set_volume_in(sw, &vol);
2015 void audio_set_volume_in(SWVoiceIn *sw, Volume *vol)
2017 if (sw) {
2018 HWVoiceIn *hw = sw->hw;
2020 sw->vol.mute = vol->mute;
2021 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
2022 sw->vol.r = nominal_volume.r * vol->vol[vol->channels > 1 ? 1 : 0] /
2023 255;
2025 if (hw->pcm_ops->volume_in) {
2026 hw->pcm_ops->volume_in(hw, vol);
2031 void audio_create_pdos(Audiodev *dev)
2033 switch (dev->driver) {
2034 #define CASE(DRIVER, driver, pdo_name) \
2035 case AUDIODEV_DRIVER_##DRIVER: \
2036 if (!dev->u.driver.in) { \
2037 dev->u.driver.in = g_malloc0( \
2038 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
2040 if (!dev->u.driver.out) { \
2041 dev->u.driver.out = g_malloc0( \
2042 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
2044 break
2046 CASE(NONE, none, );
2047 #ifdef CONFIG_AUDIO_ALSA
2048 CASE(ALSA, alsa, Alsa);
2049 #endif
2050 #ifdef CONFIG_AUDIO_COREAUDIO
2051 CASE(COREAUDIO, coreaudio, Coreaudio);
2052 #endif
2053 #ifdef CONFIG_DBUS_DISPLAY
2054 CASE(DBUS, dbus, );
2055 #endif
2056 #ifdef CONFIG_AUDIO_DSOUND
2057 CASE(DSOUND, dsound, );
2058 #endif
2059 #ifdef CONFIG_AUDIO_JACK
2060 CASE(JACK, jack, Jack);
2061 #endif
2062 #ifdef CONFIG_AUDIO_OSS
2063 CASE(OSS, oss, Oss);
2064 #endif
2065 #ifdef CONFIG_AUDIO_PA
2066 CASE(PA, pa, Pa);
2067 #endif
2068 #ifdef CONFIG_AUDIO_PIPEWIRE
2069 CASE(PIPEWIRE, pipewire, Pipewire);
2070 #endif
2071 #ifdef CONFIG_AUDIO_SDL
2072 CASE(SDL, sdl, Sdl);
2073 #endif
2074 #ifdef CONFIG_AUDIO_SNDIO
2075 CASE(SNDIO, sndio, );
2076 #endif
2077 #ifdef CONFIG_SPICE
2078 CASE(SPICE, spice, );
2079 #endif
2080 CASE(WAV, wav, );
2082 case AUDIODEV_DRIVER__MAX:
2083 abort();
2087 static void audio_validate_per_direction_opts(
2088 AudiodevPerDirectionOptions *pdo, Error **errp)
2090 if (!pdo->has_mixing_engine) {
2091 pdo->has_mixing_engine = true;
2092 pdo->mixing_engine = true;
2094 if (!pdo->has_fixed_settings) {
2095 pdo->has_fixed_settings = true;
2096 pdo->fixed_settings = pdo->mixing_engine;
2098 if (!pdo->fixed_settings &&
2099 (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
2100 error_setg(errp,
2101 "You can't use frequency, channels or format with fixed-settings=off");
2102 return;
2104 if (!pdo->mixing_engine && pdo->fixed_settings) {
2105 error_setg(errp, "You can't use fixed-settings without mixeng");
2106 return;
2109 if (!pdo->has_frequency) {
2110 pdo->has_frequency = true;
2111 pdo->frequency = 44100;
2113 if (!pdo->has_channels) {
2114 pdo->has_channels = true;
2115 pdo->channels = 2;
2117 if (!pdo->has_voices) {
2118 pdo->has_voices = true;
2119 pdo->voices = pdo->mixing_engine ? 1 : INT_MAX;
2121 if (!pdo->has_format) {
2122 pdo->has_format = true;
2123 pdo->format = AUDIO_FORMAT_S16;
2127 static void audio_validate_opts(Audiodev *dev, Error **errp)
2129 Error *err = NULL;
2131 audio_create_pdos(dev);
2133 audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
2134 if (err) {
2135 error_propagate(errp, err);
2136 return;
2139 audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
2140 if (err) {
2141 error_propagate(errp, err);
2142 return;
2145 if (!dev->has_timer_period) {
2146 dev->has_timer_period = true;
2147 dev->timer_period = 10000; /* 100Hz -> 10ms */
2151 void audio_help(void)
2153 int i;
2155 printf("Available audio drivers:\n");
2157 for (i = 0; i < AUDIODEV_DRIVER__MAX; i++) {
2158 audio_driver *driver = audio_driver_lookup(AudiodevDriver_str(i));
2159 if (driver) {
2160 printf("%s\n", driver->name);
2165 void audio_parse_option(const char *opt)
2167 Audiodev *dev = NULL;
2169 if (is_help_option(opt)) {
2170 audio_help();
2171 exit(EXIT_SUCCESS);
2173 Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
2174 visit_type_Audiodev(v, NULL, &dev, &error_fatal);
2175 visit_free(v);
2177 audio_define(dev);
2180 void audio_define(Audiodev *dev)
2182 AudiodevListEntry *e;
2184 audio_validate_opts(dev, &error_fatal);
2186 e = g_new0(AudiodevListEntry, 1);
2187 e->dev = dev;
2188 QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
2191 bool audio_init_audiodevs(void)
2193 AudiodevListEntry *e;
2195 QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2196 if (!audio_init(e->dev, NULL)) {
2197 return false;
2201 return true;
2204 audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
2206 return (audsettings) {
2207 .freq = pdo->frequency,
2208 .nchannels = pdo->channels,
2209 .fmt = pdo->format,
2210 .endianness = AUDIO_HOST_ENDIANNESS,
2214 int audioformat_bytes_per_sample(AudioFormat fmt)
2216 switch (fmt) {
2217 case AUDIO_FORMAT_U8:
2218 case AUDIO_FORMAT_S8:
2219 return 1;
2221 case AUDIO_FORMAT_U16:
2222 case AUDIO_FORMAT_S16:
2223 return 2;
2225 case AUDIO_FORMAT_U32:
2226 case AUDIO_FORMAT_S32:
2227 case AUDIO_FORMAT_F32:
2228 return 4;
2230 case AUDIO_FORMAT__MAX:
2233 abort();
2237 /* frames = freq * usec / 1e6 */
2238 int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
2239 audsettings *as, int def_usecs)
2241 uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
2242 return (as->freq * usecs + 500000) / 1000000;
2245 /* samples = channels * frames = channels * freq * usec / 1e6 */
2246 int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
2247 audsettings *as, int def_usecs)
2249 return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
2253 * bytes = bytes_per_sample * samples =
2254 * bytes_per_sample * channels * freq * usec / 1e6
2256 int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
2257 audsettings *as, int def_usecs)
2259 return audio_buffer_samples(pdo, as, def_usecs) *
2260 audioformat_bytes_per_sample(as->fmt);
2263 AudioState *audio_state_by_name(const char *name)
2265 AudioState *s;
2266 QTAILQ_FOREACH(s, &audio_states, list) {
2267 assert(s->dev);
2268 if (strcmp(name, s->dev->id) == 0) {
2269 return s;
2272 return NULL;
2275 const char *audio_get_id(QEMUSoundCard *card)
2277 if (card->state) {
2278 assert(card->state->dev);
2279 return card->state->dev->id;
2280 } else {
2281 return "";
2285 const char *audio_application_name(void)
2287 const char *vm_name;
2289 vm_name = qemu_get_vm_name();
2290 return vm_name ? vm_name : "qemu";
2293 void audio_rate_start(RateCtl *rate)
2295 memset(rate, 0, sizeof(RateCtl));
2296 rate->start_ticks = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2299 size_t audio_rate_peek_bytes(RateCtl *rate, struct audio_pcm_info *info)
2301 int64_t now;
2302 int64_t ticks;
2303 int64_t bytes;
2304 int64_t frames;
2306 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2307 ticks = now - rate->start_ticks;
2308 bytes = muldiv64(ticks, info->bytes_per_second, NANOSECONDS_PER_SECOND);
2309 frames = (bytes - rate->bytes_sent) / info->bytes_per_frame;
2310 if (frames < 0 || frames > 65536) {
2311 AUD_log(NULL, "Resetting rate control (%" PRId64 " frames)\n", frames);
2312 audio_rate_start(rate);
2313 frames = 0;
2316 return frames * info->bytes_per_frame;
2319 void audio_rate_add_bytes(RateCtl *rate, size_t bytes_used)
2321 rate->bytes_sent += bytes_used;
2324 size_t audio_rate_get_bytes(RateCtl *rate, struct audio_pcm_info *info,
2325 size_t bytes_avail)
2327 size_t bytes;
2329 bytes = audio_rate_peek_bytes(rate, info);
2330 bytes = MIN(bytes, bytes_avail);
2331 audio_rate_add_bytes(rate, bytes);
2333 return bytes;
2336 AudiodevList *qmp_query_audiodevs(Error **errp)
2338 AudiodevList *ret = NULL;
2339 AudiodevListEntry *e;
2340 QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2341 QAPI_LIST_PREPEND(ret, QAPI_CLONE(Audiodev, e->dev));
2343 return ret;