docs: do not talk about past removal as happening in the future
[qemu.git] / audio / audio.c
blobd849a94a8176ae8db724758961d308a518d3d645
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/qobject-input-visitor.h"
32 #include "qapi/qapi-visit-audio.h"
33 #include "qemu/cutils.h"
34 #include "qemu/module.h"
35 #include "qemu/help_option.h"
36 #include "sysemu/sysemu.h"
37 #include "sysemu/replay.h"
38 #include "sysemu/runstate.h"
39 #include "ui/qemu-spice.h"
40 #include "trace.h"
42 #define AUDIO_CAP "audio"
43 #include "audio_int.h"
45 /* #define DEBUG_LIVE */
46 /* #define DEBUG_OUT */
47 /* #define DEBUG_CAPTURE */
48 /* #define DEBUG_POLL */
50 #define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
53 /* Order of CONFIG_AUDIO_DRIVERS is import.
54 The 1st one is the one used by default, that is the reason
55 that we generate the list.
57 const char *audio_prio_list[] = {
58 "spice",
59 CONFIG_AUDIO_DRIVERS
60 "none",
61 "wav",
62 NULL
65 static QLIST_HEAD(, audio_driver) audio_drivers;
66 static AudiodevListHead audiodevs = QSIMPLEQ_HEAD_INITIALIZER(audiodevs);
68 void audio_driver_register(audio_driver *drv)
70 QLIST_INSERT_HEAD(&audio_drivers, drv, next);
73 audio_driver *audio_driver_lookup(const char *name)
75 struct audio_driver *d;
76 Error *local_err = NULL;
77 int rv;
79 QLIST_FOREACH(d, &audio_drivers, next) {
80 if (strcmp(name, d->name) == 0) {
81 return d;
84 rv = audio_module_load(name, &local_err);
85 if (rv > 0) {
86 QLIST_FOREACH(d, &audio_drivers, next) {
87 if (strcmp(name, d->name) == 0) {
88 return d;
91 } else if (rv < 0) {
92 error_report_err(local_err);
94 return NULL;
97 static QTAILQ_HEAD(AudioStateHead, AudioState) audio_states =
98 QTAILQ_HEAD_INITIALIZER(audio_states);
100 const struct mixeng_volume nominal_volume = {
101 .mute = 0,
102 #ifdef FLOAT_MIXENG
103 .r = 1.0,
104 .l = 1.0,
105 #else
106 .r = 1ULL << 32,
107 .l = 1ULL << 32,
108 #endif
111 static bool legacy_config = true;
113 int audio_bug (const char *funcname, int cond)
115 if (cond) {
116 static int shown;
118 AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
119 if (!shown) {
120 shown = 1;
121 AUD_log (NULL, "Save all your work and restart without audio\n");
122 AUD_log (NULL, "I am sorry\n");
124 AUD_log (NULL, "Context:\n");
127 return cond;
130 static inline int audio_bits_to_index (int bits)
132 switch (bits) {
133 case 8:
134 return 0;
136 case 16:
137 return 1;
139 case 32:
140 return 2;
142 default:
143 audio_bug ("bits_to_index", 1);
144 AUD_log (NULL, "invalid bits %d\n", bits);
145 return 0;
149 void *audio_calloc (const char *funcname, int nmemb, size_t size)
151 int cond;
152 size_t len;
154 len = nmemb * size;
155 cond = !nmemb || !size;
156 cond |= nmemb < 0;
157 cond |= len < size;
159 if (audio_bug ("audio_calloc", cond)) {
160 AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
161 funcname);
162 AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
163 return NULL;
166 return g_malloc0 (len);
169 void AUD_vlog (const char *cap, const char *fmt, va_list ap)
171 if (cap) {
172 fprintf(stderr, "%s: ", cap);
175 vfprintf(stderr, fmt, ap);
178 void AUD_log (const char *cap, const char *fmt, ...)
180 va_list ap;
182 va_start (ap, fmt);
183 AUD_vlog (cap, fmt, ap);
184 va_end (ap);
187 static void audio_print_settings (struct audsettings *as)
189 dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
191 switch (as->fmt) {
192 case AUDIO_FORMAT_S8:
193 AUD_log (NULL, "S8");
194 break;
195 case AUDIO_FORMAT_U8:
196 AUD_log (NULL, "U8");
197 break;
198 case AUDIO_FORMAT_S16:
199 AUD_log (NULL, "S16");
200 break;
201 case AUDIO_FORMAT_U16:
202 AUD_log (NULL, "U16");
203 break;
204 case AUDIO_FORMAT_S32:
205 AUD_log (NULL, "S32");
206 break;
207 case AUDIO_FORMAT_U32:
208 AUD_log (NULL, "U32");
209 break;
210 case AUDIO_FORMAT_F32:
211 AUD_log (NULL, "F32");
212 break;
213 default:
214 AUD_log (NULL, "invalid(%d)", as->fmt);
215 break;
218 AUD_log (NULL, " endianness=");
219 switch (as->endianness) {
220 case 0:
221 AUD_log (NULL, "little");
222 break;
223 case 1:
224 AUD_log (NULL, "big");
225 break;
226 default:
227 AUD_log (NULL, "invalid");
228 break;
230 AUD_log (NULL, "\n");
233 static int audio_validate_settings (struct audsettings *as)
235 int invalid;
237 invalid = as->nchannels < 1;
238 invalid |= as->endianness != 0 && as->endianness != 1;
240 switch (as->fmt) {
241 case AUDIO_FORMAT_S8:
242 case AUDIO_FORMAT_U8:
243 case AUDIO_FORMAT_S16:
244 case AUDIO_FORMAT_U16:
245 case AUDIO_FORMAT_S32:
246 case AUDIO_FORMAT_U32:
247 case AUDIO_FORMAT_F32:
248 break;
249 default:
250 invalid = 1;
251 break;
254 invalid |= as->freq <= 0;
255 return invalid ? -1 : 0;
258 static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
260 int bits = 8;
261 bool is_signed = false, is_float = false;
263 switch (as->fmt) {
264 case AUDIO_FORMAT_S8:
265 is_signed = true;
266 /* fall through */
267 case AUDIO_FORMAT_U8:
268 break;
270 case AUDIO_FORMAT_S16:
271 is_signed = true;
272 /* fall through */
273 case AUDIO_FORMAT_U16:
274 bits = 16;
275 break;
277 case AUDIO_FORMAT_F32:
278 is_float = true;
279 /* fall through */
280 case AUDIO_FORMAT_S32:
281 is_signed = true;
282 /* fall through */
283 case AUDIO_FORMAT_U32:
284 bits = 32;
285 break;
287 default:
288 abort();
290 return info->freq == as->freq
291 && info->nchannels == as->nchannels
292 && info->is_signed == is_signed
293 && info->is_float == is_float
294 && info->bits == bits
295 && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
298 void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
300 int bits = 8, mul;
301 bool is_signed = false, is_float = false;
303 switch (as->fmt) {
304 case AUDIO_FORMAT_S8:
305 is_signed = true;
306 /* fall through */
307 case AUDIO_FORMAT_U8:
308 mul = 1;
309 break;
311 case AUDIO_FORMAT_S16:
312 is_signed = true;
313 /* fall through */
314 case AUDIO_FORMAT_U16:
315 bits = 16;
316 mul = 2;
317 break;
319 case AUDIO_FORMAT_F32:
320 is_float = true;
321 /* fall through */
322 case AUDIO_FORMAT_S32:
323 is_signed = true;
324 /* fall through */
325 case AUDIO_FORMAT_U32:
326 bits = 32;
327 mul = 4;
328 break;
330 default:
331 abort();
334 info->freq = as->freq;
335 info->bits = bits;
336 info->is_signed = is_signed;
337 info->is_float = is_float;
338 info->nchannels = as->nchannels;
339 info->bytes_per_frame = as->nchannels * mul;
340 info->bytes_per_second = info->freq * info->bytes_per_frame;
341 info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
344 void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
346 if (!len) {
347 return;
350 if (info->is_signed || info->is_float) {
351 memset(buf, 0x00, len * info->bytes_per_frame);
352 } else {
353 switch (info->bits) {
354 case 8:
355 memset(buf, 0x80, len * info->bytes_per_frame);
356 break;
358 case 16:
360 int i;
361 uint16_t *p = buf;
362 short s = INT16_MAX;
364 if (info->swap_endianness) {
365 s = bswap16 (s);
368 for (i = 0; i < len * info->nchannels; i++) {
369 p[i] = s;
372 break;
374 case 32:
376 int i;
377 uint32_t *p = buf;
378 int32_t s = INT32_MAX;
380 if (info->swap_endianness) {
381 s = bswap32 (s);
384 for (i = 0; i < len * info->nchannels; i++) {
385 p[i] = s;
388 break;
390 default:
391 AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
392 info->bits);
393 break;
399 * Capture
401 static void noop_conv (struct st_sample *dst, const void *src, int samples)
403 (void) src;
404 (void) dst;
405 (void) samples;
408 static CaptureVoiceOut *audio_pcm_capture_find_specific(AudioState *s,
409 struct audsettings *as)
411 CaptureVoiceOut *cap;
413 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
414 if (audio_pcm_info_eq (&cap->hw.info, as)) {
415 return cap;
418 return NULL;
421 static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
423 struct capture_callback *cb;
425 #ifdef DEBUG_CAPTURE
426 dolog ("notification %d sent\n", cmd);
427 #endif
428 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
429 cb->ops.notify (cb->opaque, cmd);
433 static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
435 if (cap->hw.enabled != enabled) {
436 audcnotification_e cmd;
437 cap->hw.enabled = enabled;
438 cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
439 audio_notify_capture (cap, cmd);
443 static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
445 HWVoiceOut *hw = &cap->hw;
446 SWVoiceOut *sw;
447 int enabled = 0;
449 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
450 if (sw->active) {
451 enabled = 1;
452 break;
455 audio_capture_maybe_changed (cap, enabled);
458 static void audio_detach_capture (HWVoiceOut *hw)
460 SWVoiceCap *sc = hw->cap_head.lh_first;
462 while (sc) {
463 SWVoiceCap *sc1 = sc->entries.le_next;
464 SWVoiceOut *sw = &sc->sw;
465 CaptureVoiceOut *cap = sc->cap;
466 int was_active = sw->active;
468 if (sw->rate) {
469 st_rate_stop (sw->rate);
470 sw->rate = NULL;
473 QLIST_REMOVE (sw, entries);
474 QLIST_REMOVE (sc, entries);
475 g_free (sc);
476 if (was_active) {
477 /* We have removed soft voice from the capture:
478 this might have changed the overall status of the capture
479 since this might have been the only active voice */
480 audio_recalc_and_notify_capture (cap);
482 sc = sc1;
486 static int audio_attach_capture (HWVoiceOut *hw)
488 AudioState *s = hw->s;
489 CaptureVoiceOut *cap;
491 audio_detach_capture (hw);
492 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
493 SWVoiceCap *sc;
494 SWVoiceOut *sw;
495 HWVoiceOut *hw_cap = &cap->hw;
497 sc = g_malloc0(sizeof(*sc));
499 sc->cap = cap;
500 sw = &sc->sw;
501 sw->hw = hw_cap;
502 sw->info = hw->info;
503 sw->empty = 1;
504 sw->active = hw->enabled;
505 sw->conv = noop_conv;
506 sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
507 sw->vol = nominal_volume;
508 sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
509 if (!sw->rate) {
510 dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
511 g_free (sw);
512 return -1;
514 QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
515 QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
516 #ifdef DEBUG_CAPTURE
517 sw->name = g_strdup_printf ("for %p %d,%d,%d",
518 hw, sw->info.freq, sw->info.bits,
519 sw->info.nchannels);
520 dolog ("Added %s active = %d\n", sw->name, sw->active);
521 #endif
522 if (sw->active) {
523 audio_capture_maybe_changed (cap, 1);
526 return 0;
530 * Hard voice (capture)
532 static size_t audio_pcm_hw_find_min_in (HWVoiceIn *hw)
534 SWVoiceIn *sw;
535 size_t m = hw->total_samples_captured;
537 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
538 if (sw->active) {
539 m = MIN (m, sw->total_hw_samples_acquired);
542 return m;
545 static size_t audio_pcm_hw_get_live_in(HWVoiceIn *hw)
547 size_t live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
548 if (audio_bug(__func__, live > hw->conv_buf->size)) {
549 dolog("live=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
550 return 0;
552 return live;
555 static size_t audio_pcm_hw_conv_in(HWVoiceIn *hw, void *pcm_buf, size_t samples)
557 size_t conv = 0;
558 STSampleBuffer *conv_buf = hw->conv_buf;
560 while (samples) {
561 uint8_t *src = advance(pcm_buf, conv * hw->info.bytes_per_frame);
562 size_t proc = MIN(samples, conv_buf->size - conv_buf->pos);
564 hw->conv(conv_buf->samples + conv_buf->pos, src, proc);
565 conv_buf->pos = (conv_buf->pos + proc) % conv_buf->size;
566 samples -= proc;
567 conv += proc;
570 return conv;
574 * Soft voice (capture)
576 static size_t audio_pcm_sw_read(SWVoiceIn *sw, void *buf, size_t size)
578 HWVoiceIn *hw = sw->hw;
579 size_t samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
580 struct st_sample *src, *dst = sw->buf;
582 live = hw->total_samples_captured - sw->total_hw_samples_acquired;
583 if (!live) {
584 return 0;
586 if (audio_bug(__func__, live > hw->conv_buf->size)) {
587 dolog("live_in=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
588 return 0;
591 rpos = audio_ring_posb(hw->conv_buf->pos, live, hw->conv_buf->size);
593 samples = size / sw->info.bytes_per_frame;
595 swlim = (live * sw->ratio) >> 32;
596 swlim = MIN (swlim, samples);
598 while (swlim) {
599 src = hw->conv_buf->samples + rpos;
600 if (hw->conv_buf->pos > rpos) {
601 isamp = hw->conv_buf->pos - rpos;
602 } else {
603 isamp = hw->conv_buf->size - rpos;
606 if (!isamp) {
607 break;
609 osamp = swlim;
611 st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
612 swlim -= osamp;
613 rpos = (rpos + isamp) % hw->conv_buf->size;
614 dst += osamp;
615 ret += osamp;
616 total += isamp;
619 if (!hw->pcm_ops->volume_in) {
620 mixeng_volume (sw->buf, ret, &sw->vol);
623 sw->clip (buf, sw->buf, ret);
624 sw->total_hw_samples_acquired += total;
625 return ret * sw->info.bytes_per_frame;
629 * Hard voice (playback)
631 static size_t audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
633 SWVoiceOut *sw;
634 size_t m = SIZE_MAX;
635 int nb_live = 0;
637 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
638 if (sw->active || !sw->empty) {
639 m = MIN (m, sw->total_hw_samples_mixed);
640 nb_live += 1;
644 *nb_livep = nb_live;
645 return m;
648 static size_t audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
650 size_t smin;
651 int nb_live1;
653 smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
654 if (nb_live) {
655 *nb_live = nb_live1;
658 if (nb_live1) {
659 size_t live = smin;
661 if (audio_bug(__func__, live > hw->mix_buf->size)) {
662 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
663 return 0;
665 return live;
667 return 0;
670 static size_t audio_pcm_hw_get_free(HWVoiceOut *hw)
672 return (hw->pcm_ops->buffer_get_free ? hw->pcm_ops->buffer_get_free(hw) :
673 INT_MAX) / hw->info.bytes_per_frame;
676 static void audio_pcm_hw_clip_out(HWVoiceOut *hw, void *pcm_buf, size_t len)
678 size_t clipped = 0;
679 size_t pos = hw->mix_buf->pos;
681 while (len) {
682 st_sample *src = hw->mix_buf->samples + pos;
683 uint8_t *dst = advance(pcm_buf, clipped * hw->info.bytes_per_frame);
684 size_t samples_till_end_of_buf = hw->mix_buf->size - pos;
685 size_t samples_to_clip = MIN(len, samples_till_end_of_buf);
687 hw->clip(dst, src, samples_to_clip);
689 pos = (pos + samples_to_clip) % hw->mix_buf->size;
690 len -= samples_to_clip;
691 clipped += samples_to_clip;
696 * Soft voice (playback)
698 static size_t audio_pcm_sw_write(SWVoiceOut *sw, void *buf, size_t size)
700 size_t hwsamples, samples, isamp, osamp, wpos, live, dead, left, blck;
701 size_t hw_free;
702 size_t ret = 0, pos = 0, total = 0;
704 if (!sw) {
705 return size;
708 hwsamples = sw->hw->mix_buf->size;
710 live = sw->total_hw_samples_mixed;
711 if (audio_bug(__func__, live > hwsamples)) {
712 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hwsamples);
713 return 0;
716 if (live == hwsamples) {
717 #ifdef DEBUG_OUT
718 dolog ("%s is full %zu\n", sw->name, live);
719 #endif
720 return 0;
723 wpos = (sw->hw->mix_buf->pos + live) % hwsamples;
725 dead = hwsamples - live;
726 hw_free = audio_pcm_hw_get_free(sw->hw);
727 hw_free = hw_free > live ? hw_free - live : 0;
728 samples = ((int64_t)MIN(dead, hw_free) << 32) / sw->ratio;
729 samples = MIN(samples, size / sw->info.bytes_per_frame);
730 if (samples) {
731 sw->conv(sw->buf, buf, samples);
733 if (!sw->hw->pcm_ops->volume_out) {
734 mixeng_volume(sw->buf, samples, &sw->vol);
738 while (samples) {
739 dead = hwsamples - live;
740 left = hwsamples - wpos;
741 blck = MIN (dead, left);
742 if (!blck) {
743 break;
745 isamp = samples;
746 osamp = blck;
747 st_rate_flow_mix (
748 sw->rate,
749 sw->buf + pos,
750 sw->hw->mix_buf->samples + wpos,
751 &isamp,
752 &osamp
754 ret += isamp;
755 samples -= isamp;
756 pos += isamp;
757 live += osamp;
758 wpos = (wpos + osamp) % hwsamples;
759 total += osamp;
762 sw->total_hw_samples_mixed += total;
763 sw->empty = sw->total_hw_samples_mixed == 0;
765 #ifdef DEBUG_OUT
766 dolog (
767 "%s: write size %zu ret %zu total sw %zu\n",
768 SW_NAME (sw),
769 size / sw->info.bytes_per_frame,
770 ret,
771 sw->total_hw_samples_mixed
773 #endif
775 return ret * sw->info.bytes_per_frame;
778 #ifdef DEBUG_AUDIO
779 static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
781 dolog("%s: bits %d, sign %d, float %d, freq %d, nchan %d\n",
782 cap, info->bits, info->is_signed, info->is_float, info->freq,
783 info->nchannels);
785 #endif
787 #define DAC
788 #include "audio_template.h"
789 #undef DAC
790 #include "audio_template.h"
793 * Timer
795 static int audio_is_timer_needed(AudioState *s)
797 HWVoiceIn *hwi = NULL;
798 HWVoiceOut *hwo = NULL;
800 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
801 if (!hwo->poll_mode) {
802 return 1;
805 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
806 if (!hwi->poll_mode) {
807 return 1;
810 return 0;
813 static void audio_reset_timer (AudioState *s)
815 if (audio_is_timer_needed(s)) {
816 timer_mod_anticipate_ns(s->ts,
817 qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
818 if (!s->timer_running) {
819 s->timer_running = true;
820 s->timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
821 trace_audio_timer_start(s->period_ticks / SCALE_MS);
823 } else {
824 timer_del(s->ts);
825 if (s->timer_running) {
826 s->timer_running = false;
827 trace_audio_timer_stop();
832 static void audio_timer (void *opaque)
834 int64_t now, diff;
835 AudioState *s = opaque;
837 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
838 diff = now - s->timer_last;
839 if (diff > s->period_ticks * 3 / 2) {
840 trace_audio_timer_delayed(diff / SCALE_MS);
842 s->timer_last = now;
844 audio_run(s, "timer");
845 audio_reset_timer(s);
849 * Public API
851 size_t AUD_write(SWVoiceOut *sw, void *buf, size_t size)
853 HWVoiceOut *hw;
855 if (!sw) {
856 /* XXX: Consider options */
857 return size;
859 hw = sw->hw;
861 if (!hw->enabled) {
862 dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
863 return 0;
866 if (audio_get_pdo_out(hw->s->dev)->mixing_engine) {
867 return audio_pcm_sw_write(sw, buf, size);
868 } else {
869 return hw->pcm_ops->write(hw, buf, size);
873 size_t AUD_read(SWVoiceIn *sw, void *buf, size_t size)
875 HWVoiceIn *hw;
877 if (!sw) {
878 /* XXX: Consider options */
879 return size;
881 hw = sw->hw;
883 if (!hw->enabled) {
884 dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
885 return 0;
888 if (audio_get_pdo_in(hw->s->dev)->mixing_engine) {
889 return audio_pcm_sw_read(sw, buf, size);
890 } else {
891 return hw->pcm_ops->read(hw, buf, size);
895 int AUD_get_buffer_size_out(SWVoiceOut *sw)
897 return sw->hw->samples * sw->hw->info.bytes_per_frame;
900 void AUD_set_active_out (SWVoiceOut *sw, int on)
902 HWVoiceOut *hw;
904 if (!sw) {
905 return;
908 hw = sw->hw;
909 if (sw->active != on) {
910 AudioState *s = sw->s;
911 SWVoiceOut *temp_sw;
912 SWVoiceCap *sc;
914 if (on) {
915 hw->pending_disable = 0;
916 if (!hw->enabled) {
917 hw->enabled = 1;
918 if (s->vm_running) {
919 if (hw->pcm_ops->enable_out) {
920 hw->pcm_ops->enable_out(hw, true);
922 audio_reset_timer (s);
925 } else {
926 if (hw->enabled) {
927 int nb_active = 0;
929 for (temp_sw = hw->sw_head.lh_first; temp_sw;
930 temp_sw = temp_sw->entries.le_next) {
931 nb_active += temp_sw->active != 0;
934 hw->pending_disable = nb_active == 1;
938 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
939 sc->sw.active = hw->enabled;
940 if (hw->enabled) {
941 audio_capture_maybe_changed (sc->cap, 1);
944 sw->active = on;
948 void AUD_set_active_in (SWVoiceIn *sw, int on)
950 HWVoiceIn *hw;
952 if (!sw) {
953 return;
956 hw = sw->hw;
957 if (sw->active != on) {
958 AudioState *s = sw->s;
959 SWVoiceIn *temp_sw;
961 if (on) {
962 if (!hw->enabled) {
963 hw->enabled = 1;
964 if (s->vm_running) {
965 if (hw->pcm_ops->enable_in) {
966 hw->pcm_ops->enable_in(hw, true);
968 audio_reset_timer (s);
971 sw->total_hw_samples_acquired = hw->total_samples_captured;
972 } else {
973 if (hw->enabled) {
974 int nb_active = 0;
976 for (temp_sw = hw->sw_head.lh_first; temp_sw;
977 temp_sw = temp_sw->entries.le_next) {
978 nb_active += temp_sw->active != 0;
981 if (nb_active == 1) {
982 hw->enabled = 0;
983 if (hw->pcm_ops->enable_in) {
984 hw->pcm_ops->enable_in(hw, false);
989 sw->active = on;
994 * audio_frontend_frames_in() - returns the number of frames the resampling
995 * code generates from frames_in frames
997 * @sw: audio recording frontend
998 * @frames_in: number of frames
1000 static size_t audio_frontend_frames_in(SWVoiceIn *sw, size_t frames_in)
1002 return (int64_t)frames_in * sw->ratio >> 32;
1005 static size_t audio_get_avail (SWVoiceIn *sw)
1007 size_t live;
1009 if (!sw) {
1010 return 0;
1013 live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
1014 if (audio_bug(__func__, live > sw->hw->conv_buf->size)) {
1015 dolog("live=%zu sw->hw->conv_buf->size=%zu\n", live,
1016 sw->hw->conv_buf->size);
1017 return 0;
1020 ldebug (
1021 "%s: get_avail live %zu frontend frames %zu\n",
1022 SW_NAME (sw),
1023 live, audio_frontend_frames_in(sw, live)
1026 return live;
1030 * audio_frontend_frames_out() - returns the number of frames needed to
1031 * get frames_out frames after resampling
1033 * @sw: audio playback frontend
1034 * @frames_out: number of frames
1036 static size_t audio_frontend_frames_out(SWVoiceOut *sw, size_t frames_out)
1038 return ((int64_t)frames_out << 32) / sw->ratio;
1041 static size_t audio_get_free(SWVoiceOut *sw)
1043 size_t live, dead;
1045 if (!sw) {
1046 return 0;
1049 live = sw->total_hw_samples_mixed;
1051 if (audio_bug(__func__, live > sw->hw->mix_buf->size)) {
1052 dolog("live=%zu sw->hw->mix_buf->size=%zu\n", live,
1053 sw->hw->mix_buf->size);
1054 return 0;
1057 dead = sw->hw->mix_buf->size - live;
1059 #ifdef DEBUG_OUT
1060 dolog("%s: get_free live %zu dead %zu frontend frames %zu\n",
1061 SW_NAME(sw), live, dead, audio_frontend_frames_out(sw, dead));
1062 #endif
1064 return dead;
1067 static void audio_capture_mix_and_clear(HWVoiceOut *hw, size_t rpos,
1068 size_t samples)
1070 size_t n;
1072 if (hw->enabled) {
1073 SWVoiceCap *sc;
1075 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1076 SWVoiceOut *sw = &sc->sw;
1077 int rpos2 = rpos;
1079 n = samples;
1080 while (n) {
1081 size_t till_end_of_hw = hw->mix_buf->size - rpos2;
1082 size_t to_write = MIN(till_end_of_hw, n);
1083 size_t bytes = to_write * hw->info.bytes_per_frame;
1084 size_t written;
1086 sw->buf = hw->mix_buf->samples + rpos2;
1087 written = audio_pcm_sw_write (sw, NULL, bytes);
1088 if (written - bytes) {
1089 dolog("Could not mix %zu bytes into a capture "
1090 "buffer, mixed %zu\n",
1091 bytes, written);
1092 break;
1094 n -= to_write;
1095 rpos2 = (rpos2 + to_write) % hw->mix_buf->size;
1100 n = MIN(samples, hw->mix_buf->size - rpos);
1101 mixeng_clear(hw->mix_buf->samples + rpos, n);
1102 mixeng_clear(hw->mix_buf->samples, samples - n);
1105 static size_t audio_pcm_hw_run_out(HWVoiceOut *hw, size_t live)
1107 size_t clipped = 0;
1109 while (live) {
1110 size_t size = live * hw->info.bytes_per_frame;
1111 size_t decr, proc;
1112 void *buf = hw->pcm_ops->get_buffer_out(hw, &size);
1114 if (size == 0) {
1115 break;
1118 decr = MIN(size / hw->info.bytes_per_frame, live);
1119 if (buf) {
1120 audio_pcm_hw_clip_out(hw, buf, decr);
1122 proc = hw->pcm_ops->put_buffer_out(hw, buf,
1123 decr * hw->info.bytes_per_frame) /
1124 hw->info.bytes_per_frame;
1126 live -= proc;
1127 clipped += proc;
1128 hw->mix_buf->pos = (hw->mix_buf->pos + proc) % hw->mix_buf->size;
1130 if (proc == 0 || proc < decr) {
1131 break;
1135 if (hw->pcm_ops->run_buffer_out) {
1136 hw->pcm_ops->run_buffer_out(hw);
1139 return clipped;
1142 static void audio_run_out (AudioState *s)
1144 HWVoiceOut *hw = NULL;
1145 SWVoiceOut *sw;
1147 while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1148 size_t played, live, prev_rpos;
1149 size_t hw_free = audio_pcm_hw_get_free(hw);
1150 int nb_live;
1152 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1153 /* there is exactly 1 sw for each hw with no mixeng */
1154 sw = hw->sw_head.lh_first;
1156 if (hw->pending_disable) {
1157 hw->enabled = 0;
1158 hw->pending_disable = 0;
1159 if (hw->pcm_ops->enable_out) {
1160 hw->pcm_ops->enable_out(hw, false);
1164 if (sw->active) {
1165 sw->callback.fn(sw->callback.opaque,
1166 hw_free * sw->info.bytes_per_frame);
1169 if (hw->pcm_ops->run_buffer_out) {
1170 hw->pcm_ops->run_buffer_out(hw);
1173 continue;
1176 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1177 if (sw->active) {
1178 size_t sw_free = audio_get_free(sw);
1179 size_t free;
1181 if (hw_free > sw->total_hw_samples_mixed) {
1182 free = audio_frontend_frames_out(sw,
1183 MIN(sw_free, hw_free - sw->total_hw_samples_mixed));
1184 } else {
1185 free = 0;
1187 if (free > 0) {
1188 sw->callback.fn(sw->callback.opaque,
1189 free * sw->info.bytes_per_frame);
1194 live = audio_pcm_hw_get_live_out (hw, &nb_live);
1195 if (!nb_live) {
1196 live = 0;
1199 if (audio_bug(__func__, live > hw->mix_buf->size)) {
1200 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
1201 continue;
1204 if (hw->pending_disable && !nb_live) {
1205 SWVoiceCap *sc;
1206 #ifdef DEBUG_OUT
1207 dolog ("Disabling voice\n");
1208 #endif
1209 hw->enabled = 0;
1210 hw->pending_disable = 0;
1211 if (hw->pcm_ops->enable_out) {
1212 hw->pcm_ops->enable_out(hw, false);
1214 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1215 sc->sw.active = 0;
1216 audio_recalc_and_notify_capture (sc->cap);
1218 continue;
1221 if (!live) {
1222 if (hw->pcm_ops->run_buffer_out) {
1223 hw->pcm_ops->run_buffer_out(hw);
1225 continue;
1228 prev_rpos = hw->mix_buf->pos;
1229 played = audio_pcm_hw_run_out(hw, live);
1230 replay_audio_out(&played);
1231 if (audio_bug(__func__, hw->mix_buf->pos >= hw->mix_buf->size)) {
1232 dolog("hw->mix_buf->pos=%zu hw->mix_buf->size=%zu played=%zu\n",
1233 hw->mix_buf->pos, hw->mix_buf->size, played);
1234 hw->mix_buf->pos = 0;
1237 #ifdef DEBUG_OUT
1238 dolog("played=%zu\n", played);
1239 #endif
1241 if (played) {
1242 hw->ts_helper += played;
1243 audio_capture_mix_and_clear (hw, prev_rpos, played);
1246 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1247 if (!sw->active && sw->empty) {
1248 continue;
1251 if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1252 dolog("played=%zu sw->total_hw_samples_mixed=%zu\n",
1253 played, sw->total_hw_samples_mixed);
1254 played = sw->total_hw_samples_mixed;
1257 sw->total_hw_samples_mixed -= played;
1259 if (!sw->total_hw_samples_mixed) {
1260 sw->empty = 1;
1266 static size_t audio_pcm_hw_run_in(HWVoiceIn *hw, size_t samples)
1268 size_t conv = 0;
1270 if (hw->pcm_ops->run_buffer_in) {
1271 hw->pcm_ops->run_buffer_in(hw);
1274 while (samples) {
1275 size_t proc;
1276 size_t size = samples * hw->info.bytes_per_frame;
1277 void *buf = hw->pcm_ops->get_buffer_in(hw, &size);
1279 assert(size % hw->info.bytes_per_frame == 0);
1280 if (size == 0) {
1281 break;
1284 proc = audio_pcm_hw_conv_in(hw, buf, size / hw->info.bytes_per_frame);
1286 samples -= proc;
1287 conv += proc;
1288 hw->pcm_ops->put_buffer_in(hw, buf, proc * hw->info.bytes_per_frame);
1291 return conv;
1294 static void audio_run_in (AudioState *s)
1296 HWVoiceIn *hw = NULL;
1298 if (!audio_get_pdo_in(s->dev)->mixing_engine) {
1299 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1300 /* there is exactly 1 sw for each hw with no mixeng */
1301 SWVoiceIn *sw = hw->sw_head.lh_first;
1302 if (sw->active) {
1303 sw->callback.fn(sw->callback.opaque, INT_MAX);
1306 return;
1309 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1310 SWVoiceIn *sw;
1311 size_t captured = 0, min;
1313 if (replay_mode != REPLAY_MODE_PLAY) {
1314 captured = audio_pcm_hw_run_in(
1315 hw, hw->conv_buf->size - audio_pcm_hw_get_live_in(hw));
1317 replay_audio_in(&captured, hw->conv_buf->samples, &hw->conv_buf->pos,
1318 hw->conv_buf->size);
1320 min = audio_pcm_hw_find_min_in (hw);
1321 hw->total_samples_captured += captured - min;
1322 hw->ts_helper += captured;
1324 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1325 sw->total_hw_samples_acquired -= min;
1327 if (sw->active) {
1328 size_t sw_avail = audio_get_avail(sw);
1329 size_t avail;
1331 avail = audio_frontend_frames_in(sw, sw_avail);
1332 if (avail > 0) {
1333 sw->callback.fn(sw->callback.opaque,
1334 avail * sw->info.bytes_per_frame);
1341 static void audio_run_capture (AudioState *s)
1343 CaptureVoiceOut *cap;
1345 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1346 size_t live, rpos, captured;
1347 HWVoiceOut *hw = &cap->hw;
1348 SWVoiceOut *sw;
1350 captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1351 rpos = hw->mix_buf->pos;
1352 while (live) {
1353 size_t left = hw->mix_buf->size - rpos;
1354 size_t to_capture = MIN(live, left);
1355 struct st_sample *src;
1356 struct capture_callback *cb;
1358 src = hw->mix_buf->samples + rpos;
1359 hw->clip (cap->buf, src, to_capture);
1360 mixeng_clear (src, to_capture);
1362 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1363 cb->ops.capture (cb->opaque, cap->buf,
1364 to_capture * hw->info.bytes_per_frame);
1366 rpos = (rpos + to_capture) % hw->mix_buf->size;
1367 live -= to_capture;
1369 hw->mix_buf->pos = rpos;
1371 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1372 if (!sw->active && sw->empty) {
1373 continue;
1376 if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1377 dolog("captured=%zu sw->total_hw_samples_mixed=%zu\n",
1378 captured, sw->total_hw_samples_mixed);
1379 captured = sw->total_hw_samples_mixed;
1382 sw->total_hw_samples_mixed -= captured;
1383 sw->empty = sw->total_hw_samples_mixed == 0;
1388 void audio_run(AudioState *s, const char *msg)
1390 audio_run_out(s);
1391 audio_run_in(s);
1392 audio_run_capture(s);
1394 #ifdef DEBUG_POLL
1396 static double prevtime;
1397 double currtime;
1398 struct timeval tv;
1400 if (gettimeofday (&tv, NULL)) {
1401 perror ("audio_run: gettimeofday");
1402 return;
1405 currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1406 dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1407 prevtime = currtime;
1409 #endif
1412 void audio_generic_run_buffer_in(HWVoiceIn *hw)
1414 if (unlikely(!hw->buf_emul)) {
1415 hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1416 hw->buf_emul = g_malloc(hw->size_emul);
1417 hw->pos_emul = hw->pending_emul = 0;
1420 while (hw->pending_emul < hw->size_emul) {
1421 size_t read_len = MIN(hw->size_emul - hw->pos_emul,
1422 hw->size_emul - hw->pending_emul);
1423 size_t read = hw->pcm_ops->read(hw, hw->buf_emul + hw->pos_emul,
1424 read_len);
1425 hw->pending_emul += read;
1426 hw->pos_emul = (hw->pos_emul + read) % hw->size_emul;
1427 if (read < read_len) {
1428 break;
1433 void *audio_generic_get_buffer_in(HWVoiceIn *hw, size_t *size)
1435 size_t start;
1437 start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1438 assert(start < hw->size_emul);
1440 *size = MIN(*size, hw->pending_emul);
1441 *size = MIN(*size, hw->size_emul - start);
1442 return hw->buf_emul + start;
1445 void audio_generic_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
1447 assert(size <= hw->pending_emul);
1448 hw->pending_emul -= size;
1451 size_t audio_generic_buffer_get_free(HWVoiceOut *hw)
1453 if (hw->buf_emul) {
1454 return hw->size_emul - hw->pending_emul;
1455 } else {
1456 return hw->samples * hw->info.bytes_per_frame;
1460 void audio_generic_run_buffer_out(HWVoiceOut *hw)
1462 while (hw->pending_emul) {
1463 size_t write_len, written, start;
1465 start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1466 assert(start < hw->size_emul);
1468 write_len = MIN(hw->pending_emul, hw->size_emul - start);
1470 written = hw->pcm_ops->write(hw, hw->buf_emul + start, write_len);
1471 hw->pending_emul -= written;
1473 if (written < write_len) {
1474 break;
1479 void *audio_generic_get_buffer_out(HWVoiceOut *hw, size_t *size)
1481 if (unlikely(!hw->buf_emul)) {
1482 hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1483 hw->buf_emul = g_malloc(hw->size_emul);
1484 hw->pos_emul = hw->pending_emul = 0;
1487 *size = MIN(hw->size_emul - hw->pending_emul,
1488 hw->size_emul - hw->pos_emul);
1489 return hw->buf_emul + hw->pos_emul;
1492 size_t audio_generic_put_buffer_out(HWVoiceOut *hw, void *buf, size_t size)
1494 assert(buf == hw->buf_emul + hw->pos_emul &&
1495 size + hw->pending_emul <= hw->size_emul);
1497 hw->pending_emul += size;
1498 hw->pos_emul = (hw->pos_emul + size) % hw->size_emul;
1500 return size;
1503 size_t audio_generic_write(HWVoiceOut *hw, void *buf, size_t size)
1505 size_t total = 0;
1507 if (hw->pcm_ops->buffer_get_free) {
1508 size_t free = hw->pcm_ops->buffer_get_free(hw);
1510 size = MIN(size, free);
1513 while (total < size) {
1514 size_t dst_size = size - total;
1515 size_t copy_size, proc;
1516 void *dst = hw->pcm_ops->get_buffer_out(hw, &dst_size);
1518 if (dst_size == 0) {
1519 break;
1522 copy_size = MIN(size - total, dst_size);
1523 if (dst) {
1524 memcpy(dst, (char *)buf + total, copy_size);
1526 proc = hw->pcm_ops->put_buffer_out(hw, dst, copy_size);
1527 total += proc;
1529 if (proc == 0 || proc < copy_size) {
1530 break;
1534 return total;
1537 size_t audio_generic_read(HWVoiceIn *hw, void *buf, size_t size)
1539 size_t total = 0;
1541 if (hw->pcm_ops->run_buffer_in) {
1542 hw->pcm_ops->run_buffer_in(hw);
1545 while (total < size) {
1546 size_t src_size = size - total;
1547 void *src = hw->pcm_ops->get_buffer_in(hw, &src_size);
1549 if (src_size == 0) {
1550 break;
1553 memcpy((char *)buf + total, src, src_size);
1554 hw->pcm_ops->put_buffer_in(hw, src, src_size);
1555 total += src_size;
1558 return total;
1561 static int audio_driver_init(AudioState *s, struct audio_driver *drv,
1562 bool msg, Audiodev *dev)
1564 s->drv_opaque = drv->init(dev);
1566 if (s->drv_opaque) {
1567 if (!drv->pcm_ops->get_buffer_in) {
1568 drv->pcm_ops->get_buffer_in = audio_generic_get_buffer_in;
1569 drv->pcm_ops->put_buffer_in = audio_generic_put_buffer_in;
1571 if (!drv->pcm_ops->get_buffer_out) {
1572 drv->pcm_ops->get_buffer_out = audio_generic_get_buffer_out;
1573 drv->pcm_ops->put_buffer_out = audio_generic_put_buffer_out;
1576 audio_init_nb_voices_out(s, drv);
1577 audio_init_nb_voices_in(s, drv);
1578 s->drv = drv;
1579 return 0;
1580 } else {
1581 if (msg) {
1582 dolog("Could not init `%s' audio driver\n", drv->name);
1584 return -1;
1588 static void audio_vm_change_state_handler (void *opaque, bool running,
1589 RunState state)
1591 AudioState *s = opaque;
1592 HWVoiceOut *hwo = NULL;
1593 HWVoiceIn *hwi = NULL;
1595 s->vm_running = running;
1596 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
1597 if (hwo->pcm_ops->enable_out) {
1598 hwo->pcm_ops->enable_out(hwo, running);
1602 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
1603 if (hwi->pcm_ops->enable_in) {
1604 hwi->pcm_ops->enable_in(hwi, running);
1607 audio_reset_timer (s);
1610 static void free_audio_state(AudioState *s)
1612 HWVoiceOut *hwo, *hwon;
1613 HWVoiceIn *hwi, *hwin;
1615 QLIST_FOREACH_SAFE(hwo, &s->hw_head_out, entries, hwon) {
1616 SWVoiceCap *sc;
1618 if (hwo->enabled && hwo->pcm_ops->enable_out) {
1619 hwo->pcm_ops->enable_out(hwo, false);
1621 hwo->pcm_ops->fini_out (hwo);
1623 for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1624 CaptureVoiceOut *cap = sc->cap;
1625 struct capture_callback *cb;
1627 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1628 cb->ops.destroy (cb->opaque);
1631 QLIST_REMOVE(hwo, entries);
1634 QLIST_FOREACH_SAFE(hwi, &s->hw_head_in, entries, hwin) {
1635 if (hwi->enabled && hwi->pcm_ops->enable_in) {
1636 hwi->pcm_ops->enable_in(hwi, false);
1638 hwi->pcm_ops->fini_in (hwi);
1639 QLIST_REMOVE(hwi, entries);
1642 if (s->drv) {
1643 s->drv->fini (s->drv_opaque);
1644 s->drv = NULL;
1647 if (s->dev) {
1648 qapi_free_Audiodev(s->dev);
1649 s->dev = NULL;
1652 if (s->ts) {
1653 timer_free(s->ts);
1654 s->ts = NULL;
1657 g_free(s);
1660 void audio_cleanup(void)
1662 while (!QTAILQ_EMPTY(&audio_states)) {
1663 AudioState *s = QTAILQ_FIRST(&audio_states);
1664 QTAILQ_REMOVE(&audio_states, s, list);
1665 free_audio_state(s);
1669 static bool vmstate_audio_needed(void *opaque)
1672 * Never needed, this vmstate only exists in case
1673 * an old qemu sends it to us.
1675 return false;
1678 static const VMStateDescription vmstate_audio = {
1679 .name = "audio",
1680 .version_id = 1,
1681 .minimum_version_id = 1,
1682 .needed = vmstate_audio_needed,
1683 .fields = (VMStateField[]) {
1684 VMSTATE_END_OF_LIST()
1688 static void audio_validate_opts(Audiodev *dev, Error **errp);
1690 static AudiodevListEntry *audiodev_find(
1691 AudiodevListHead *head, const char *drvname)
1693 AudiodevListEntry *e;
1694 QSIMPLEQ_FOREACH(e, head, next) {
1695 if (strcmp(AudiodevDriver_str(e->dev->driver), drvname) == 0) {
1696 return e;
1700 return NULL;
1704 * if we have dev, this function was called because of an -audiodev argument =>
1705 * initialize a new state with it
1706 * if dev == NULL => legacy implicit initialization, return the already created
1707 * state or create a new one
1709 static AudioState *audio_init(Audiodev *dev, const char *name)
1711 static bool atexit_registered;
1712 size_t i;
1713 int done = 0;
1714 const char *drvname = NULL;
1715 VMChangeStateEntry *e;
1716 AudioState *s;
1717 struct audio_driver *driver;
1718 /* silence gcc warning about uninitialized variable */
1719 AudiodevListHead head = QSIMPLEQ_HEAD_INITIALIZER(head);
1721 if (using_spice) {
1723 * When using spice allow the spice audio driver being picked
1724 * as default.
1726 * Temporary hack. Using audio devices without explicit
1727 * audiodev= property is already deprecated. Same goes for
1728 * the -soundhw switch. Once this support gets finally
1729 * removed we can also drop the concept of a default audio
1730 * backend and this can go away.
1732 driver = audio_driver_lookup("spice");
1733 if (driver) {
1734 driver->can_be_default = 1;
1738 if (dev) {
1739 /* -audiodev option */
1740 legacy_config = false;
1741 drvname = AudiodevDriver_str(dev->driver);
1742 } else if (!QTAILQ_EMPTY(&audio_states)) {
1743 if (!legacy_config) {
1744 dolog("Device %s: audiodev default parameter is deprecated, please "
1745 "specify audiodev=%s\n", name,
1746 QTAILQ_FIRST(&audio_states)->dev->id);
1748 return QTAILQ_FIRST(&audio_states);
1749 } else {
1750 /* legacy implicit initialization */
1751 head = audio_handle_legacy_opts();
1753 * In case of legacy initialization, all Audiodevs in the list will have
1754 * the same configuration (except the driver), so it doesn't matter which
1755 * one we chose. We need an Audiodev to set up AudioState before we can
1756 * init a driver. Also note that dev at this point is still in the
1757 * list.
1759 dev = QSIMPLEQ_FIRST(&head)->dev;
1760 audio_validate_opts(dev, &error_abort);
1763 s = g_new0(AudioState, 1);
1764 s->dev = dev;
1766 QLIST_INIT (&s->hw_head_out);
1767 QLIST_INIT (&s->hw_head_in);
1768 QLIST_INIT (&s->cap_head);
1769 if (!atexit_registered) {
1770 atexit(audio_cleanup);
1771 atexit_registered = true;
1774 s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1776 s->nb_hw_voices_out = audio_get_pdo_out(dev)->voices;
1777 s->nb_hw_voices_in = audio_get_pdo_in(dev)->voices;
1779 if (s->nb_hw_voices_out < 1) {
1780 dolog ("Bogus number of playback voices %d, setting to 1\n",
1781 s->nb_hw_voices_out);
1782 s->nb_hw_voices_out = 1;
1785 if (s->nb_hw_voices_in < 0) {
1786 dolog ("Bogus number of capture voices %d, setting to 0\n",
1787 s->nb_hw_voices_in);
1788 s->nb_hw_voices_in = 0;
1791 if (drvname) {
1792 driver = audio_driver_lookup(drvname);
1793 if (driver) {
1794 done = !audio_driver_init(s, driver, true, dev);
1795 } else {
1796 dolog ("Unknown audio driver `%s'\n", drvname);
1798 if (!done) {
1799 free_audio_state(s);
1800 return NULL;
1802 } else {
1803 for (i = 0; audio_prio_list[i]; i++) {
1804 AudiodevListEntry *e = audiodev_find(&head, audio_prio_list[i]);
1805 driver = audio_driver_lookup(audio_prio_list[i]);
1807 if (e && driver) {
1808 s->dev = dev = e->dev;
1809 audio_validate_opts(dev, &error_abort);
1810 done = !audio_driver_init(s, driver, false, dev);
1811 if (done) {
1812 e->dev = NULL;
1813 break;
1818 audio_free_audiodev_list(&head);
1820 if (!done) {
1821 driver = audio_driver_lookup("none");
1822 done = !audio_driver_init(s, driver, false, dev);
1823 assert(done);
1824 dolog("warning: Using timer based audio emulation\n");
1827 if (dev->timer_period <= 0) {
1828 s->period_ticks = 1;
1829 } else {
1830 s->period_ticks = dev->timer_period * (int64_t)SCALE_US;
1833 e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1834 if (!e) {
1835 dolog ("warning: Could not register change state handler\n"
1836 "(Audio can continue looping even after stopping the VM)\n");
1839 QTAILQ_INSERT_TAIL(&audio_states, s, list);
1840 QLIST_INIT (&s->card_head);
1841 vmstate_register (NULL, 0, &vmstate_audio, s);
1842 return s;
1845 void audio_free_audiodev_list(AudiodevListHead *head)
1847 AudiodevListEntry *e;
1848 while ((e = QSIMPLEQ_FIRST(head))) {
1849 QSIMPLEQ_REMOVE_HEAD(head, next);
1850 qapi_free_Audiodev(e->dev);
1851 g_free(e);
1855 void AUD_register_card (const char *name, QEMUSoundCard *card)
1857 if (!card->state) {
1858 card->state = audio_init(NULL, name);
1861 card->name = g_strdup (name);
1862 memset (&card->entries, 0, sizeof (card->entries));
1863 QLIST_INSERT_HEAD(&card->state->card_head, card, entries);
1866 void AUD_remove_card (QEMUSoundCard *card)
1868 QLIST_REMOVE (card, entries);
1869 g_free (card->name);
1872 static struct audio_pcm_ops capture_pcm_ops;
1874 CaptureVoiceOut *AUD_add_capture(
1875 AudioState *s,
1876 struct audsettings *as,
1877 struct audio_capture_ops *ops,
1878 void *cb_opaque
1881 CaptureVoiceOut *cap;
1882 struct capture_callback *cb;
1884 if (!s) {
1885 if (!legacy_config) {
1886 dolog("Capturing without setting an audiodev is deprecated\n");
1888 s = audio_init(NULL, NULL);
1891 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1892 dolog("Can't capture with mixeng disabled\n");
1893 return NULL;
1896 if (audio_validate_settings (as)) {
1897 dolog ("Invalid settings were passed when trying to add capture\n");
1898 audio_print_settings (as);
1899 return NULL;
1902 cb = g_malloc0(sizeof(*cb));
1903 cb->ops = *ops;
1904 cb->opaque = cb_opaque;
1906 cap = audio_pcm_capture_find_specific(s, as);
1907 if (cap) {
1908 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1909 return cap;
1910 } else {
1911 HWVoiceOut *hw;
1912 CaptureVoiceOut *cap;
1914 cap = g_malloc0(sizeof(*cap));
1916 hw = &cap->hw;
1917 hw->s = s;
1918 hw->pcm_ops = &capture_pcm_ops;
1919 QLIST_INIT (&hw->sw_head);
1920 QLIST_INIT (&cap->cb_head);
1922 /* XXX find a more elegant way */
1923 hw->samples = 4096 * 4;
1924 audio_pcm_hw_alloc_resources_out(hw);
1926 audio_pcm_init_info (&hw->info, as);
1928 cap->buf = g_malloc0_n(hw->mix_buf->size, hw->info.bytes_per_frame);
1930 if (hw->info.is_float) {
1931 hw->clip = mixeng_clip_float[hw->info.nchannels == 2];
1932 } else {
1933 hw->clip = mixeng_clip
1934 [hw->info.nchannels == 2]
1935 [hw->info.is_signed]
1936 [hw->info.swap_endianness]
1937 [audio_bits_to_index(hw->info.bits)];
1940 QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1941 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1943 QLIST_FOREACH(hw, &s->hw_head_out, entries) {
1944 audio_attach_capture (hw);
1946 return cap;
1950 void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1952 struct capture_callback *cb;
1954 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1955 if (cb->opaque == cb_opaque) {
1956 cb->ops.destroy (cb_opaque);
1957 QLIST_REMOVE (cb, entries);
1958 g_free (cb);
1960 if (!cap->cb_head.lh_first) {
1961 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
1963 while (sw) {
1964 SWVoiceCap *sc = (SWVoiceCap *) sw;
1965 #ifdef DEBUG_CAPTURE
1966 dolog ("freeing %s\n", sw->name);
1967 #endif
1969 sw1 = sw->entries.le_next;
1970 if (sw->rate) {
1971 st_rate_stop (sw->rate);
1972 sw->rate = NULL;
1974 QLIST_REMOVE (sw, entries);
1975 QLIST_REMOVE (sc, entries);
1976 g_free (sc);
1977 sw = sw1;
1979 QLIST_REMOVE (cap, entries);
1980 g_free (cap->hw.mix_buf);
1981 g_free (cap->buf);
1982 g_free (cap);
1984 return;
1989 void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
1991 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1992 audio_set_volume_out(sw, &vol);
1995 void audio_set_volume_out(SWVoiceOut *sw, Volume *vol)
1997 if (sw) {
1998 HWVoiceOut *hw = sw->hw;
2000 sw->vol.mute = vol->mute;
2001 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
2002 sw->vol.r = nominal_volume.l * vol->vol[vol->channels > 1 ? 1 : 0] /
2003 255;
2005 if (hw->pcm_ops->volume_out) {
2006 hw->pcm_ops->volume_out(hw, vol);
2011 void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
2013 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
2014 audio_set_volume_in(sw, &vol);
2017 void audio_set_volume_in(SWVoiceIn *sw, Volume *vol)
2019 if (sw) {
2020 HWVoiceIn *hw = sw->hw;
2022 sw->vol.mute = vol->mute;
2023 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
2024 sw->vol.r = nominal_volume.r * vol->vol[vol->channels > 1 ? 1 : 0] /
2025 255;
2027 if (hw->pcm_ops->volume_in) {
2028 hw->pcm_ops->volume_in(hw, vol);
2033 void audio_create_pdos(Audiodev *dev)
2035 switch (dev->driver) {
2036 #define CASE(DRIVER, driver, pdo_name) \
2037 case AUDIODEV_DRIVER_##DRIVER: \
2038 if (!dev->u.driver.in) { \
2039 dev->u.driver.in = g_malloc0( \
2040 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
2042 if (!dev->u.driver.out) { \
2043 dev->u.driver.out = g_malloc0( \
2044 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
2046 break
2048 CASE(NONE, none, );
2049 CASE(ALSA, alsa, Alsa);
2050 CASE(COREAUDIO, coreaudio, Coreaudio);
2051 CASE(DBUS, dbus, );
2052 CASE(DSOUND, dsound, );
2053 CASE(JACK, jack, Jack);
2054 CASE(OSS, oss, Oss);
2055 CASE(PA, pa, Pa);
2056 CASE(SDL, sdl, Sdl);
2057 CASE(SNDIO, sndio, );
2058 CASE(SPICE, spice, );
2059 CASE(WAV, wav, );
2061 case AUDIODEV_DRIVER__MAX:
2062 abort();
2066 static void audio_validate_per_direction_opts(
2067 AudiodevPerDirectionOptions *pdo, Error **errp)
2069 if (!pdo->has_mixing_engine) {
2070 pdo->has_mixing_engine = true;
2071 pdo->mixing_engine = true;
2073 if (!pdo->has_fixed_settings) {
2074 pdo->has_fixed_settings = true;
2075 pdo->fixed_settings = pdo->mixing_engine;
2077 if (!pdo->fixed_settings &&
2078 (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
2079 error_setg(errp,
2080 "You can't use frequency, channels or format with fixed-settings=off");
2081 return;
2083 if (!pdo->mixing_engine && pdo->fixed_settings) {
2084 error_setg(errp, "You can't use fixed-settings without mixeng");
2085 return;
2088 if (!pdo->has_frequency) {
2089 pdo->has_frequency = true;
2090 pdo->frequency = 44100;
2092 if (!pdo->has_channels) {
2093 pdo->has_channels = true;
2094 pdo->channels = 2;
2096 if (!pdo->has_voices) {
2097 pdo->has_voices = true;
2098 pdo->voices = pdo->mixing_engine ? 1 : INT_MAX;
2100 if (!pdo->has_format) {
2101 pdo->has_format = true;
2102 pdo->format = AUDIO_FORMAT_S16;
2106 static void audio_validate_opts(Audiodev *dev, Error **errp)
2108 Error *err = NULL;
2110 audio_create_pdos(dev);
2112 audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
2113 if (err) {
2114 error_propagate(errp, err);
2115 return;
2118 audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
2119 if (err) {
2120 error_propagate(errp, err);
2121 return;
2124 if (!dev->has_timer_period) {
2125 dev->has_timer_period = true;
2126 dev->timer_period = 10000; /* 100Hz -> 10ms */
2130 void audio_help(void)
2132 int i;
2134 printf("Available audio drivers:\n");
2136 for (i = 0; i < AUDIODEV_DRIVER__MAX; i++) {
2137 audio_driver *driver = audio_driver_lookup(AudiodevDriver_str(i));
2138 if (driver) {
2139 printf("%s\n", driver->name);
2144 void audio_parse_option(const char *opt)
2146 Audiodev *dev = NULL;
2148 if (is_help_option(opt)) {
2149 audio_help();
2150 exit(EXIT_SUCCESS);
2152 Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
2153 visit_type_Audiodev(v, NULL, &dev, &error_fatal);
2154 visit_free(v);
2156 audio_define(dev);
2159 void audio_define(Audiodev *dev)
2161 AudiodevListEntry *e;
2163 audio_validate_opts(dev, &error_fatal);
2165 e = g_new0(AudiodevListEntry, 1);
2166 e->dev = dev;
2167 QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
2170 bool audio_init_audiodevs(void)
2172 AudiodevListEntry *e;
2174 QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2175 if (!audio_init(e->dev, NULL)) {
2176 return false;
2180 return true;
2183 audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
2185 return (audsettings) {
2186 .freq = pdo->frequency,
2187 .nchannels = pdo->channels,
2188 .fmt = pdo->format,
2189 .endianness = AUDIO_HOST_ENDIANNESS,
2193 int audioformat_bytes_per_sample(AudioFormat fmt)
2195 switch (fmt) {
2196 case AUDIO_FORMAT_U8:
2197 case AUDIO_FORMAT_S8:
2198 return 1;
2200 case AUDIO_FORMAT_U16:
2201 case AUDIO_FORMAT_S16:
2202 return 2;
2204 case AUDIO_FORMAT_U32:
2205 case AUDIO_FORMAT_S32:
2206 case AUDIO_FORMAT_F32:
2207 return 4;
2209 case AUDIO_FORMAT__MAX:
2212 abort();
2216 /* frames = freq * usec / 1e6 */
2217 int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
2218 audsettings *as, int def_usecs)
2220 uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
2221 return (as->freq * usecs + 500000) / 1000000;
2224 /* samples = channels * frames = channels * freq * usec / 1e6 */
2225 int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
2226 audsettings *as, int def_usecs)
2228 return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
2232 * bytes = bytes_per_sample * samples =
2233 * bytes_per_sample * channels * freq * usec / 1e6
2235 int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
2236 audsettings *as, int def_usecs)
2238 return audio_buffer_samples(pdo, as, def_usecs) *
2239 audioformat_bytes_per_sample(as->fmt);
2242 AudioState *audio_state_by_name(const char *name)
2244 AudioState *s;
2245 QTAILQ_FOREACH(s, &audio_states, list) {
2246 assert(s->dev);
2247 if (strcmp(name, s->dev->id) == 0) {
2248 return s;
2251 return NULL;
2254 const char *audio_get_id(QEMUSoundCard *card)
2256 if (card->state) {
2257 assert(card->state->dev);
2258 return card->state->dev->id;
2259 } else {
2260 return "";
2264 const char *audio_application_name(void)
2266 const char *vm_name;
2268 vm_name = qemu_get_vm_name();
2269 return vm_name ? vm_name : "qemu";
2272 void audio_rate_start(RateCtl *rate)
2274 memset(rate, 0, sizeof(RateCtl));
2275 rate->start_ticks = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2278 size_t audio_rate_peek_bytes(RateCtl *rate, struct audio_pcm_info *info)
2280 int64_t now;
2281 int64_t ticks;
2282 int64_t bytes;
2283 int64_t frames;
2285 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2286 ticks = now - rate->start_ticks;
2287 bytes = muldiv64(ticks, info->bytes_per_second, NANOSECONDS_PER_SECOND);
2288 frames = (bytes - rate->bytes_sent) / info->bytes_per_frame;
2289 if (frames < 0 || frames > 65536) {
2290 AUD_log(NULL, "Resetting rate control (%" PRId64 " frames)\n", frames);
2291 audio_rate_start(rate);
2292 frames = 0;
2295 return frames * info->bytes_per_frame;
2298 void audio_rate_add_bytes(RateCtl *rate, size_t bytes_used)
2300 rate->bytes_sent += bytes_used;
2303 size_t audio_rate_get_bytes(RateCtl *rate, struct audio_pcm_info *info,
2304 size_t bytes_avail)
2306 size_t bytes;
2308 bytes = audio_rate_peek_bytes(rate, info);
2309 bytes = MIN(bytes, bytes_avail);
2310 audio_rate_add_bytes(rate, bytes);
2312 return bytes;