Revert "migration: Properly destroy variables on incoming side"
[qemu/kevin.git] / audio / audio.c
blob46578e4a583b9ad5c5fd4d40c7114697113a2323
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 "sysemu/replay.h"
36 #include "sysemu/runstate.h"
37 #include "ui/qemu-spice.h"
38 #include "trace.h"
40 #define AUDIO_CAP "audio"
41 #include "audio_int.h"
43 /* #define DEBUG_LIVE */
44 /* #define DEBUG_OUT */
45 /* #define DEBUG_CAPTURE */
46 /* #define DEBUG_POLL */
48 #define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
51 /* Order of CONFIG_AUDIO_DRIVERS is import.
52 The 1st one is the one used by default, that is the reason
53 that we generate the list.
55 const char *audio_prio_list[] = {
56 "spice",
57 CONFIG_AUDIO_DRIVERS
58 "none",
59 "wav",
60 NULL
63 static QLIST_HEAD(, audio_driver) audio_drivers;
64 static AudiodevListHead audiodevs = QSIMPLEQ_HEAD_INITIALIZER(audiodevs);
66 void audio_driver_register(audio_driver *drv)
68 QLIST_INSERT_HEAD(&audio_drivers, drv, next);
71 audio_driver *audio_driver_lookup(const char *name)
73 struct audio_driver *d;
75 QLIST_FOREACH(d, &audio_drivers, next) {
76 if (strcmp(name, d->name) == 0) {
77 return d;
81 audio_module_load_one(name);
82 QLIST_FOREACH(d, &audio_drivers, next) {
83 if (strcmp(name, d->name) == 0) {
84 return d;
88 return NULL;
91 static QTAILQ_HEAD(AudioStateHead, AudioState) audio_states =
92 QTAILQ_HEAD_INITIALIZER(audio_states);
94 const struct mixeng_volume nominal_volume = {
95 .mute = 0,
96 #ifdef FLOAT_MIXENG
97 .r = 1.0,
98 .l = 1.0,
99 #else
100 .r = 1ULL << 32,
101 .l = 1ULL << 32,
102 #endif
105 static bool legacy_config = true;
107 #ifdef AUDIO_IS_FLAWLESS_AND_NO_CHECKS_ARE_REQURIED
108 #error No its not
109 #else
110 int audio_bug (const char *funcname, int cond)
112 if (cond) {
113 static int shown;
115 AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
116 if (!shown) {
117 shown = 1;
118 AUD_log (NULL, "Save all your work and restart without audio\n");
119 AUD_log (NULL, "I am sorry\n");
121 AUD_log (NULL, "Context:\n");
123 #if defined AUDIO_BREAKPOINT_ON_BUG
124 # if defined HOST_I386
125 # if defined __GNUC__
126 __asm__ ("int3");
127 # elif defined _MSC_VER
128 _asm _emit 0xcc;
129 # else
130 abort ();
131 # endif
132 # else
133 abort ();
134 # endif
135 #endif
138 return cond;
140 #endif
142 static inline int audio_bits_to_index (int bits)
144 switch (bits) {
145 case 8:
146 return 0;
148 case 16:
149 return 1;
151 case 32:
152 return 2;
154 default:
155 audio_bug ("bits_to_index", 1);
156 AUD_log (NULL, "invalid bits %d\n", bits);
157 return 0;
161 void *audio_calloc (const char *funcname, int nmemb, size_t size)
163 int cond;
164 size_t len;
166 len = nmemb * size;
167 cond = !nmemb || !size;
168 cond |= nmemb < 0;
169 cond |= len < size;
171 if (audio_bug ("audio_calloc", cond)) {
172 AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
173 funcname);
174 AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
175 return NULL;
178 return g_malloc0 (len);
181 void AUD_vlog (const char *cap, const char *fmt, va_list ap)
183 if (cap) {
184 fprintf(stderr, "%s: ", cap);
187 vfprintf(stderr, fmt, ap);
190 void AUD_log (const char *cap, const char *fmt, ...)
192 va_list ap;
194 va_start (ap, fmt);
195 AUD_vlog (cap, fmt, ap);
196 va_end (ap);
199 static void audio_print_settings (struct audsettings *as)
201 dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
203 switch (as->fmt) {
204 case AUDIO_FORMAT_S8:
205 AUD_log (NULL, "S8");
206 break;
207 case AUDIO_FORMAT_U8:
208 AUD_log (NULL, "U8");
209 break;
210 case AUDIO_FORMAT_S16:
211 AUD_log (NULL, "S16");
212 break;
213 case AUDIO_FORMAT_U16:
214 AUD_log (NULL, "U16");
215 break;
216 case AUDIO_FORMAT_S32:
217 AUD_log (NULL, "S32");
218 break;
219 case AUDIO_FORMAT_U32:
220 AUD_log (NULL, "U32");
221 break;
222 case AUDIO_FORMAT_F32:
223 AUD_log (NULL, "F32");
224 break;
225 default:
226 AUD_log (NULL, "invalid(%d)", as->fmt);
227 break;
230 AUD_log (NULL, " endianness=");
231 switch (as->endianness) {
232 case 0:
233 AUD_log (NULL, "little");
234 break;
235 case 1:
236 AUD_log (NULL, "big");
237 break;
238 default:
239 AUD_log (NULL, "invalid");
240 break;
242 AUD_log (NULL, "\n");
245 static int audio_validate_settings (struct audsettings *as)
247 int invalid;
249 invalid = as->nchannels < 1;
250 invalid |= as->endianness != 0 && as->endianness != 1;
252 switch (as->fmt) {
253 case AUDIO_FORMAT_S8:
254 case AUDIO_FORMAT_U8:
255 case AUDIO_FORMAT_S16:
256 case AUDIO_FORMAT_U16:
257 case AUDIO_FORMAT_S32:
258 case AUDIO_FORMAT_U32:
259 case AUDIO_FORMAT_F32:
260 break;
261 default:
262 invalid = 1;
263 break;
266 invalid |= as->freq <= 0;
267 return invalid ? -1 : 0;
270 static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
272 int bits = 8;
273 bool is_signed = false, is_float = false;
275 switch (as->fmt) {
276 case AUDIO_FORMAT_S8:
277 is_signed = true;
278 /* fall through */
279 case AUDIO_FORMAT_U8:
280 break;
282 case AUDIO_FORMAT_S16:
283 is_signed = true;
284 /* fall through */
285 case AUDIO_FORMAT_U16:
286 bits = 16;
287 break;
289 case AUDIO_FORMAT_F32:
290 is_float = true;
291 /* fall through */
292 case AUDIO_FORMAT_S32:
293 is_signed = true;
294 /* fall through */
295 case AUDIO_FORMAT_U32:
296 bits = 32;
297 break;
299 default:
300 abort();
302 return info->freq == as->freq
303 && info->nchannels == as->nchannels
304 && info->is_signed == is_signed
305 && info->is_float == is_float
306 && info->bits == bits
307 && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
310 void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
312 int bits = 8, mul;
313 bool is_signed = false, is_float = false;
315 switch (as->fmt) {
316 case AUDIO_FORMAT_S8:
317 is_signed = true;
318 /* fall through */
319 case AUDIO_FORMAT_U8:
320 mul = 1;
321 break;
323 case AUDIO_FORMAT_S16:
324 is_signed = true;
325 /* fall through */
326 case AUDIO_FORMAT_U16:
327 bits = 16;
328 mul = 2;
329 break;
331 case AUDIO_FORMAT_F32:
332 is_float = true;
333 /* fall through */
334 case AUDIO_FORMAT_S32:
335 is_signed = true;
336 /* fall through */
337 case AUDIO_FORMAT_U32:
338 bits = 32;
339 mul = 4;
340 break;
342 default:
343 abort();
346 info->freq = as->freq;
347 info->bits = bits;
348 info->is_signed = is_signed;
349 info->is_float = is_float;
350 info->nchannels = as->nchannels;
351 info->bytes_per_frame = as->nchannels * mul;
352 info->bytes_per_second = info->freq * info->bytes_per_frame;
353 info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
356 void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
358 if (!len) {
359 return;
362 if (info->is_signed || info->is_float) {
363 memset(buf, 0x00, len * info->bytes_per_frame);
365 else {
366 switch (info->bits) {
367 case 8:
368 memset(buf, 0x80, len * info->bytes_per_frame);
369 break;
371 case 16:
373 int i;
374 uint16_t *p = buf;
375 short s = INT16_MAX;
377 if (info->swap_endianness) {
378 s = bswap16 (s);
381 for (i = 0; i < len * info->nchannels; i++) {
382 p[i] = s;
385 break;
387 case 32:
389 int i;
390 uint32_t *p = buf;
391 int32_t s = INT32_MAX;
393 if (info->swap_endianness) {
394 s = bswap32 (s);
397 for (i = 0; i < len * info->nchannels; i++) {
398 p[i] = s;
401 break;
403 default:
404 AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
405 info->bits);
406 break;
412 * Capture
414 static void noop_conv (struct st_sample *dst, const void *src, int samples)
416 (void) src;
417 (void) dst;
418 (void) samples;
421 static CaptureVoiceOut *audio_pcm_capture_find_specific(AudioState *s,
422 struct audsettings *as)
424 CaptureVoiceOut *cap;
426 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
427 if (audio_pcm_info_eq (&cap->hw.info, as)) {
428 return cap;
431 return NULL;
434 static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
436 struct capture_callback *cb;
438 #ifdef DEBUG_CAPTURE
439 dolog ("notification %d sent\n", cmd);
440 #endif
441 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
442 cb->ops.notify (cb->opaque, cmd);
446 static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
448 if (cap->hw.enabled != enabled) {
449 audcnotification_e cmd;
450 cap->hw.enabled = enabled;
451 cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
452 audio_notify_capture (cap, cmd);
456 static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
458 HWVoiceOut *hw = &cap->hw;
459 SWVoiceOut *sw;
460 int enabled = 0;
462 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
463 if (sw->active) {
464 enabled = 1;
465 break;
468 audio_capture_maybe_changed (cap, enabled);
471 static void audio_detach_capture (HWVoiceOut *hw)
473 SWVoiceCap *sc = hw->cap_head.lh_first;
475 while (sc) {
476 SWVoiceCap *sc1 = sc->entries.le_next;
477 SWVoiceOut *sw = &sc->sw;
478 CaptureVoiceOut *cap = sc->cap;
479 int was_active = sw->active;
481 if (sw->rate) {
482 st_rate_stop (sw->rate);
483 sw->rate = NULL;
486 QLIST_REMOVE (sw, entries);
487 QLIST_REMOVE (sc, entries);
488 g_free (sc);
489 if (was_active) {
490 /* We have removed soft voice from the capture:
491 this might have changed the overall status of the capture
492 since this might have been the only active voice */
493 audio_recalc_and_notify_capture (cap);
495 sc = sc1;
499 static int audio_attach_capture (HWVoiceOut *hw)
501 AudioState *s = hw->s;
502 CaptureVoiceOut *cap;
504 audio_detach_capture (hw);
505 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
506 SWVoiceCap *sc;
507 SWVoiceOut *sw;
508 HWVoiceOut *hw_cap = &cap->hw;
510 sc = g_malloc0(sizeof(*sc));
512 sc->cap = cap;
513 sw = &sc->sw;
514 sw->hw = hw_cap;
515 sw->info = hw->info;
516 sw->empty = 1;
517 sw->active = hw->enabled;
518 sw->conv = noop_conv;
519 sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
520 sw->vol = nominal_volume;
521 sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
522 if (!sw->rate) {
523 dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
524 g_free (sw);
525 return -1;
527 QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
528 QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
529 #ifdef DEBUG_CAPTURE
530 sw->name = g_strdup_printf ("for %p %d,%d,%d",
531 hw, sw->info.freq, sw->info.bits,
532 sw->info.nchannels);
533 dolog ("Added %s active = %d\n", sw->name, sw->active);
534 #endif
535 if (sw->active) {
536 audio_capture_maybe_changed (cap, 1);
539 return 0;
543 * Hard voice (capture)
545 static size_t audio_pcm_hw_find_min_in (HWVoiceIn *hw)
547 SWVoiceIn *sw;
548 size_t m = hw->total_samples_captured;
550 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
551 if (sw->active) {
552 m = MIN (m, sw->total_hw_samples_acquired);
555 return m;
558 static size_t audio_pcm_hw_get_live_in(HWVoiceIn *hw)
560 size_t live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
561 if (audio_bug(__func__, live > hw->conv_buf->size)) {
562 dolog("live=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
563 return 0;
565 return live;
568 static void audio_pcm_hw_clip_out(HWVoiceOut *hw, void *pcm_buf, size_t len)
570 size_t clipped = 0;
571 size_t pos = hw->mix_buf->pos;
573 while (len) {
574 st_sample *src = hw->mix_buf->samples + pos;
575 uint8_t *dst = advance(pcm_buf, clipped * hw->info.bytes_per_frame);
576 size_t samples_till_end_of_buf = hw->mix_buf->size - pos;
577 size_t samples_to_clip = MIN(len, samples_till_end_of_buf);
579 hw->clip(dst, src, samples_to_clip);
581 pos = (pos + samples_to_clip) % hw->mix_buf->size;
582 len -= samples_to_clip;
583 clipped += samples_to_clip;
588 * Soft voice (capture)
590 static size_t audio_pcm_sw_get_rpos_in(SWVoiceIn *sw)
592 HWVoiceIn *hw = sw->hw;
593 ssize_t live = hw->total_samples_captured - sw->total_hw_samples_acquired;
594 ssize_t rpos;
596 if (audio_bug(__func__, live < 0 || live > hw->conv_buf->size)) {
597 dolog("live=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
598 return 0;
601 rpos = hw->conv_buf->pos - live;
602 if (rpos >= 0) {
603 return rpos;
605 else {
606 return hw->conv_buf->size + rpos;
610 static size_t audio_pcm_sw_read(SWVoiceIn *sw, void *buf, size_t size)
612 HWVoiceIn *hw = sw->hw;
613 size_t samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
614 struct st_sample *src, *dst = sw->buf;
616 rpos = audio_pcm_sw_get_rpos_in(sw) % hw->conv_buf->size;
618 live = hw->total_samples_captured - sw->total_hw_samples_acquired;
619 if (audio_bug(__func__, live > hw->conv_buf->size)) {
620 dolog("live_in=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
621 return 0;
624 samples = size / sw->info.bytes_per_frame;
625 if (!live) {
626 return 0;
629 swlim = (live * sw->ratio) >> 32;
630 swlim = MIN (swlim, samples);
632 while (swlim) {
633 src = hw->conv_buf->samples + rpos;
634 if (hw->conv_buf->pos > rpos) {
635 isamp = hw->conv_buf->pos - rpos;
636 } else {
637 isamp = hw->conv_buf->size - rpos;
640 if (!isamp) {
641 break;
643 osamp = swlim;
645 st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
646 swlim -= osamp;
647 rpos = (rpos + isamp) % hw->conv_buf->size;
648 dst += osamp;
649 ret += osamp;
650 total += isamp;
653 if (hw->pcm_ops && !hw->pcm_ops->volume_in) {
654 mixeng_volume (sw->buf, ret, &sw->vol);
657 sw->clip (buf, sw->buf, ret);
658 sw->total_hw_samples_acquired += total;
659 return ret * sw->info.bytes_per_frame;
663 * Hard voice (playback)
665 static size_t audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
667 SWVoiceOut *sw;
668 size_t m = SIZE_MAX;
669 int nb_live = 0;
671 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
672 if (sw->active || !sw->empty) {
673 m = MIN (m, sw->total_hw_samples_mixed);
674 nb_live += 1;
678 *nb_livep = nb_live;
679 return m;
682 static size_t audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
684 size_t smin;
685 int nb_live1;
687 smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
688 if (nb_live) {
689 *nb_live = nb_live1;
692 if (nb_live1) {
693 size_t live = smin;
695 if (audio_bug(__func__, live > hw->mix_buf->size)) {
696 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
697 return 0;
699 return live;
701 return 0;
705 * Soft voice (playback)
707 static size_t audio_pcm_sw_write(SWVoiceOut *sw, void *buf, size_t size)
709 size_t hwsamples, samples, isamp, osamp, wpos, live, dead, left, swlim, blck;
710 size_t ret = 0, pos = 0, total = 0;
712 if (!sw) {
713 return size;
716 hwsamples = sw->hw->mix_buf->size;
718 live = sw->total_hw_samples_mixed;
719 if (audio_bug(__func__, live > hwsamples)) {
720 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hwsamples);
721 return 0;
724 if (live == hwsamples) {
725 #ifdef DEBUG_OUT
726 dolog ("%s is full %d\n", sw->name, live);
727 #endif
728 return 0;
731 wpos = (sw->hw->mix_buf->pos + live) % hwsamples;
732 samples = size / sw->info.bytes_per_frame;
734 dead = hwsamples - live;
735 swlim = ((int64_t) dead << 32) / sw->ratio;
736 swlim = MIN (swlim, samples);
737 if (swlim) {
738 sw->conv (sw->buf, buf, swlim);
740 if (sw->hw->pcm_ops && !sw->hw->pcm_ops->volume_out) {
741 mixeng_volume (sw->buf, swlim, &sw->vol);
745 while (swlim) {
746 dead = hwsamples - live;
747 left = hwsamples - wpos;
748 blck = MIN (dead, left);
749 if (!blck) {
750 break;
752 isamp = swlim;
753 osamp = blck;
754 st_rate_flow_mix (
755 sw->rate,
756 sw->buf + pos,
757 sw->hw->mix_buf->samples + wpos,
758 &isamp,
759 &osamp
761 ret += isamp;
762 swlim -= isamp;
763 pos += isamp;
764 live += osamp;
765 wpos = (wpos + osamp) % hwsamples;
766 total += osamp;
769 sw->total_hw_samples_mixed += total;
770 sw->empty = sw->total_hw_samples_mixed == 0;
772 #ifdef DEBUG_OUT
773 dolog (
774 "%s: write size %zu ret %zu total sw %zu\n",
775 SW_NAME (sw),
776 size / sw->info.bytes_per_frame,
777 ret,
778 sw->total_hw_samples_mixed
780 #endif
782 return ret * sw->info.bytes_per_frame;
785 #ifdef DEBUG_AUDIO
786 static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
788 dolog("%s: bits %d, sign %d, float %d, freq %d, nchan %d\n",
789 cap, info->bits, info->is_signed, info->is_float, info->freq,
790 info->nchannels);
792 #endif
794 #define DAC
795 #include "audio_template.h"
796 #undef DAC
797 #include "audio_template.h"
800 * Timer
802 static int audio_is_timer_needed(AudioState *s)
804 HWVoiceIn *hwi = NULL;
805 HWVoiceOut *hwo = NULL;
807 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
808 if (!hwo->poll_mode) return 1;
810 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
811 if (!hwi->poll_mode) return 1;
813 return 0;
816 static void audio_reset_timer (AudioState *s)
818 if (audio_is_timer_needed(s)) {
819 timer_mod_anticipate_ns(s->ts,
820 qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
821 if (!s->timer_running) {
822 s->timer_running = true;
823 s->timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
824 trace_audio_timer_start(s->period_ticks / SCALE_MS);
826 } else {
827 timer_del(s->ts);
828 if (s->timer_running) {
829 s->timer_running = false;
830 trace_audio_timer_stop();
835 static void audio_timer (void *opaque)
837 int64_t now, diff;
838 AudioState *s = opaque;
840 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
841 diff = now - s->timer_last;
842 if (diff > s->period_ticks * 3 / 2) {
843 trace_audio_timer_delayed(diff / SCALE_MS);
845 s->timer_last = now;
847 audio_run(s, "timer");
848 audio_reset_timer(s);
852 * Public API
854 size_t AUD_write(SWVoiceOut *sw, void *buf, size_t size)
856 HWVoiceOut *hw;
858 if (!sw) {
859 /* XXX: Consider options */
860 return size;
862 hw = sw->hw;
864 if (!hw->enabled) {
865 dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
866 return 0;
869 if (audio_get_pdo_out(hw->s->dev)->mixing_engine) {
870 return audio_pcm_sw_write(sw, buf, size);
871 } else {
872 return hw->pcm_ops->write(hw, buf, size);
876 size_t AUD_read(SWVoiceIn *sw, void *buf, size_t size)
878 HWVoiceIn *hw;
880 if (!sw) {
881 /* XXX: Consider options */
882 return size;
884 hw = sw->hw;
886 if (!hw->enabled) {
887 dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
888 return 0;
891 if (audio_get_pdo_in(hw->s->dev)->mixing_engine) {
892 return audio_pcm_sw_read(sw, buf, size);
893 } else {
894 return hw->pcm_ops->read(hw, buf, size);
898 int AUD_get_buffer_size_out(SWVoiceOut *sw)
900 return sw->hw->samples * sw->hw->info.bytes_per_frame;
903 void AUD_set_active_out (SWVoiceOut *sw, int on)
905 HWVoiceOut *hw;
907 if (!sw) {
908 return;
911 hw = sw->hw;
912 if (sw->active != on) {
913 AudioState *s = sw->s;
914 SWVoiceOut *temp_sw;
915 SWVoiceCap *sc;
917 if (on) {
918 hw->pending_disable = 0;
919 if (!hw->enabled) {
920 hw->enabled = 1;
921 if (s->vm_running) {
922 if (hw->pcm_ops->enable_out) {
923 hw->pcm_ops->enable_out(hw, true);
925 audio_reset_timer (s);
929 else {
930 if (hw->enabled) {
931 int nb_active = 0;
933 for (temp_sw = hw->sw_head.lh_first; temp_sw;
934 temp_sw = temp_sw->entries.le_next) {
935 nb_active += temp_sw->active != 0;
938 hw->pending_disable = nb_active == 1;
942 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
943 sc->sw.active = hw->enabled;
944 if (hw->enabled) {
945 audio_capture_maybe_changed (sc->cap, 1);
948 sw->active = on;
952 void AUD_set_active_in (SWVoiceIn *sw, int on)
954 HWVoiceIn *hw;
956 if (!sw) {
957 return;
960 hw = sw->hw;
961 if (sw->active != on) {
962 AudioState *s = sw->s;
963 SWVoiceIn *temp_sw;
965 if (on) {
966 if (!hw->enabled) {
967 hw->enabled = 1;
968 if (s->vm_running) {
969 if (hw->pcm_ops->enable_in) {
970 hw->pcm_ops->enable_in(hw, true);
972 audio_reset_timer (s);
975 sw->total_hw_samples_acquired = hw->total_samples_captured;
977 else {
978 if (hw->enabled) {
979 int nb_active = 0;
981 for (temp_sw = hw->sw_head.lh_first; temp_sw;
982 temp_sw = temp_sw->entries.le_next) {
983 nb_active += temp_sw->active != 0;
986 if (nb_active == 1) {
987 hw->enabled = 0;
988 if (hw->pcm_ops->enable_in) {
989 hw->pcm_ops->enable_in(hw, false);
994 sw->active = on;
998 static size_t audio_get_avail (SWVoiceIn *sw)
1000 size_t live;
1002 if (!sw) {
1003 return 0;
1006 live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
1007 if (audio_bug(__func__, live > sw->hw->conv_buf->size)) {
1008 dolog("live=%zu sw->hw->conv_buf->size=%zu\n", live,
1009 sw->hw->conv_buf->size);
1010 return 0;
1013 ldebug (
1014 "%s: get_avail live %d ret %" PRId64 "\n",
1015 SW_NAME (sw),
1016 live, (((int64_t) live << 32) / sw->ratio) * sw->info.bytes_per_frame
1019 return (((int64_t) live << 32) / sw->ratio) * sw->info.bytes_per_frame;
1022 static size_t audio_get_free(SWVoiceOut *sw)
1024 size_t live, dead;
1026 if (!sw) {
1027 return 0;
1030 live = sw->total_hw_samples_mixed;
1032 if (audio_bug(__func__, live > sw->hw->mix_buf->size)) {
1033 dolog("live=%zu sw->hw->mix_buf->size=%zu\n", live,
1034 sw->hw->mix_buf->size);
1035 return 0;
1038 dead = sw->hw->mix_buf->size - live;
1040 #ifdef DEBUG_OUT
1041 dolog ("%s: get_free live %d dead %d ret %" PRId64 "\n",
1042 SW_NAME (sw),
1043 live, dead, (((int64_t) dead << 32) / sw->ratio) *
1044 sw->info.bytes_per_frame);
1045 #endif
1047 return (((int64_t) dead << 32) / sw->ratio) * sw->info.bytes_per_frame;
1050 static void audio_capture_mix_and_clear(HWVoiceOut *hw, size_t rpos,
1051 size_t samples)
1053 size_t n;
1055 if (hw->enabled) {
1056 SWVoiceCap *sc;
1058 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1059 SWVoiceOut *sw = &sc->sw;
1060 int rpos2 = rpos;
1062 n = samples;
1063 while (n) {
1064 size_t till_end_of_hw = hw->mix_buf->size - rpos2;
1065 size_t to_write = MIN(till_end_of_hw, n);
1066 size_t bytes = to_write * hw->info.bytes_per_frame;
1067 size_t written;
1069 sw->buf = hw->mix_buf->samples + rpos2;
1070 written = audio_pcm_sw_write (sw, NULL, bytes);
1071 if (written - bytes) {
1072 dolog("Could not mix %zu bytes into a capture "
1073 "buffer, mixed %zu\n",
1074 bytes, written);
1075 break;
1077 n -= to_write;
1078 rpos2 = (rpos2 + to_write) % hw->mix_buf->size;
1083 n = MIN(samples, hw->mix_buf->size - rpos);
1084 mixeng_clear(hw->mix_buf->samples + rpos, n);
1085 mixeng_clear(hw->mix_buf->samples, samples - n);
1088 static size_t audio_pcm_hw_run_out(HWVoiceOut *hw, size_t live)
1090 size_t clipped = 0;
1092 while (live) {
1093 size_t size = live * hw->info.bytes_per_frame;
1094 size_t decr, proc;
1095 void *buf = hw->pcm_ops->get_buffer_out(hw, &size);
1097 if (size == 0) {
1098 break;
1101 decr = MIN(size / hw->info.bytes_per_frame, live);
1102 if (buf) {
1103 audio_pcm_hw_clip_out(hw, buf, decr);
1105 proc = hw->pcm_ops->put_buffer_out(hw, buf,
1106 decr * hw->info.bytes_per_frame) /
1107 hw->info.bytes_per_frame;
1109 live -= proc;
1110 clipped += proc;
1111 hw->mix_buf->pos = (hw->mix_buf->pos + proc) % hw->mix_buf->size;
1113 if (proc == 0 || proc < decr) {
1114 break;
1118 if (hw->pcm_ops->run_buffer_out) {
1119 hw->pcm_ops->run_buffer_out(hw);
1122 return clipped;
1125 static void audio_run_out (AudioState *s)
1127 HWVoiceOut *hw = NULL;
1128 SWVoiceOut *sw;
1130 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1131 while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1132 /* there is exactly 1 sw for each hw with no mixeng */
1133 sw = hw->sw_head.lh_first;
1135 if (hw->pending_disable) {
1136 hw->enabled = 0;
1137 hw->pending_disable = 0;
1138 if (hw->pcm_ops->enable_out) {
1139 hw->pcm_ops->enable_out(hw, false);
1143 if (sw->active) {
1144 sw->callback.fn(sw->callback.opaque, INT_MAX);
1147 return;
1150 while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1151 size_t played, live, prev_rpos, free;
1152 int nb_live, cleanup_required;
1154 live = audio_pcm_hw_get_live_out (hw, &nb_live);
1155 if (!nb_live) {
1156 live = 0;
1159 if (audio_bug(__func__, live > hw->mix_buf->size)) {
1160 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
1161 continue;
1164 if (hw->pending_disable && !nb_live) {
1165 SWVoiceCap *sc;
1166 #ifdef DEBUG_OUT
1167 dolog ("Disabling voice\n");
1168 #endif
1169 hw->enabled = 0;
1170 hw->pending_disable = 0;
1171 if (hw->pcm_ops->enable_out) {
1172 hw->pcm_ops->enable_out(hw, false);
1174 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1175 sc->sw.active = 0;
1176 audio_recalc_and_notify_capture (sc->cap);
1178 continue;
1181 if (!live) {
1182 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1183 if (sw->active) {
1184 free = audio_get_free (sw);
1185 if (free > 0) {
1186 sw->callback.fn (sw->callback.opaque, free);
1190 if (hw->pcm_ops->run_buffer_out) {
1191 hw->pcm_ops->run_buffer_out(hw);
1193 continue;
1196 prev_rpos = hw->mix_buf->pos;
1197 played = audio_pcm_hw_run_out(hw, live);
1198 replay_audio_out(&played);
1199 if (audio_bug(__func__, hw->mix_buf->pos >= hw->mix_buf->size)) {
1200 dolog("hw->mix_buf->pos=%zu hw->mix_buf->size=%zu played=%zu\n",
1201 hw->mix_buf->pos, hw->mix_buf->size, played);
1202 hw->mix_buf->pos = 0;
1205 #ifdef DEBUG_OUT
1206 dolog("played=%zu\n", played);
1207 #endif
1209 if (played) {
1210 hw->ts_helper += played;
1211 audio_capture_mix_and_clear (hw, prev_rpos, played);
1214 cleanup_required = 0;
1215 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1216 if (!sw->active && sw->empty) {
1217 continue;
1220 if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1221 dolog("played=%zu sw->total_hw_samples_mixed=%zu\n",
1222 played, sw->total_hw_samples_mixed);
1223 played = sw->total_hw_samples_mixed;
1226 sw->total_hw_samples_mixed -= played;
1228 if (!sw->total_hw_samples_mixed) {
1229 sw->empty = 1;
1230 cleanup_required |= !sw->active && !sw->callback.fn;
1233 if (sw->active) {
1234 free = audio_get_free (sw);
1235 if (free > 0) {
1236 sw->callback.fn (sw->callback.opaque, free);
1241 if (cleanup_required) {
1242 SWVoiceOut *sw1;
1244 sw = hw->sw_head.lh_first;
1245 while (sw) {
1246 sw1 = sw->entries.le_next;
1247 if (!sw->active && !sw->callback.fn) {
1248 audio_close_out (sw);
1250 sw = sw1;
1256 static size_t audio_pcm_hw_run_in(HWVoiceIn *hw, size_t samples)
1258 size_t conv = 0;
1259 STSampleBuffer *conv_buf = hw->conv_buf;
1261 while (samples) {
1262 size_t proc;
1263 size_t size = samples * hw->info.bytes_per_frame;
1264 void *buf = hw->pcm_ops->get_buffer_in(hw, &size);
1266 assert(size % hw->info.bytes_per_frame == 0);
1267 if (size == 0) {
1268 break;
1271 proc = MIN(size / hw->info.bytes_per_frame,
1272 conv_buf->size - conv_buf->pos);
1274 hw->conv(conv_buf->samples + conv_buf->pos, buf, proc);
1275 conv_buf->pos = (conv_buf->pos + proc) % conv_buf->size;
1277 samples -= proc;
1278 conv += proc;
1279 hw->pcm_ops->put_buffer_in(hw, buf, proc * hw->info.bytes_per_frame);
1282 return conv;
1285 static void audio_run_in (AudioState *s)
1287 HWVoiceIn *hw = NULL;
1289 if (!audio_get_pdo_in(s->dev)->mixing_engine) {
1290 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1291 /* there is exactly 1 sw for each hw with no mixeng */
1292 SWVoiceIn *sw = hw->sw_head.lh_first;
1293 if (sw->active) {
1294 sw->callback.fn(sw->callback.opaque, INT_MAX);
1297 return;
1300 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1301 SWVoiceIn *sw;
1302 size_t captured = 0, min;
1304 if (replay_mode != REPLAY_MODE_PLAY) {
1305 captured = audio_pcm_hw_run_in(
1306 hw, hw->conv_buf->size - audio_pcm_hw_get_live_in(hw));
1308 replay_audio_in(&captured, hw->conv_buf->samples, &hw->conv_buf->pos,
1309 hw->conv_buf->size);
1311 min = audio_pcm_hw_find_min_in (hw);
1312 hw->total_samples_captured += captured - min;
1313 hw->ts_helper += captured;
1315 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1316 sw->total_hw_samples_acquired -= min;
1318 if (sw->active) {
1319 size_t avail;
1321 avail = audio_get_avail (sw);
1322 if (avail > 0) {
1323 sw->callback.fn (sw->callback.opaque, avail);
1330 static void audio_run_capture (AudioState *s)
1332 CaptureVoiceOut *cap;
1334 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1335 size_t live, rpos, captured;
1336 HWVoiceOut *hw = &cap->hw;
1337 SWVoiceOut *sw;
1339 captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1340 rpos = hw->mix_buf->pos;
1341 while (live) {
1342 size_t left = hw->mix_buf->size - rpos;
1343 size_t to_capture = MIN(live, left);
1344 struct st_sample *src;
1345 struct capture_callback *cb;
1347 src = hw->mix_buf->samples + rpos;
1348 hw->clip (cap->buf, src, to_capture);
1349 mixeng_clear (src, to_capture);
1351 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1352 cb->ops.capture (cb->opaque, cap->buf,
1353 to_capture * hw->info.bytes_per_frame);
1355 rpos = (rpos + to_capture) % hw->mix_buf->size;
1356 live -= to_capture;
1358 hw->mix_buf->pos = rpos;
1360 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1361 if (!sw->active && sw->empty) {
1362 continue;
1365 if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1366 dolog("captured=%zu sw->total_hw_samples_mixed=%zu\n",
1367 captured, sw->total_hw_samples_mixed);
1368 captured = sw->total_hw_samples_mixed;
1371 sw->total_hw_samples_mixed -= captured;
1372 sw->empty = sw->total_hw_samples_mixed == 0;
1377 void audio_run(AudioState *s, const char *msg)
1379 audio_run_out(s);
1380 audio_run_in(s);
1381 audio_run_capture(s);
1383 #ifdef DEBUG_POLL
1385 static double prevtime;
1386 double currtime;
1387 struct timeval tv;
1389 if (gettimeofday (&tv, NULL)) {
1390 perror ("audio_run: gettimeofday");
1391 return;
1394 currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1395 dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1396 prevtime = currtime;
1398 #endif
1401 void *audio_generic_get_buffer_in(HWVoiceIn *hw, size_t *size)
1403 ssize_t start;
1405 if (unlikely(!hw->buf_emul)) {
1406 size_t calc_size = hw->conv_buf->size * hw->info.bytes_per_frame;
1407 hw->buf_emul = g_malloc(calc_size);
1408 hw->size_emul = calc_size;
1409 hw->pos_emul = hw->pending_emul = 0;
1412 while (hw->pending_emul < hw->size_emul) {
1413 size_t read_len = MIN(hw->size_emul - hw->pos_emul,
1414 hw->size_emul - hw->pending_emul);
1415 size_t read = hw->pcm_ops->read(hw, hw->buf_emul + hw->pos_emul,
1416 read_len);
1417 hw->pending_emul += read;
1418 hw->pos_emul = (hw->pos_emul + read) % hw->size_emul;
1419 if (read < read_len) {
1420 break;
1424 start = ((ssize_t) hw->pos_emul) - hw->pending_emul;
1425 if (start < 0) {
1426 start += hw->size_emul;
1428 assert(start >= 0 && start < hw->size_emul);
1430 *size = MIN(*size, hw->pending_emul);
1431 *size = MIN(*size, hw->size_emul - start);
1432 return hw->buf_emul + start;
1435 void audio_generic_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
1437 assert(size <= hw->pending_emul);
1438 hw->pending_emul -= size;
1441 void audio_generic_run_buffer_out(HWVoiceOut *hw)
1443 while (hw->pending_emul) {
1444 size_t write_len, written;
1445 ssize_t start = ((ssize_t) hw->pos_emul) - hw->pending_emul;
1447 if (start < 0) {
1448 start += hw->size_emul;
1450 assert(start >= 0 && start < hw->size_emul);
1452 write_len = MIN(hw->pending_emul, hw->size_emul - start);
1454 written = hw->pcm_ops->write(hw, hw->buf_emul + start, write_len);
1455 hw->pending_emul -= written;
1457 if (written < write_len) {
1458 break;
1463 void *audio_generic_get_buffer_out(HWVoiceOut *hw, size_t *size)
1465 if (unlikely(!hw->buf_emul)) {
1466 size_t calc_size = hw->mix_buf->size * hw->info.bytes_per_frame;
1468 hw->buf_emul = g_malloc(calc_size);
1469 hw->size_emul = calc_size;
1470 hw->pos_emul = hw->pending_emul = 0;
1473 *size = MIN(hw->size_emul - hw->pending_emul,
1474 hw->size_emul - hw->pos_emul);
1475 return hw->buf_emul + hw->pos_emul;
1478 size_t audio_generic_put_buffer_out(HWVoiceOut *hw, void *buf, size_t size)
1480 assert(buf == hw->buf_emul + hw->pos_emul &&
1481 size + hw->pending_emul <= hw->size_emul);
1483 hw->pending_emul += size;
1484 hw->pos_emul = (hw->pos_emul + size) % hw->size_emul;
1486 return size;
1489 size_t audio_generic_write(HWVoiceOut *hw, void *buf, size_t size)
1491 size_t total = 0;
1493 while (total < size) {
1494 size_t dst_size = size - total;
1495 size_t copy_size, proc;
1496 void *dst = hw->pcm_ops->get_buffer_out(hw, &dst_size);
1498 if (dst_size == 0) {
1499 break;
1502 copy_size = MIN(size - total, dst_size);
1503 if (dst) {
1504 memcpy(dst, (char *)buf + total, copy_size);
1506 proc = hw->pcm_ops->put_buffer_out(hw, dst, copy_size);
1507 total += proc;
1509 if (proc == 0 || proc < copy_size) {
1510 break;
1514 if (hw->pcm_ops->run_buffer_out) {
1515 hw->pcm_ops->run_buffer_out(hw);
1518 return total;
1521 size_t audio_generic_read(HWVoiceIn *hw, void *buf, size_t size)
1523 size_t total = 0;
1525 while (total < size) {
1526 size_t src_size = size - total;
1527 void *src = hw->pcm_ops->get_buffer_in(hw, &src_size);
1529 if (src_size == 0) {
1530 break;
1533 memcpy((char *)buf + total, src, src_size);
1534 hw->pcm_ops->put_buffer_in(hw, src, src_size);
1535 total += src_size;
1538 return total;
1541 static int audio_driver_init(AudioState *s, struct audio_driver *drv,
1542 bool msg, Audiodev *dev)
1544 s->drv_opaque = drv->init(dev);
1546 if (s->drv_opaque) {
1547 if (!drv->pcm_ops->get_buffer_in) {
1548 drv->pcm_ops->get_buffer_in = audio_generic_get_buffer_in;
1549 drv->pcm_ops->put_buffer_in = audio_generic_put_buffer_in;
1551 if (!drv->pcm_ops->get_buffer_out) {
1552 drv->pcm_ops->get_buffer_out = audio_generic_get_buffer_out;
1553 drv->pcm_ops->put_buffer_out = audio_generic_put_buffer_out;
1556 audio_init_nb_voices_out(s, drv);
1557 audio_init_nb_voices_in(s, drv);
1558 s->drv = drv;
1559 return 0;
1561 else {
1562 if (msg) {
1563 dolog("Could not init `%s' audio driver\n", drv->name);
1565 return -1;
1569 static void audio_vm_change_state_handler (void *opaque, int running,
1570 RunState state)
1572 AudioState *s = opaque;
1573 HWVoiceOut *hwo = NULL;
1574 HWVoiceIn *hwi = NULL;
1576 s->vm_running = running;
1577 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
1578 if (hwo->pcm_ops->enable_out) {
1579 hwo->pcm_ops->enable_out(hwo, running);
1583 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
1584 if (hwi->pcm_ops->enable_in) {
1585 hwi->pcm_ops->enable_in(hwi, running);
1588 audio_reset_timer (s);
1591 static bool is_cleaning_up;
1593 bool audio_is_cleaning_up(void)
1595 return is_cleaning_up;
1598 static void free_audio_state(AudioState *s)
1600 HWVoiceOut *hwo, *hwon;
1601 HWVoiceIn *hwi, *hwin;
1603 QLIST_FOREACH_SAFE(hwo, &s->hw_head_out, entries, hwon) {
1604 SWVoiceCap *sc;
1606 if (hwo->enabled && hwo->pcm_ops->enable_out) {
1607 hwo->pcm_ops->enable_out(hwo, false);
1609 hwo->pcm_ops->fini_out (hwo);
1611 for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1612 CaptureVoiceOut *cap = sc->cap;
1613 struct capture_callback *cb;
1615 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1616 cb->ops.destroy (cb->opaque);
1619 QLIST_REMOVE(hwo, entries);
1622 QLIST_FOREACH_SAFE(hwi, &s->hw_head_in, entries, hwin) {
1623 if (hwi->enabled && hwi->pcm_ops->enable_in) {
1624 hwi->pcm_ops->enable_in(hwi, false);
1626 hwi->pcm_ops->fini_in (hwi);
1627 QLIST_REMOVE(hwi, entries);
1630 if (s->drv) {
1631 s->drv->fini (s->drv_opaque);
1632 s->drv = NULL;
1635 if (s->dev) {
1636 qapi_free_Audiodev(s->dev);
1637 s->dev = NULL;
1640 if (s->ts) {
1641 timer_free(s->ts);
1642 s->ts = NULL;
1645 g_free(s);
1648 void audio_cleanup(void)
1650 is_cleaning_up = true;
1651 while (!QTAILQ_EMPTY(&audio_states)) {
1652 AudioState *s = QTAILQ_FIRST(&audio_states);
1653 QTAILQ_REMOVE(&audio_states, s, list);
1654 free_audio_state(s);
1658 static const VMStateDescription vmstate_audio = {
1659 .name = "audio",
1660 .version_id = 1,
1661 .minimum_version_id = 1,
1662 .fields = (VMStateField[]) {
1663 VMSTATE_END_OF_LIST()
1667 static void audio_validate_opts(Audiodev *dev, Error **errp);
1669 static AudiodevListEntry *audiodev_find(
1670 AudiodevListHead *head, const char *drvname)
1672 AudiodevListEntry *e;
1673 QSIMPLEQ_FOREACH(e, head, next) {
1674 if (strcmp(AudiodevDriver_str(e->dev->driver), drvname) == 0) {
1675 return e;
1679 return NULL;
1683 * if we have dev, this function was called because of an -audiodev argument =>
1684 * initialize a new state with it
1685 * if dev == NULL => legacy implicit initialization, return the already created
1686 * state or create a new one
1688 static AudioState *audio_init(Audiodev *dev, const char *name)
1690 static bool atexit_registered;
1691 size_t i;
1692 int done = 0;
1693 const char *drvname = NULL;
1694 VMChangeStateEntry *e;
1695 AudioState *s;
1696 struct audio_driver *driver;
1697 /* silence gcc warning about uninitialized variable */
1698 AudiodevListHead head = QSIMPLEQ_HEAD_INITIALIZER(head);
1700 if (using_spice) {
1702 * When using spice allow the spice audio driver being picked
1703 * as default.
1705 * Temporary hack. Using audio devices without explicit
1706 * audiodev= property is already deprecated. Same goes for
1707 * the -soundhw switch. Once this support gets finally
1708 * removed we can also drop the concept of a default audio
1709 * backend and this can go away.
1711 driver = audio_driver_lookup("spice");
1712 driver->can_be_default = 1;
1715 if (dev) {
1716 /* -audiodev option */
1717 legacy_config = false;
1718 drvname = AudiodevDriver_str(dev->driver);
1719 } else if (!QTAILQ_EMPTY(&audio_states)) {
1720 if (!legacy_config) {
1721 dolog("Device %s: audiodev default parameter is deprecated, please "
1722 "specify audiodev=%s\n", name,
1723 QTAILQ_FIRST(&audio_states)->dev->id);
1725 return QTAILQ_FIRST(&audio_states);
1726 } else {
1727 /* legacy implicit initialization */
1728 head = audio_handle_legacy_opts();
1730 * In case of legacy initialization, all Audiodevs in the list will have
1731 * the same configuration (except the driver), so it doesn't matter which
1732 * one we chose. We need an Audiodev to set up AudioState before we can
1733 * init a driver. Also note that dev at this point is still in the
1734 * list.
1736 dev = QSIMPLEQ_FIRST(&head)->dev;
1737 audio_validate_opts(dev, &error_abort);
1740 s = g_malloc0(sizeof(AudioState));
1741 s->dev = dev;
1743 QLIST_INIT (&s->hw_head_out);
1744 QLIST_INIT (&s->hw_head_in);
1745 QLIST_INIT (&s->cap_head);
1746 if (!atexit_registered) {
1747 atexit(audio_cleanup);
1748 atexit_registered = true;
1750 QTAILQ_INSERT_TAIL(&audio_states, s, list);
1752 s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1754 s->nb_hw_voices_out = audio_get_pdo_out(dev)->voices;
1755 s->nb_hw_voices_in = audio_get_pdo_in(dev)->voices;
1757 if (s->nb_hw_voices_out <= 0) {
1758 dolog ("Bogus number of playback voices %d, setting to 1\n",
1759 s->nb_hw_voices_out);
1760 s->nb_hw_voices_out = 1;
1763 if (s->nb_hw_voices_in <= 0) {
1764 dolog ("Bogus number of capture voices %d, setting to 0\n",
1765 s->nb_hw_voices_in);
1766 s->nb_hw_voices_in = 0;
1769 if (drvname) {
1770 driver = audio_driver_lookup(drvname);
1771 if (driver) {
1772 done = !audio_driver_init(s, driver, true, dev);
1773 } else {
1774 dolog ("Unknown audio driver `%s'\n", drvname);
1776 } else {
1777 for (i = 0; audio_prio_list[i]; i++) {
1778 AudiodevListEntry *e = audiodev_find(&head, audio_prio_list[i]);
1779 driver = audio_driver_lookup(audio_prio_list[i]);
1781 if (e && driver) {
1782 s->dev = dev = e->dev;
1783 audio_validate_opts(dev, &error_abort);
1784 done = !audio_driver_init(s, driver, false, dev);
1785 if (done) {
1786 e->dev = NULL;
1787 break;
1792 audio_free_audiodev_list(&head);
1794 if (!done) {
1795 driver = audio_driver_lookup("none");
1796 done = !audio_driver_init(s, driver, false, dev);
1797 assert(done);
1798 dolog("warning: Using timer based audio emulation\n");
1801 if (dev->timer_period <= 0) {
1802 s->period_ticks = 1;
1803 } else {
1804 s->period_ticks = dev->timer_period * (int64_t)SCALE_US;
1807 e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1808 if (!e) {
1809 dolog ("warning: Could not register change state handler\n"
1810 "(Audio can continue looping even after stopping the VM)\n");
1813 QLIST_INIT (&s->card_head);
1814 vmstate_register (NULL, 0, &vmstate_audio, s);
1815 return s;
1818 void audio_free_audiodev_list(AudiodevListHead *head)
1820 AudiodevListEntry *e;
1821 while ((e = QSIMPLEQ_FIRST(head))) {
1822 QSIMPLEQ_REMOVE_HEAD(head, next);
1823 qapi_free_Audiodev(e->dev);
1824 g_free(e);
1828 void AUD_register_card (const char *name, QEMUSoundCard *card)
1830 if (!card->state) {
1831 card->state = audio_init(NULL, name);
1834 card->name = g_strdup (name);
1835 memset (&card->entries, 0, sizeof (card->entries));
1836 QLIST_INSERT_HEAD(&card->state->card_head, card, entries);
1839 void AUD_remove_card (QEMUSoundCard *card)
1841 QLIST_REMOVE (card, entries);
1842 g_free (card->name);
1846 CaptureVoiceOut *AUD_add_capture(
1847 AudioState *s,
1848 struct audsettings *as,
1849 struct audio_capture_ops *ops,
1850 void *cb_opaque
1853 CaptureVoiceOut *cap;
1854 struct capture_callback *cb;
1856 if (!s) {
1857 if (!legacy_config) {
1858 dolog("Capturing without setting an audiodev is deprecated\n");
1860 s = audio_init(NULL, NULL);
1863 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1864 dolog("Can't capture with mixeng disabled\n");
1865 return NULL;
1868 if (audio_validate_settings (as)) {
1869 dolog ("Invalid settings were passed when trying to add capture\n");
1870 audio_print_settings (as);
1871 return NULL;
1874 cb = g_malloc0(sizeof(*cb));
1875 cb->ops = *ops;
1876 cb->opaque = cb_opaque;
1878 cap = audio_pcm_capture_find_specific(s, as);
1879 if (cap) {
1880 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1881 return cap;
1883 else {
1884 HWVoiceOut *hw;
1885 CaptureVoiceOut *cap;
1887 cap = g_malloc0(sizeof(*cap));
1889 hw = &cap->hw;
1890 hw->s = s;
1891 QLIST_INIT (&hw->sw_head);
1892 QLIST_INIT (&cap->cb_head);
1894 /* XXX find a more elegant way */
1895 hw->samples = 4096 * 4;
1896 audio_pcm_hw_alloc_resources_out(hw);
1898 audio_pcm_init_info (&hw->info, as);
1900 cap->buf = g_malloc0_n(hw->mix_buf->size, hw->info.bytes_per_frame);
1902 if (hw->info.is_float) {
1903 hw->clip = mixeng_clip_float[hw->info.nchannels == 2];
1904 } else {
1905 hw->clip = mixeng_clip
1906 [hw->info.nchannels == 2]
1907 [hw->info.is_signed]
1908 [hw->info.swap_endianness]
1909 [audio_bits_to_index(hw->info.bits)];
1912 QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1913 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1915 QLIST_FOREACH(hw, &s->hw_head_out, entries) {
1916 audio_attach_capture (hw);
1918 return cap;
1922 void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1924 struct capture_callback *cb;
1926 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1927 if (cb->opaque == cb_opaque) {
1928 cb->ops.destroy (cb_opaque);
1929 QLIST_REMOVE (cb, entries);
1930 g_free (cb);
1932 if (!cap->cb_head.lh_first) {
1933 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
1935 while (sw) {
1936 SWVoiceCap *sc = (SWVoiceCap *) sw;
1937 #ifdef DEBUG_CAPTURE
1938 dolog ("freeing %s\n", sw->name);
1939 #endif
1941 sw1 = sw->entries.le_next;
1942 if (sw->rate) {
1943 st_rate_stop (sw->rate);
1944 sw->rate = NULL;
1946 QLIST_REMOVE (sw, entries);
1947 QLIST_REMOVE (sc, entries);
1948 g_free (sc);
1949 sw = sw1;
1951 QLIST_REMOVE (cap, entries);
1952 g_free (cap->hw.mix_buf);
1953 g_free (cap->buf);
1954 g_free (cap);
1956 return;
1961 void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
1963 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1964 audio_set_volume_out(sw, &vol);
1967 void audio_set_volume_out(SWVoiceOut *sw, Volume *vol)
1969 if (sw) {
1970 HWVoiceOut *hw = sw->hw;
1972 sw->vol.mute = vol->mute;
1973 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
1974 sw->vol.r = nominal_volume.l * vol->vol[vol->channels > 1 ? 1 : 0] /
1975 255;
1977 if (hw->pcm_ops->volume_out) {
1978 hw->pcm_ops->volume_out(hw, vol);
1983 void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
1985 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1986 audio_set_volume_in(sw, &vol);
1989 void audio_set_volume_in(SWVoiceIn *sw, Volume *vol)
1991 if (sw) {
1992 HWVoiceIn *hw = sw->hw;
1994 sw->vol.mute = vol->mute;
1995 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
1996 sw->vol.r = nominal_volume.r * vol->vol[vol->channels > 1 ? 1 : 0] /
1997 255;
1999 if (hw->pcm_ops->volume_in) {
2000 hw->pcm_ops->volume_in(hw, vol);
2005 void audio_create_pdos(Audiodev *dev)
2007 switch (dev->driver) {
2008 #define CASE(DRIVER, driver, pdo_name) \
2009 case AUDIODEV_DRIVER_##DRIVER: \
2010 if (!dev->u.driver.has_in) { \
2011 dev->u.driver.in = g_malloc0( \
2012 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
2013 dev->u.driver.has_in = true; \
2015 if (!dev->u.driver.has_out) { \
2016 dev->u.driver.out = g_malloc0( \
2017 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
2018 dev->u.driver.has_out = true; \
2020 break
2022 CASE(NONE, none, );
2023 CASE(ALSA, alsa, Alsa);
2024 CASE(COREAUDIO, coreaudio, Coreaudio);
2025 CASE(DSOUND, dsound, );
2026 CASE(JACK, jack, Jack);
2027 CASE(OSS, oss, Oss);
2028 CASE(PA, pa, Pa);
2029 CASE(SDL, sdl, );
2030 CASE(SPICE, spice, );
2031 CASE(WAV, wav, );
2033 case AUDIODEV_DRIVER__MAX:
2034 abort();
2038 static void audio_validate_per_direction_opts(
2039 AudiodevPerDirectionOptions *pdo, Error **errp)
2041 if (!pdo->has_mixing_engine) {
2042 pdo->has_mixing_engine = true;
2043 pdo->mixing_engine = true;
2045 if (!pdo->has_fixed_settings) {
2046 pdo->has_fixed_settings = true;
2047 pdo->fixed_settings = pdo->mixing_engine;
2049 if (!pdo->fixed_settings &&
2050 (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
2051 error_setg(errp,
2052 "You can't use frequency, channels or format with fixed-settings=off");
2053 return;
2055 if (!pdo->mixing_engine && pdo->fixed_settings) {
2056 error_setg(errp, "You can't use fixed-settings without mixeng");
2057 return;
2060 if (!pdo->has_frequency) {
2061 pdo->has_frequency = true;
2062 pdo->frequency = 44100;
2064 if (!pdo->has_channels) {
2065 pdo->has_channels = true;
2066 pdo->channels = 2;
2068 if (!pdo->has_voices) {
2069 pdo->has_voices = true;
2070 pdo->voices = pdo->mixing_engine ? 1 : INT_MAX;
2072 if (!pdo->has_format) {
2073 pdo->has_format = true;
2074 pdo->format = AUDIO_FORMAT_S16;
2078 static void audio_validate_opts(Audiodev *dev, Error **errp)
2080 Error *err = NULL;
2082 audio_create_pdos(dev);
2084 audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
2085 if (err) {
2086 error_propagate(errp, err);
2087 return;
2090 audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
2091 if (err) {
2092 error_propagate(errp, err);
2093 return;
2096 if (!dev->has_timer_period) {
2097 dev->has_timer_period = true;
2098 dev->timer_period = 10000; /* 100Hz -> 10ms */
2102 void audio_parse_option(const char *opt)
2104 AudiodevListEntry *e;
2105 Audiodev *dev = NULL;
2107 Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
2108 visit_type_Audiodev(v, NULL, &dev, &error_fatal);
2109 visit_free(v);
2111 audio_validate_opts(dev, &error_fatal);
2113 e = g_malloc0(sizeof(AudiodevListEntry));
2114 e->dev = dev;
2115 QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
2118 void audio_init_audiodevs(void)
2120 AudiodevListEntry *e;
2122 QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2123 audio_init(e->dev, NULL);
2127 audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
2129 return (audsettings) {
2130 .freq = pdo->frequency,
2131 .nchannels = pdo->channels,
2132 .fmt = pdo->format,
2133 .endianness = AUDIO_HOST_ENDIANNESS,
2137 int audioformat_bytes_per_sample(AudioFormat fmt)
2139 switch (fmt) {
2140 case AUDIO_FORMAT_U8:
2141 case AUDIO_FORMAT_S8:
2142 return 1;
2144 case AUDIO_FORMAT_U16:
2145 case AUDIO_FORMAT_S16:
2146 return 2;
2148 case AUDIO_FORMAT_U32:
2149 case AUDIO_FORMAT_S32:
2150 case AUDIO_FORMAT_F32:
2151 return 4;
2153 case AUDIO_FORMAT__MAX:
2156 abort();
2160 /* frames = freq * usec / 1e6 */
2161 int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
2162 audsettings *as, int def_usecs)
2164 uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
2165 return (as->freq * usecs + 500000) / 1000000;
2168 /* samples = channels * frames = channels * freq * usec / 1e6 */
2169 int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
2170 audsettings *as, int def_usecs)
2172 return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
2176 * bytes = bytes_per_sample * samples =
2177 * bytes_per_sample * channels * freq * usec / 1e6
2179 int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
2180 audsettings *as, int def_usecs)
2182 return audio_buffer_samples(pdo, as, def_usecs) *
2183 audioformat_bytes_per_sample(as->fmt);
2186 AudioState *audio_state_by_name(const char *name)
2188 AudioState *s;
2189 QTAILQ_FOREACH(s, &audio_states, list) {
2190 assert(s->dev);
2191 if (strcmp(name, s->dev->id) == 0) {
2192 return s;
2195 return NULL;
2198 const char *audio_get_id(QEMUSoundCard *card)
2200 if (card->state) {
2201 assert(card->state->dev);
2202 return card->state->dev->id;
2203 } else {
2204 return "";
2208 void audio_rate_start(RateCtl *rate)
2210 memset(rate, 0, sizeof(RateCtl));
2211 rate->start_ticks = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2214 size_t audio_rate_get_bytes(struct audio_pcm_info *info, RateCtl *rate,
2215 size_t bytes_avail)
2217 int64_t now;
2218 int64_t ticks;
2219 int64_t bytes;
2220 int64_t samples;
2221 size_t ret;
2223 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2224 ticks = now - rate->start_ticks;
2225 bytes = muldiv64(ticks, info->bytes_per_second, NANOSECONDS_PER_SECOND);
2226 samples = (bytes - rate->bytes_sent) / info->bytes_per_frame;
2227 if (samples < 0 || samples > 65536) {
2228 AUD_log(NULL, "Resetting rate control (%" PRId64 " samples)\n", samples);
2229 audio_rate_start(rate);
2230 samples = 0;
2233 ret = MIN(samples * info->bytes_per_frame, bytes_avail);
2234 rate->bytes_sent += ret;
2235 return ret;