gitlab-ci: Fix 'when:' condition in EDK2 jobs
[qemu/rayw.git] / audio / audio.c
blob59453ef85673d69d6b16c4c69afefb5dca6f84c1
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-common.h"
36 #include "sysemu/replay.h"
37 #include "sysemu/runstate.h"
38 #include "ui/qemu-spice.h"
39 #include "trace.h"
41 #define AUDIO_CAP "audio"
42 #include "audio_int.h"
44 /* #define DEBUG_LIVE */
45 /* #define DEBUG_OUT */
46 /* #define DEBUG_CAPTURE */
47 /* #define DEBUG_POLL */
49 #define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
52 /* Order of CONFIG_AUDIO_DRIVERS is import.
53 The 1st one is the one used by default, that is the reason
54 that we generate the list.
56 const char *audio_prio_list[] = {
57 "spice",
58 CONFIG_AUDIO_DRIVERS
59 "none",
60 "wav",
61 NULL
64 static QLIST_HEAD(, audio_driver) audio_drivers;
65 static AudiodevListHead audiodevs = QSIMPLEQ_HEAD_INITIALIZER(audiodevs);
67 void audio_driver_register(audio_driver *drv)
69 QLIST_INSERT_HEAD(&audio_drivers, drv, next);
72 audio_driver *audio_driver_lookup(const char *name)
74 struct audio_driver *d;
76 QLIST_FOREACH(d, &audio_drivers, next) {
77 if (strcmp(name, d->name) == 0) {
78 return d;
82 audio_module_load_one(name);
83 QLIST_FOREACH(d, &audio_drivers, next) {
84 if (strcmp(name, d->name) == 0) {
85 return d;
89 return NULL;
92 static QTAILQ_HEAD(AudioStateHead, AudioState) audio_states =
93 QTAILQ_HEAD_INITIALIZER(audio_states);
95 const struct mixeng_volume nominal_volume = {
96 .mute = 0,
97 #ifdef FLOAT_MIXENG
98 .r = 1.0,
99 .l = 1.0,
100 #else
101 .r = 1ULL << 32,
102 .l = 1ULL << 32,
103 #endif
106 static bool legacy_config = true;
108 int audio_bug (const char *funcname, int cond)
110 if (cond) {
111 static int shown;
113 AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
114 if (!shown) {
115 shown = 1;
116 AUD_log (NULL, "Save all your work and restart without audio\n");
117 AUD_log (NULL, "I am sorry\n");
119 AUD_log (NULL, "Context:\n");
120 abort();
123 return cond;
126 static inline int audio_bits_to_index (int bits)
128 switch (bits) {
129 case 8:
130 return 0;
132 case 16:
133 return 1;
135 case 32:
136 return 2;
138 default:
139 audio_bug ("bits_to_index", 1);
140 AUD_log (NULL, "invalid bits %d\n", bits);
141 return 0;
145 void *audio_calloc (const char *funcname, int nmemb, size_t size)
147 int cond;
148 size_t len;
150 len = nmemb * size;
151 cond = !nmemb || !size;
152 cond |= nmemb < 0;
153 cond |= len < size;
155 if (audio_bug ("audio_calloc", cond)) {
156 AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
157 funcname);
158 AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
159 return NULL;
162 return g_malloc0 (len);
165 void AUD_vlog (const char *cap, const char *fmt, va_list ap)
167 if (cap) {
168 fprintf(stderr, "%s: ", cap);
171 vfprintf(stderr, fmt, ap);
174 void AUD_log (const char *cap, const char *fmt, ...)
176 va_list ap;
178 va_start (ap, fmt);
179 AUD_vlog (cap, fmt, ap);
180 va_end (ap);
183 static void audio_print_settings (struct audsettings *as)
185 dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
187 switch (as->fmt) {
188 case AUDIO_FORMAT_S8:
189 AUD_log (NULL, "S8");
190 break;
191 case AUDIO_FORMAT_U8:
192 AUD_log (NULL, "U8");
193 break;
194 case AUDIO_FORMAT_S16:
195 AUD_log (NULL, "S16");
196 break;
197 case AUDIO_FORMAT_U16:
198 AUD_log (NULL, "U16");
199 break;
200 case AUDIO_FORMAT_S32:
201 AUD_log (NULL, "S32");
202 break;
203 case AUDIO_FORMAT_U32:
204 AUD_log (NULL, "U32");
205 break;
206 case AUDIO_FORMAT_F32:
207 AUD_log (NULL, "F32");
208 break;
209 default:
210 AUD_log (NULL, "invalid(%d)", as->fmt);
211 break;
214 AUD_log (NULL, " endianness=");
215 switch (as->endianness) {
216 case 0:
217 AUD_log (NULL, "little");
218 break;
219 case 1:
220 AUD_log (NULL, "big");
221 break;
222 default:
223 AUD_log (NULL, "invalid");
224 break;
226 AUD_log (NULL, "\n");
229 static int audio_validate_settings (struct audsettings *as)
231 int invalid;
233 invalid = as->nchannels < 1;
234 invalid |= as->endianness != 0 && as->endianness != 1;
236 switch (as->fmt) {
237 case AUDIO_FORMAT_S8:
238 case AUDIO_FORMAT_U8:
239 case AUDIO_FORMAT_S16:
240 case AUDIO_FORMAT_U16:
241 case AUDIO_FORMAT_S32:
242 case AUDIO_FORMAT_U32:
243 case AUDIO_FORMAT_F32:
244 break;
245 default:
246 invalid = 1;
247 break;
250 invalid |= as->freq <= 0;
251 return invalid ? -1 : 0;
254 static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
256 int bits = 8;
257 bool is_signed = false, is_float = false;
259 switch (as->fmt) {
260 case AUDIO_FORMAT_S8:
261 is_signed = true;
262 /* fall through */
263 case AUDIO_FORMAT_U8:
264 break;
266 case AUDIO_FORMAT_S16:
267 is_signed = true;
268 /* fall through */
269 case AUDIO_FORMAT_U16:
270 bits = 16;
271 break;
273 case AUDIO_FORMAT_F32:
274 is_float = true;
275 /* fall through */
276 case AUDIO_FORMAT_S32:
277 is_signed = true;
278 /* fall through */
279 case AUDIO_FORMAT_U32:
280 bits = 32;
281 break;
283 default:
284 abort();
286 return info->freq == as->freq
287 && info->nchannels == as->nchannels
288 && info->is_signed == is_signed
289 && info->is_float == is_float
290 && info->bits == bits
291 && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
294 void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
296 int bits = 8, mul;
297 bool is_signed = false, is_float = false;
299 switch (as->fmt) {
300 case AUDIO_FORMAT_S8:
301 is_signed = true;
302 /* fall through */
303 case AUDIO_FORMAT_U8:
304 mul = 1;
305 break;
307 case AUDIO_FORMAT_S16:
308 is_signed = true;
309 /* fall through */
310 case AUDIO_FORMAT_U16:
311 bits = 16;
312 mul = 2;
313 break;
315 case AUDIO_FORMAT_F32:
316 is_float = true;
317 /* fall through */
318 case AUDIO_FORMAT_S32:
319 is_signed = true;
320 /* fall through */
321 case AUDIO_FORMAT_U32:
322 bits = 32;
323 mul = 4;
324 break;
326 default:
327 abort();
330 info->freq = as->freq;
331 info->bits = bits;
332 info->is_signed = is_signed;
333 info->is_float = is_float;
334 info->nchannels = as->nchannels;
335 info->bytes_per_frame = as->nchannels * mul;
336 info->bytes_per_second = info->freq * info->bytes_per_frame;
337 info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
340 void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
342 if (!len) {
343 return;
346 if (info->is_signed || info->is_float) {
347 memset(buf, 0x00, len * info->bytes_per_frame);
348 } else {
349 switch (info->bits) {
350 case 8:
351 memset(buf, 0x80, len * info->bytes_per_frame);
352 break;
354 case 16:
356 int i;
357 uint16_t *p = buf;
358 short s = INT16_MAX;
360 if (info->swap_endianness) {
361 s = bswap16 (s);
364 for (i = 0; i < len * info->nchannels; i++) {
365 p[i] = s;
368 break;
370 case 32:
372 int i;
373 uint32_t *p = buf;
374 int32_t s = INT32_MAX;
376 if (info->swap_endianness) {
377 s = bswap32 (s);
380 for (i = 0; i < len * info->nchannels; i++) {
381 p[i] = s;
384 break;
386 default:
387 AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
388 info->bits);
389 break;
395 * Capture
397 static void noop_conv (struct st_sample *dst, const void *src, int samples)
399 (void) src;
400 (void) dst;
401 (void) samples;
404 static CaptureVoiceOut *audio_pcm_capture_find_specific(AudioState *s,
405 struct audsettings *as)
407 CaptureVoiceOut *cap;
409 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
410 if (audio_pcm_info_eq (&cap->hw.info, as)) {
411 return cap;
414 return NULL;
417 static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
419 struct capture_callback *cb;
421 #ifdef DEBUG_CAPTURE
422 dolog ("notification %d sent\n", cmd);
423 #endif
424 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
425 cb->ops.notify (cb->opaque, cmd);
429 static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
431 if (cap->hw.enabled != enabled) {
432 audcnotification_e cmd;
433 cap->hw.enabled = enabled;
434 cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
435 audio_notify_capture (cap, cmd);
439 static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
441 HWVoiceOut *hw = &cap->hw;
442 SWVoiceOut *sw;
443 int enabled = 0;
445 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
446 if (sw->active) {
447 enabled = 1;
448 break;
451 audio_capture_maybe_changed (cap, enabled);
454 static void audio_detach_capture (HWVoiceOut *hw)
456 SWVoiceCap *sc = hw->cap_head.lh_first;
458 while (sc) {
459 SWVoiceCap *sc1 = sc->entries.le_next;
460 SWVoiceOut *sw = &sc->sw;
461 CaptureVoiceOut *cap = sc->cap;
462 int was_active = sw->active;
464 if (sw->rate) {
465 st_rate_stop (sw->rate);
466 sw->rate = NULL;
469 QLIST_REMOVE (sw, entries);
470 QLIST_REMOVE (sc, entries);
471 g_free (sc);
472 if (was_active) {
473 /* We have removed soft voice from the capture:
474 this might have changed the overall status of the capture
475 since this might have been the only active voice */
476 audio_recalc_and_notify_capture (cap);
478 sc = sc1;
482 static int audio_attach_capture (HWVoiceOut *hw)
484 AudioState *s = hw->s;
485 CaptureVoiceOut *cap;
487 audio_detach_capture (hw);
488 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
489 SWVoiceCap *sc;
490 SWVoiceOut *sw;
491 HWVoiceOut *hw_cap = &cap->hw;
493 sc = g_malloc0(sizeof(*sc));
495 sc->cap = cap;
496 sw = &sc->sw;
497 sw->hw = hw_cap;
498 sw->info = hw->info;
499 sw->empty = 1;
500 sw->active = hw->enabled;
501 sw->conv = noop_conv;
502 sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
503 sw->vol = nominal_volume;
504 sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
505 if (!sw->rate) {
506 dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
507 g_free (sw);
508 return -1;
510 QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
511 QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
512 #ifdef DEBUG_CAPTURE
513 sw->name = g_strdup_printf ("for %p %d,%d,%d",
514 hw, sw->info.freq, sw->info.bits,
515 sw->info.nchannels);
516 dolog ("Added %s active = %d\n", sw->name, sw->active);
517 #endif
518 if (sw->active) {
519 audio_capture_maybe_changed (cap, 1);
522 return 0;
526 * Hard voice (capture)
528 static size_t audio_pcm_hw_find_min_in (HWVoiceIn *hw)
530 SWVoiceIn *sw;
531 size_t m = hw->total_samples_captured;
533 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
534 if (sw->active) {
535 m = MIN (m, sw->total_hw_samples_acquired);
538 return m;
541 static size_t audio_pcm_hw_get_live_in(HWVoiceIn *hw)
543 size_t live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
544 if (audio_bug(__func__, live > hw->conv_buf->size)) {
545 dolog("live=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
546 return 0;
548 return live;
551 static void audio_pcm_hw_clip_out(HWVoiceOut *hw, void *pcm_buf, size_t len)
553 size_t clipped = 0;
554 size_t pos = hw->mix_buf->pos;
556 while (len) {
557 st_sample *src = hw->mix_buf->samples + pos;
558 uint8_t *dst = advance(pcm_buf, clipped * hw->info.bytes_per_frame);
559 size_t samples_till_end_of_buf = hw->mix_buf->size - pos;
560 size_t samples_to_clip = MIN(len, samples_till_end_of_buf);
562 hw->clip(dst, src, samples_to_clip);
564 pos = (pos + samples_to_clip) % hw->mix_buf->size;
565 len -= samples_to_clip;
566 clipped += samples_to_clip;
571 * Soft voice (capture)
573 static size_t audio_pcm_sw_get_rpos_in(SWVoiceIn *sw)
575 HWVoiceIn *hw = sw->hw;
576 ssize_t live = hw->total_samples_captured - sw->total_hw_samples_acquired;
577 ssize_t rpos;
579 if (audio_bug(__func__, live < 0 || live > hw->conv_buf->size)) {
580 dolog("live=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
581 return 0;
584 rpos = hw->conv_buf->pos - live;
585 if (rpos >= 0) {
586 return rpos;
587 } else {
588 return hw->conv_buf->size + rpos;
592 static size_t audio_pcm_sw_read(SWVoiceIn *sw, void *buf, size_t size)
594 HWVoiceIn *hw = sw->hw;
595 size_t samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
596 struct st_sample *src, *dst = sw->buf;
598 rpos = audio_pcm_sw_get_rpos_in(sw) % hw->conv_buf->size;
600 live = hw->total_samples_captured - sw->total_hw_samples_acquired;
601 if (audio_bug(__func__, live > hw->conv_buf->size)) {
602 dolog("live_in=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
603 return 0;
606 samples = size / sw->info.bytes_per_frame;
607 if (!live) {
608 return 0;
611 swlim = (live * sw->ratio) >> 32;
612 swlim = MIN (swlim, samples);
614 while (swlim) {
615 src = hw->conv_buf->samples + rpos;
616 if (hw->conv_buf->pos > rpos) {
617 isamp = hw->conv_buf->pos - rpos;
618 } else {
619 isamp = hw->conv_buf->size - rpos;
622 if (!isamp) {
623 break;
625 osamp = swlim;
627 st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
628 swlim -= osamp;
629 rpos = (rpos + isamp) % hw->conv_buf->size;
630 dst += osamp;
631 ret += osamp;
632 total += isamp;
635 if (hw->pcm_ops && !hw->pcm_ops->volume_in) {
636 mixeng_volume (sw->buf, ret, &sw->vol);
639 sw->clip (buf, sw->buf, ret);
640 sw->total_hw_samples_acquired += total;
641 return ret * sw->info.bytes_per_frame;
645 * Hard voice (playback)
647 static size_t audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
649 SWVoiceOut *sw;
650 size_t m = SIZE_MAX;
651 int nb_live = 0;
653 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
654 if (sw->active || !sw->empty) {
655 m = MIN (m, sw->total_hw_samples_mixed);
656 nb_live += 1;
660 *nb_livep = nb_live;
661 return m;
664 static size_t audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
666 size_t smin;
667 int nb_live1;
669 smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
670 if (nb_live) {
671 *nb_live = nb_live1;
674 if (nb_live1) {
675 size_t live = smin;
677 if (audio_bug(__func__, live > hw->mix_buf->size)) {
678 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
679 return 0;
681 return live;
683 return 0;
687 * Soft voice (playback)
689 static size_t audio_pcm_sw_write(SWVoiceOut *sw, void *buf, size_t size)
691 size_t hwsamples, samples, isamp, osamp, wpos, live, dead, left, swlim, blck;
692 size_t ret = 0, pos = 0, total = 0;
694 if (!sw) {
695 return size;
698 hwsamples = sw->hw->mix_buf->size;
700 live = sw->total_hw_samples_mixed;
701 if (audio_bug(__func__, live > hwsamples)) {
702 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hwsamples);
703 return 0;
706 if (live == hwsamples) {
707 #ifdef DEBUG_OUT
708 dolog ("%s is full %zu\n", sw->name, live);
709 #endif
710 return 0;
713 wpos = (sw->hw->mix_buf->pos + live) % hwsamples;
714 samples = size / sw->info.bytes_per_frame;
716 dead = hwsamples - live;
717 swlim = ((int64_t) dead << 32) / sw->ratio;
718 swlim = MIN (swlim, samples);
719 if (swlim) {
720 sw->conv (sw->buf, buf, swlim);
722 if (sw->hw->pcm_ops && !sw->hw->pcm_ops->volume_out) {
723 mixeng_volume (sw->buf, swlim, &sw->vol);
727 while (swlim) {
728 dead = hwsamples - live;
729 left = hwsamples - wpos;
730 blck = MIN (dead, left);
731 if (!blck) {
732 break;
734 isamp = swlim;
735 osamp = blck;
736 st_rate_flow_mix (
737 sw->rate,
738 sw->buf + pos,
739 sw->hw->mix_buf->samples + wpos,
740 &isamp,
741 &osamp
743 ret += isamp;
744 swlim -= isamp;
745 pos += isamp;
746 live += osamp;
747 wpos = (wpos + osamp) % hwsamples;
748 total += osamp;
751 sw->total_hw_samples_mixed += total;
752 sw->empty = sw->total_hw_samples_mixed == 0;
754 #ifdef DEBUG_OUT
755 dolog (
756 "%s: write size %zu ret %zu total sw %zu\n",
757 SW_NAME (sw),
758 size / sw->info.bytes_per_frame,
759 ret,
760 sw->total_hw_samples_mixed
762 #endif
764 return ret * sw->info.bytes_per_frame;
767 #ifdef DEBUG_AUDIO
768 static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
770 dolog("%s: bits %d, sign %d, float %d, freq %d, nchan %d\n",
771 cap, info->bits, info->is_signed, info->is_float, info->freq,
772 info->nchannels);
774 #endif
776 #define DAC
777 #include "audio_template.h"
778 #undef DAC
779 #include "audio_template.h"
782 * Timer
784 static int audio_is_timer_needed(AudioState *s)
786 HWVoiceIn *hwi = NULL;
787 HWVoiceOut *hwo = NULL;
789 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
790 if (!hwo->poll_mode) {
791 return 1;
794 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
795 if (!hwi->poll_mode) {
796 return 1;
799 return 0;
802 static void audio_reset_timer (AudioState *s)
804 if (audio_is_timer_needed(s)) {
805 timer_mod_anticipate_ns(s->ts,
806 qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
807 if (!s->timer_running) {
808 s->timer_running = true;
809 s->timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
810 trace_audio_timer_start(s->period_ticks / SCALE_MS);
812 } else {
813 timer_del(s->ts);
814 if (s->timer_running) {
815 s->timer_running = false;
816 trace_audio_timer_stop();
821 static void audio_timer (void *opaque)
823 int64_t now, diff;
824 AudioState *s = opaque;
826 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
827 diff = now - s->timer_last;
828 if (diff > s->period_ticks * 3 / 2) {
829 trace_audio_timer_delayed(diff / SCALE_MS);
831 s->timer_last = now;
833 audio_run(s, "timer");
834 audio_reset_timer(s);
838 * Public API
840 size_t AUD_write(SWVoiceOut *sw, void *buf, size_t size)
842 HWVoiceOut *hw;
844 if (!sw) {
845 /* XXX: Consider options */
846 return size;
848 hw = sw->hw;
850 if (!hw->enabled) {
851 dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
852 return 0;
855 if (audio_get_pdo_out(hw->s->dev)->mixing_engine) {
856 return audio_pcm_sw_write(sw, buf, size);
857 } else {
858 return hw->pcm_ops->write(hw, buf, size);
862 size_t AUD_read(SWVoiceIn *sw, void *buf, size_t size)
864 HWVoiceIn *hw;
866 if (!sw) {
867 /* XXX: Consider options */
868 return size;
870 hw = sw->hw;
872 if (!hw->enabled) {
873 dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
874 return 0;
877 if (audio_get_pdo_in(hw->s->dev)->mixing_engine) {
878 return audio_pcm_sw_read(sw, buf, size);
879 } else {
880 return hw->pcm_ops->read(hw, buf, size);
884 int AUD_get_buffer_size_out(SWVoiceOut *sw)
886 return sw->hw->samples * sw->hw->info.bytes_per_frame;
889 void AUD_set_active_out (SWVoiceOut *sw, int on)
891 HWVoiceOut *hw;
893 if (!sw) {
894 return;
897 hw = sw->hw;
898 if (sw->active != on) {
899 AudioState *s = sw->s;
900 SWVoiceOut *temp_sw;
901 SWVoiceCap *sc;
903 if (on) {
904 hw->pending_disable = 0;
905 if (!hw->enabled) {
906 hw->enabled = 1;
907 if (s->vm_running) {
908 if (hw->pcm_ops->enable_out) {
909 hw->pcm_ops->enable_out(hw, true);
911 audio_reset_timer (s);
914 } else {
915 if (hw->enabled) {
916 int nb_active = 0;
918 for (temp_sw = hw->sw_head.lh_first; temp_sw;
919 temp_sw = temp_sw->entries.le_next) {
920 nb_active += temp_sw->active != 0;
923 hw->pending_disable = nb_active == 1;
927 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
928 sc->sw.active = hw->enabled;
929 if (hw->enabled) {
930 audio_capture_maybe_changed (sc->cap, 1);
933 sw->active = on;
937 void AUD_set_active_in (SWVoiceIn *sw, int on)
939 HWVoiceIn *hw;
941 if (!sw) {
942 return;
945 hw = sw->hw;
946 if (sw->active != on) {
947 AudioState *s = sw->s;
948 SWVoiceIn *temp_sw;
950 if (on) {
951 if (!hw->enabled) {
952 hw->enabled = 1;
953 if (s->vm_running) {
954 if (hw->pcm_ops->enable_in) {
955 hw->pcm_ops->enable_in(hw, true);
957 audio_reset_timer (s);
960 sw->total_hw_samples_acquired = hw->total_samples_captured;
961 } else {
962 if (hw->enabled) {
963 int nb_active = 0;
965 for (temp_sw = hw->sw_head.lh_first; temp_sw;
966 temp_sw = temp_sw->entries.le_next) {
967 nb_active += temp_sw->active != 0;
970 if (nb_active == 1) {
971 hw->enabled = 0;
972 if (hw->pcm_ops->enable_in) {
973 hw->pcm_ops->enable_in(hw, false);
978 sw->active = on;
982 static size_t audio_get_avail (SWVoiceIn *sw)
984 size_t live;
986 if (!sw) {
987 return 0;
990 live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
991 if (audio_bug(__func__, live > sw->hw->conv_buf->size)) {
992 dolog("live=%zu sw->hw->conv_buf->size=%zu\n", live,
993 sw->hw->conv_buf->size);
994 return 0;
997 ldebug (
998 "%s: get_avail live %zu ret %" PRId64 "\n",
999 SW_NAME (sw),
1000 live, (((int64_t) live << 32) / sw->ratio) * sw->info.bytes_per_frame
1003 return (((int64_t) live << 32) / sw->ratio) * sw->info.bytes_per_frame;
1006 static size_t audio_get_free(SWVoiceOut *sw)
1008 size_t live, dead;
1010 if (!sw) {
1011 return 0;
1014 live = sw->total_hw_samples_mixed;
1016 if (audio_bug(__func__, live > sw->hw->mix_buf->size)) {
1017 dolog("live=%zu sw->hw->mix_buf->size=%zu\n", live,
1018 sw->hw->mix_buf->size);
1019 return 0;
1022 dead = sw->hw->mix_buf->size - live;
1024 #ifdef DEBUG_OUT
1025 dolog ("%s: get_free live %zu dead %zu ret %" PRId64 "\n",
1026 SW_NAME (sw),
1027 live, dead, (((int64_t) dead << 32) / sw->ratio) *
1028 sw->info.bytes_per_frame);
1029 #endif
1031 return (((int64_t) dead << 32) / sw->ratio) * sw->info.bytes_per_frame;
1034 static void audio_capture_mix_and_clear(HWVoiceOut *hw, size_t rpos,
1035 size_t samples)
1037 size_t n;
1039 if (hw->enabled) {
1040 SWVoiceCap *sc;
1042 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1043 SWVoiceOut *sw = &sc->sw;
1044 int rpos2 = rpos;
1046 n = samples;
1047 while (n) {
1048 size_t till_end_of_hw = hw->mix_buf->size - rpos2;
1049 size_t to_write = MIN(till_end_of_hw, n);
1050 size_t bytes = to_write * hw->info.bytes_per_frame;
1051 size_t written;
1053 sw->buf = hw->mix_buf->samples + rpos2;
1054 written = audio_pcm_sw_write (sw, NULL, bytes);
1055 if (written - bytes) {
1056 dolog("Could not mix %zu bytes into a capture "
1057 "buffer, mixed %zu\n",
1058 bytes, written);
1059 break;
1061 n -= to_write;
1062 rpos2 = (rpos2 + to_write) % hw->mix_buf->size;
1067 n = MIN(samples, hw->mix_buf->size - rpos);
1068 mixeng_clear(hw->mix_buf->samples + rpos, n);
1069 mixeng_clear(hw->mix_buf->samples, samples - n);
1072 static size_t audio_pcm_hw_run_out(HWVoiceOut *hw, size_t live)
1074 size_t clipped = 0;
1076 while (live) {
1077 size_t size = live * hw->info.bytes_per_frame;
1078 size_t decr, proc;
1079 void *buf = hw->pcm_ops->get_buffer_out(hw, &size);
1081 if (size == 0) {
1082 break;
1085 decr = MIN(size / hw->info.bytes_per_frame, live);
1086 if (buf) {
1087 audio_pcm_hw_clip_out(hw, buf, decr);
1089 proc = hw->pcm_ops->put_buffer_out(hw, buf,
1090 decr * hw->info.bytes_per_frame) /
1091 hw->info.bytes_per_frame;
1093 live -= proc;
1094 clipped += proc;
1095 hw->mix_buf->pos = (hw->mix_buf->pos + proc) % hw->mix_buf->size;
1097 if (proc == 0 || proc < decr) {
1098 break;
1102 if (hw->pcm_ops->run_buffer_out) {
1103 hw->pcm_ops->run_buffer_out(hw);
1106 return clipped;
1109 static void audio_run_out (AudioState *s)
1111 HWVoiceOut *hw = NULL;
1112 SWVoiceOut *sw;
1114 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1115 while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1116 /* there is exactly 1 sw for each hw with no mixeng */
1117 sw = hw->sw_head.lh_first;
1119 if (hw->pending_disable) {
1120 hw->enabled = 0;
1121 hw->pending_disable = 0;
1122 if (hw->pcm_ops->enable_out) {
1123 hw->pcm_ops->enable_out(hw, false);
1127 if (sw->active) {
1128 sw->callback.fn(sw->callback.opaque, INT_MAX);
1131 return;
1134 while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1135 size_t played, live, prev_rpos, free;
1136 int nb_live;
1138 live = audio_pcm_hw_get_live_out (hw, &nb_live);
1139 if (!nb_live) {
1140 live = 0;
1143 if (audio_bug(__func__, live > hw->mix_buf->size)) {
1144 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
1145 continue;
1148 if (hw->pending_disable && !nb_live) {
1149 SWVoiceCap *sc;
1150 #ifdef DEBUG_OUT
1151 dolog ("Disabling voice\n");
1152 #endif
1153 hw->enabled = 0;
1154 hw->pending_disable = 0;
1155 if (hw->pcm_ops->enable_out) {
1156 hw->pcm_ops->enable_out(hw, false);
1158 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1159 sc->sw.active = 0;
1160 audio_recalc_and_notify_capture (sc->cap);
1162 continue;
1165 if (!live) {
1166 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1167 if (sw->active) {
1168 free = audio_get_free (sw);
1169 if (free > 0) {
1170 sw->callback.fn (sw->callback.opaque, free);
1174 if (hw->pcm_ops->run_buffer_out) {
1175 hw->pcm_ops->run_buffer_out(hw);
1177 continue;
1180 prev_rpos = hw->mix_buf->pos;
1181 played = audio_pcm_hw_run_out(hw, live);
1182 replay_audio_out(&played);
1183 if (audio_bug(__func__, hw->mix_buf->pos >= hw->mix_buf->size)) {
1184 dolog("hw->mix_buf->pos=%zu hw->mix_buf->size=%zu played=%zu\n",
1185 hw->mix_buf->pos, hw->mix_buf->size, played);
1186 hw->mix_buf->pos = 0;
1189 #ifdef DEBUG_OUT
1190 dolog("played=%zu\n", played);
1191 #endif
1193 if (played) {
1194 hw->ts_helper += played;
1195 audio_capture_mix_and_clear (hw, prev_rpos, played);
1198 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1199 if (!sw->active && sw->empty) {
1200 continue;
1203 if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1204 dolog("played=%zu sw->total_hw_samples_mixed=%zu\n",
1205 played, sw->total_hw_samples_mixed);
1206 played = sw->total_hw_samples_mixed;
1209 sw->total_hw_samples_mixed -= played;
1211 if (!sw->total_hw_samples_mixed) {
1212 sw->empty = 1;
1215 if (sw->active) {
1216 free = audio_get_free (sw);
1217 if (free > 0) {
1218 sw->callback.fn (sw->callback.opaque, free);
1225 static size_t audio_pcm_hw_run_in(HWVoiceIn *hw, size_t samples)
1227 size_t conv = 0;
1228 STSampleBuffer *conv_buf = hw->conv_buf;
1230 if (hw->pcm_ops->run_buffer_in) {
1231 hw->pcm_ops->run_buffer_in(hw);
1234 while (samples) {
1235 size_t proc;
1236 size_t size = samples * hw->info.bytes_per_frame;
1237 void *buf = hw->pcm_ops->get_buffer_in(hw, &size);
1239 assert(size % hw->info.bytes_per_frame == 0);
1240 if (size == 0) {
1241 break;
1244 proc = MIN(size / hw->info.bytes_per_frame,
1245 conv_buf->size - conv_buf->pos);
1247 hw->conv(conv_buf->samples + conv_buf->pos, buf, proc);
1248 conv_buf->pos = (conv_buf->pos + proc) % conv_buf->size;
1250 samples -= proc;
1251 conv += proc;
1252 hw->pcm_ops->put_buffer_in(hw, buf, proc * hw->info.bytes_per_frame);
1255 return conv;
1258 static void audio_run_in (AudioState *s)
1260 HWVoiceIn *hw = NULL;
1262 if (!audio_get_pdo_in(s->dev)->mixing_engine) {
1263 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1264 /* there is exactly 1 sw for each hw with no mixeng */
1265 SWVoiceIn *sw = hw->sw_head.lh_first;
1266 if (sw->active) {
1267 sw->callback.fn(sw->callback.opaque, INT_MAX);
1270 return;
1273 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1274 SWVoiceIn *sw;
1275 size_t captured = 0, min;
1277 if (replay_mode != REPLAY_MODE_PLAY) {
1278 captured = audio_pcm_hw_run_in(
1279 hw, hw->conv_buf->size - audio_pcm_hw_get_live_in(hw));
1281 replay_audio_in(&captured, hw->conv_buf->samples, &hw->conv_buf->pos,
1282 hw->conv_buf->size);
1284 min = audio_pcm_hw_find_min_in (hw);
1285 hw->total_samples_captured += captured - min;
1286 hw->ts_helper += captured;
1288 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1289 sw->total_hw_samples_acquired -= min;
1291 if (sw->active) {
1292 size_t avail;
1294 avail = audio_get_avail (sw);
1295 if (avail > 0) {
1296 sw->callback.fn (sw->callback.opaque, avail);
1303 static void audio_run_capture (AudioState *s)
1305 CaptureVoiceOut *cap;
1307 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1308 size_t live, rpos, captured;
1309 HWVoiceOut *hw = &cap->hw;
1310 SWVoiceOut *sw;
1312 captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1313 rpos = hw->mix_buf->pos;
1314 while (live) {
1315 size_t left = hw->mix_buf->size - rpos;
1316 size_t to_capture = MIN(live, left);
1317 struct st_sample *src;
1318 struct capture_callback *cb;
1320 src = hw->mix_buf->samples + rpos;
1321 hw->clip (cap->buf, src, to_capture);
1322 mixeng_clear (src, to_capture);
1324 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1325 cb->ops.capture (cb->opaque, cap->buf,
1326 to_capture * hw->info.bytes_per_frame);
1328 rpos = (rpos + to_capture) % hw->mix_buf->size;
1329 live -= to_capture;
1331 hw->mix_buf->pos = rpos;
1333 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1334 if (!sw->active && sw->empty) {
1335 continue;
1338 if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1339 dolog("captured=%zu sw->total_hw_samples_mixed=%zu\n",
1340 captured, sw->total_hw_samples_mixed);
1341 captured = sw->total_hw_samples_mixed;
1344 sw->total_hw_samples_mixed -= captured;
1345 sw->empty = sw->total_hw_samples_mixed == 0;
1350 void audio_run(AudioState *s, const char *msg)
1352 audio_run_out(s);
1353 audio_run_in(s);
1354 audio_run_capture(s);
1356 #ifdef DEBUG_POLL
1358 static double prevtime;
1359 double currtime;
1360 struct timeval tv;
1362 if (gettimeofday (&tv, NULL)) {
1363 perror ("audio_run: gettimeofday");
1364 return;
1367 currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1368 dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1369 prevtime = currtime;
1371 #endif
1374 void audio_generic_run_buffer_in(HWVoiceIn *hw)
1376 if (unlikely(!hw->buf_emul)) {
1377 hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1378 hw->buf_emul = g_malloc(hw->size_emul);
1379 hw->pos_emul = hw->pending_emul = 0;
1382 while (hw->pending_emul < hw->size_emul) {
1383 size_t read_len = MIN(hw->size_emul - hw->pos_emul,
1384 hw->size_emul - hw->pending_emul);
1385 size_t read = hw->pcm_ops->read(hw, hw->buf_emul + hw->pos_emul,
1386 read_len);
1387 hw->pending_emul += read;
1388 hw->pos_emul = (hw->pos_emul + read) % hw->size_emul;
1389 if (read < read_len) {
1390 break;
1395 void *audio_generic_get_buffer_in(HWVoiceIn *hw, size_t *size)
1397 ssize_t start = (ssize_t)hw->pos_emul - hw->pending_emul;
1399 if (start < 0) {
1400 start += hw->size_emul;
1402 assert(start >= 0 && start < hw->size_emul);
1404 *size = MIN(*size, hw->pending_emul);
1405 *size = MIN(*size, hw->size_emul - start);
1406 return hw->buf_emul + start;
1409 void audio_generic_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
1411 assert(size <= hw->pending_emul);
1412 hw->pending_emul -= size;
1415 void audio_generic_run_buffer_out(HWVoiceOut *hw)
1417 while (hw->pending_emul) {
1418 size_t write_len, written;
1419 ssize_t start = ((ssize_t) hw->pos_emul) - hw->pending_emul;
1421 if (start < 0) {
1422 start += hw->size_emul;
1424 assert(start >= 0 && start < hw->size_emul);
1426 write_len = MIN(hw->pending_emul, hw->size_emul - start);
1428 written = hw->pcm_ops->write(hw, hw->buf_emul + start, write_len);
1429 hw->pending_emul -= written;
1431 if (written < write_len) {
1432 break;
1437 void *audio_generic_get_buffer_out(HWVoiceOut *hw, size_t *size)
1439 if (unlikely(!hw->buf_emul)) {
1440 hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1441 hw->buf_emul = g_malloc(hw->size_emul);
1442 hw->pos_emul = hw->pending_emul = 0;
1445 *size = MIN(hw->size_emul - hw->pending_emul,
1446 hw->size_emul - hw->pos_emul);
1447 return hw->buf_emul + hw->pos_emul;
1450 size_t audio_generic_put_buffer_out(HWVoiceOut *hw, void *buf, size_t size)
1452 assert(buf == hw->buf_emul + hw->pos_emul &&
1453 size + hw->pending_emul <= hw->size_emul);
1455 hw->pending_emul += size;
1456 hw->pos_emul = (hw->pos_emul + size) % hw->size_emul;
1458 return size;
1461 size_t audio_generic_write(HWVoiceOut *hw, void *buf, size_t size)
1463 size_t total = 0;
1465 while (total < size) {
1466 size_t dst_size = size - total;
1467 size_t copy_size, proc;
1468 void *dst = hw->pcm_ops->get_buffer_out(hw, &dst_size);
1470 if (dst_size == 0) {
1471 break;
1474 copy_size = MIN(size - total, dst_size);
1475 if (dst) {
1476 memcpy(dst, (char *)buf + total, copy_size);
1478 proc = hw->pcm_ops->put_buffer_out(hw, dst, copy_size);
1479 total += proc;
1481 if (proc == 0 || proc < copy_size) {
1482 break;
1486 if (hw->pcm_ops->run_buffer_out) {
1487 hw->pcm_ops->run_buffer_out(hw);
1490 return total;
1493 size_t audio_generic_read(HWVoiceIn *hw, void *buf, size_t size)
1495 size_t total = 0;
1497 if (hw->pcm_ops->run_buffer_in) {
1498 hw->pcm_ops->run_buffer_in(hw);
1501 while (total < size) {
1502 size_t src_size = size - total;
1503 void *src = hw->pcm_ops->get_buffer_in(hw, &src_size);
1505 if (src_size == 0) {
1506 break;
1509 memcpy((char *)buf + total, src, src_size);
1510 hw->pcm_ops->put_buffer_in(hw, src, src_size);
1511 total += src_size;
1514 return total;
1517 static int audio_driver_init(AudioState *s, struct audio_driver *drv,
1518 bool msg, Audiodev *dev)
1520 s->drv_opaque = drv->init(dev);
1522 if (s->drv_opaque) {
1523 if (!drv->pcm_ops->get_buffer_in) {
1524 drv->pcm_ops->get_buffer_in = audio_generic_get_buffer_in;
1525 drv->pcm_ops->put_buffer_in = audio_generic_put_buffer_in;
1527 if (!drv->pcm_ops->get_buffer_out) {
1528 drv->pcm_ops->get_buffer_out = audio_generic_get_buffer_out;
1529 drv->pcm_ops->put_buffer_out = audio_generic_put_buffer_out;
1532 audio_init_nb_voices_out(s, drv);
1533 audio_init_nb_voices_in(s, drv);
1534 s->drv = drv;
1535 return 0;
1536 } else {
1537 if (msg) {
1538 dolog("Could not init `%s' audio driver\n", drv->name);
1540 return -1;
1544 static void audio_vm_change_state_handler (void *opaque, bool running,
1545 RunState state)
1547 AudioState *s = opaque;
1548 HWVoiceOut *hwo = NULL;
1549 HWVoiceIn *hwi = NULL;
1551 s->vm_running = running;
1552 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
1553 if (hwo->pcm_ops->enable_out) {
1554 hwo->pcm_ops->enable_out(hwo, running);
1558 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
1559 if (hwi->pcm_ops->enable_in) {
1560 hwi->pcm_ops->enable_in(hwi, running);
1563 audio_reset_timer (s);
1566 static void free_audio_state(AudioState *s)
1568 HWVoiceOut *hwo, *hwon;
1569 HWVoiceIn *hwi, *hwin;
1571 QLIST_FOREACH_SAFE(hwo, &s->hw_head_out, entries, hwon) {
1572 SWVoiceCap *sc;
1574 if (hwo->enabled && hwo->pcm_ops->enable_out) {
1575 hwo->pcm_ops->enable_out(hwo, false);
1577 hwo->pcm_ops->fini_out (hwo);
1579 for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1580 CaptureVoiceOut *cap = sc->cap;
1581 struct capture_callback *cb;
1583 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1584 cb->ops.destroy (cb->opaque);
1587 QLIST_REMOVE(hwo, entries);
1590 QLIST_FOREACH_SAFE(hwi, &s->hw_head_in, entries, hwin) {
1591 if (hwi->enabled && hwi->pcm_ops->enable_in) {
1592 hwi->pcm_ops->enable_in(hwi, false);
1594 hwi->pcm_ops->fini_in (hwi);
1595 QLIST_REMOVE(hwi, entries);
1598 if (s->drv) {
1599 s->drv->fini (s->drv_opaque);
1600 s->drv = NULL;
1603 if (s->dev) {
1604 qapi_free_Audiodev(s->dev);
1605 s->dev = NULL;
1608 if (s->ts) {
1609 timer_free(s->ts);
1610 s->ts = NULL;
1613 g_free(s);
1616 void audio_cleanup(void)
1618 while (!QTAILQ_EMPTY(&audio_states)) {
1619 AudioState *s = QTAILQ_FIRST(&audio_states);
1620 QTAILQ_REMOVE(&audio_states, s, list);
1621 free_audio_state(s);
1625 static const VMStateDescription vmstate_audio = {
1626 .name = "audio",
1627 .version_id = 1,
1628 .minimum_version_id = 1,
1629 .fields = (VMStateField[]) {
1630 VMSTATE_END_OF_LIST()
1634 static void audio_validate_opts(Audiodev *dev, Error **errp);
1636 static AudiodevListEntry *audiodev_find(
1637 AudiodevListHead *head, const char *drvname)
1639 AudiodevListEntry *e;
1640 QSIMPLEQ_FOREACH(e, head, next) {
1641 if (strcmp(AudiodevDriver_str(e->dev->driver), drvname) == 0) {
1642 return e;
1646 return NULL;
1650 * if we have dev, this function was called because of an -audiodev argument =>
1651 * initialize a new state with it
1652 * if dev == NULL => legacy implicit initialization, return the already created
1653 * state or create a new one
1655 static AudioState *audio_init(Audiodev *dev, const char *name)
1657 static bool atexit_registered;
1658 size_t i;
1659 int done = 0;
1660 const char *drvname = NULL;
1661 VMChangeStateEntry *e;
1662 AudioState *s;
1663 struct audio_driver *driver;
1664 /* silence gcc warning about uninitialized variable */
1665 AudiodevListHead head = QSIMPLEQ_HEAD_INITIALIZER(head);
1667 if (using_spice) {
1669 * When using spice allow the spice audio driver being picked
1670 * as default.
1672 * Temporary hack. Using audio devices without explicit
1673 * audiodev= property is already deprecated. Same goes for
1674 * the -soundhw switch. Once this support gets finally
1675 * removed we can also drop the concept of a default audio
1676 * backend and this can go away.
1678 driver = audio_driver_lookup("spice");
1679 if (driver) {
1680 driver->can_be_default = 1;
1684 if (dev) {
1685 /* -audiodev option */
1686 legacy_config = false;
1687 drvname = AudiodevDriver_str(dev->driver);
1688 } else if (!QTAILQ_EMPTY(&audio_states)) {
1689 if (!legacy_config) {
1690 dolog("Device %s: audiodev default parameter is deprecated, please "
1691 "specify audiodev=%s\n", name,
1692 QTAILQ_FIRST(&audio_states)->dev->id);
1694 return QTAILQ_FIRST(&audio_states);
1695 } else {
1696 /* legacy implicit initialization */
1697 head = audio_handle_legacy_opts();
1699 * In case of legacy initialization, all Audiodevs in the list will have
1700 * the same configuration (except the driver), so it doesn't matter which
1701 * one we chose. We need an Audiodev to set up AudioState before we can
1702 * init a driver. Also note that dev at this point is still in the
1703 * list.
1705 dev = QSIMPLEQ_FIRST(&head)->dev;
1706 audio_validate_opts(dev, &error_abort);
1709 s = g_malloc0(sizeof(AudioState));
1710 s->dev = dev;
1712 QLIST_INIT (&s->hw_head_out);
1713 QLIST_INIT (&s->hw_head_in);
1714 QLIST_INIT (&s->cap_head);
1715 if (!atexit_registered) {
1716 atexit(audio_cleanup);
1717 atexit_registered = true;
1719 QTAILQ_INSERT_TAIL(&audio_states, s, list);
1721 s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1723 s->nb_hw_voices_out = audio_get_pdo_out(dev)->voices;
1724 s->nb_hw_voices_in = audio_get_pdo_in(dev)->voices;
1726 if (s->nb_hw_voices_out <= 0) {
1727 dolog ("Bogus number of playback voices %d, setting to 1\n",
1728 s->nb_hw_voices_out);
1729 s->nb_hw_voices_out = 1;
1732 if (s->nb_hw_voices_in <= 0) {
1733 dolog ("Bogus number of capture voices %d, setting to 0\n",
1734 s->nb_hw_voices_in);
1735 s->nb_hw_voices_in = 0;
1738 if (drvname) {
1739 driver = audio_driver_lookup(drvname);
1740 if (driver) {
1741 done = !audio_driver_init(s, driver, true, dev);
1742 } else {
1743 dolog ("Unknown audio driver `%s'\n", drvname);
1745 } else {
1746 for (i = 0; audio_prio_list[i]; i++) {
1747 AudiodevListEntry *e = audiodev_find(&head, audio_prio_list[i]);
1748 driver = audio_driver_lookup(audio_prio_list[i]);
1750 if (e && driver) {
1751 s->dev = dev = e->dev;
1752 audio_validate_opts(dev, &error_abort);
1753 done = !audio_driver_init(s, driver, false, dev);
1754 if (done) {
1755 e->dev = NULL;
1756 break;
1761 audio_free_audiodev_list(&head);
1763 if (!done) {
1764 driver = audio_driver_lookup("none");
1765 done = !audio_driver_init(s, driver, false, dev);
1766 assert(done);
1767 dolog("warning: Using timer based audio emulation\n");
1770 if (dev->timer_period <= 0) {
1771 s->period_ticks = 1;
1772 } else {
1773 s->period_ticks = dev->timer_period * (int64_t)SCALE_US;
1776 e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1777 if (!e) {
1778 dolog ("warning: Could not register change state handler\n"
1779 "(Audio can continue looping even after stopping the VM)\n");
1782 QLIST_INIT (&s->card_head);
1783 vmstate_register (NULL, 0, &vmstate_audio, s);
1784 return s;
1787 void audio_free_audiodev_list(AudiodevListHead *head)
1789 AudiodevListEntry *e;
1790 while ((e = QSIMPLEQ_FIRST(head))) {
1791 QSIMPLEQ_REMOVE_HEAD(head, next);
1792 qapi_free_Audiodev(e->dev);
1793 g_free(e);
1797 void AUD_register_card (const char *name, QEMUSoundCard *card)
1799 if (!card->state) {
1800 card->state = audio_init(NULL, name);
1803 card->name = g_strdup (name);
1804 memset (&card->entries, 0, sizeof (card->entries));
1805 QLIST_INSERT_HEAD(&card->state->card_head, card, entries);
1808 void AUD_remove_card (QEMUSoundCard *card)
1810 QLIST_REMOVE (card, entries);
1811 g_free (card->name);
1815 CaptureVoiceOut *AUD_add_capture(
1816 AudioState *s,
1817 struct audsettings *as,
1818 struct audio_capture_ops *ops,
1819 void *cb_opaque
1822 CaptureVoiceOut *cap;
1823 struct capture_callback *cb;
1825 if (!s) {
1826 if (!legacy_config) {
1827 dolog("Capturing without setting an audiodev is deprecated\n");
1829 s = audio_init(NULL, NULL);
1832 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1833 dolog("Can't capture with mixeng disabled\n");
1834 return NULL;
1837 if (audio_validate_settings (as)) {
1838 dolog ("Invalid settings were passed when trying to add capture\n");
1839 audio_print_settings (as);
1840 return NULL;
1843 cb = g_malloc0(sizeof(*cb));
1844 cb->ops = *ops;
1845 cb->opaque = cb_opaque;
1847 cap = audio_pcm_capture_find_specific(s, as);
1848 if (cap) {
1849 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1850 return cap;
1851 } else {
1852 HWVoiceOut *hw;
1853 CaptureVoiceOut *cap;
1855 cap = g_malloc0(sizeof(*cap));
1857 hw = &cap->hw;
1858 hw->s = s;
1859 QLIST_INIT (&hw->sw_head);
1860 QLIST_INIT (&cap->cb_head);
1862 /* XXX find a more elegant way */
1863 hw->samples = 4096 * 4;
1864 audio_pcm_hw_alloc_resources_out(hw);
1866 audio_pcm_init_info (&hw->info, as);
1868 cap->buf = g_malloc0_n(hw->mix_buf->size, hw->info.bytes_per_frame);
1870 if (hw->info.is_float) {
1871 hw->clip = mixeng_clip_float[hw->info.nchannels == 2];
1872 } else {
1873 hw->clip = mixeng_clip
1874 [hw->info.nchannels == 2]
1875 [hw->info.is_signed]
1876 [hw->info.swap_endianness]
1877 [audio_bits_to_index(hw->info.bits)];
1880 QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1881 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1883 QLIST_FOREACH(hw, &s->hw_head_out, entries) {
1884 audio_attach_capture (hw);
1886 return cap;
1890 void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1892 struct capture_callback *cb;
1894 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1895 if (cb->opaque == cb_opaque) {
1896 cb->ops.destroy (cb_opaque);
1897 QLIST_REMOVE (cb, entries);
1898 g_free (cb);
1900 if (!cap->cb_head.lh_first) {
1901 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
1903 while (sw) {
1904 SWVoiceCap *sc = (SWVoiceCap *) sw;
1905 #ifdef DEBUG_CAPTURE
1906 dolog ("freeing %s\n", sw->name);
1907 #endif
1909 sw1 = sw->entries.le_next;
1910 if (sw->rate) {
1911 st_rate_stop (sw->rate);
1912 sw->rate = NULL;
1914 QLIST_REMOVE (sw, entries);
1915 QLIST_REMOVE (sc, entries);
1916 g_free (sc);
1917 sw = sw1;
1919 QLIST_REMOVE (cap, entries);
1920 g_free (cap->hw.mix_buf);
1921 g_free (cap->buf);
1922 g_free (cap);
1924 return;
1929 void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
1931 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1932 audio_set_volume_out(sw, &vol);
1935 void audio_set_volume_out(SWVoiceOut *sw, Volume *vol)
1937 if (sw) {
1938 HWVoiceOut *hw = sw->hw;
1940 sw->vol.mute = vol->mute;
1941 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
1942 sw->vol.r = nominal_volume.l * vol->vol[vol->channels > 1 ? 1 : 0] /
1943 255;
1945 if (hw->pcm_ops->volume_out) {
1946 hw->pcm_ops->volume_out(hw, vol);
1951 void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
1953 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1954 audio_set_volume_in(sw, &vol);
1957 void audio_set_volume_in(SWVoiceIn *sw, Volume *vol)
1959 if (sw) {
1960 HWVoiceIn *hw = sw->hw;
1962 sw->vol.mute = vol->mute;
1963 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
1964 sw->vol.r = nominal_volume.r * vol->vol[vol->channels > 1 ? 1 : 0] /
1965 255;
1967 if (hw->pcm_ops->volume_in) {
1968 hw->pcm_ops->volume_in(hw, vol);
1973 void audio_create_pdos(Audiodev *dev)
1975 switch (dev->driver) {
1976 #define CASE(DRIVER, driver, pdo_name) \
1977 case AUDIODEV_DRIVER_##DRIVER: \
1978 if (!dev->u.driver.has_in) { \
1979 dev->u.driver.in = g_malloc0( \
1980 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
1981 dev->u.driver.has_in = true; \
1983 if (!dev->u.driver.has_out) { \
1984 dev->u.driver.out = g_malloc0( \
1985 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
1986 dev->u.driver.has_out = true; \
1988 break
1990 CASE(NONE, none, );
1991 CASE(ALSA, alsa, Alsa);
1992 CASE(COREAUDIO, coreaudio, Coreaudio);
1993 CASE(DSOUND, dsound, );
1994 CASE(JACK, jack, Jack);
1995 CASE(OSS, oss, Oss);
1996 CASE(PA, pa, Pa);
1997 CASE(SDL, sdl, Sdl);
1998 CASE(SPICE, spice, );
1999 CASE(WAV, wav, );
2001 case AUDIODEV_DRIVER__MAX:
2002 abort();
2006 static void audio_validate_per_direction_opts(
2007 AudiodevPerDirectionOptions *pdo, Error **errp)
2009 if (!pdo->has_mixing_engine) {
2010 pdo->has_mixing_engine = true;
2011 pdo->mixing_engine = true;
2013 if (!pdo->has_fixed_settings) {
2014 pdo->has_fixed_settings = true;
2015 pdo->fixed_settings = pdo->mixing_engine;
2017 if (!pdo->fixed_settings &&
2018 (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
2019 error_setg(errp,
2020 "You can't use frequency, channels or format with fixed-settings=off");
2021 return;
2023 if (!pdo->mixing_engine && pdo->fixed_settings) {
2024 error_setg(errp, "You can't use fixed-settings without mixeng");
2025 return;
2028 if (!pdo->has_frequency) {
2029 pdo->has_frequency = true;
2030 pdo->frequency = 44100;
2032 if (!pdo->has_channels) {
2033 pdo->has_channels = true;
2034 pdo->channels = 2;
2036 if (!pdo->has_voices) {
2037 pdo->has_voices = true;
2038 pdo->voices = pdo->mixing_engine ? 1 : INT_MAX;
2040 if (!pdo->has_format) {
2041 pdo->has_format = true;
2042 pdo->format = AUDIO_FORMAT_S16;
2046 static void audio_validate_opts(Audiodev *dev, Error **errp)
2048 Error *err = NULL;
2050 audio_create_pdos(dev);
2052 audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
2053 if (err) {
2054 error_propagate(errp, err);
2055 return;
2058 audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
2059 if (err) {
2060 error_propagate(errp, err);
2061 return;
2064 if (!dev->has_timer_period) {
2065 dev->has_timer_period = true;
2066 dev->timer_period = 10000; /* 100Hz -> 10ms */
2070 void audio_parse_option(const char *opt)
2072 AudiodevListEntry *e;
2073 Audiodev *dev = NULL;
2075 Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
2076 visit_type_Audiodev(v, NULL, &dev, &error_fatal);
2077 visit_free(v);
2079 audio_validate_opts(dev, &error_fatal);
2081 e = g_malloc0(sizeof(AudiodevListEntry));
2082 e->dev = dev;
2083 QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
2086 void audio_init_audiodevs(void)
2088 AudiodevListEntry *e;
2090 QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2091 audio_init(e->dev, NULL);
2095 audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
2097 return (audsettings) {
2098 .freq = pdo->frequency,
2099 .nchannels = pdo->channels,
2100 .fmt = pdo->format,
2101 .endianness = AUDIO_HOST_ENDIANNESS,
2105 int audioformat_bytes_per_sample(AudioFormat fmt)
2107 switch (fmt) {
2108 case AUDIO_FORMAT_U8:
2109 case AUDIO_FORMAT_S8:
2110 return 1;
2112 case AUDIO_FORMAT_U16:
2113 case AUDIO_FORMAT_S16:
2114 return 2;
2116 case AUDIO_FORMAT_U32:
2117 case AUDIO_FORMAT_S32:
2118 case AUDIO_FORMAT_F32:
2119 return 4;
2121 case AUDIO_FORMAT__MAX:
2124 abort();
2128 /* frames = freq * usec / 1e6 */
2129 int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
2130 audsettings *as, int def_usecs)
2132 uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
2133 return (as->freq * usecs + 500000) / 1000000;
2136 /* samples = channels * frames = channels * freq * usec / 1e6 */
2137 int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
2138 audsettings *as, int def_usecs)
2140 return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
2144 * bytes = bytes_per_sample * samples =
2145 * bytes_per_sample * channels * freq * usec / 1e6
2147 int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
2148 audsettings *as, int def_usecs)
2150 return audio_buffer_samples(pdo, as, def_usecs) *
2151 audioformat_bytes_per_sample(as->fmt);
2154 AudioState *audio_state_by_name(const char *name)
2156 AudioState *s;
2157 QTAILQ_FOREACH(s, &audio_states, list) {
2158 assert(s->dev);
2159 if (strcmp(name, s->dev->id) == 0) {
2160 return s;
2163 return NULL;
2166 const char *audio_get_id(QEMUSoundCard *card)
2168 if (card->state) {
2169 assert(card->state->dev);
2170 return card->state->dev->id;
2171 } else {
2172 return "";
2176 const char *audio_application_name(void)
2178 const char *vm_name;
2180 vm_name = qemu_get_vm_name();
2181 return vm_name ? vm_name : "qemu";
2184 void audio_rate_start(RateCtl *rate)
2186 memset(rate, 0, sizeof(RateCtl));
2187 rate->start_ticks = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2190 size_t audio_rate_get_bytes(struct audio_pcm_info *info, RateCtl *rate,
2191 size_t bytes_avail)
2193 int64_t now;
2194 int64_t ticks;
2195 int64_t bytes;
2196 int64_t samples;
2197 size_t ret;
2199 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2200 ticks = now - rate->start_ticks;
2201 bytes = muldiv64(ticks, info->bytes_per_second, NANOSECONDS_PER_SECOND);
2202 samples = (bytes - rate->bytes_sent) / info->bytes_per_frame;
2203 if (samples < 0 || samples > 65536) {
2204 AUD_log(NULL, "Resetting rate control (%" PRId64 " samples)\n", samples);
2205 audio_rate_start(rate);
2206 samples = 0;
2209 ret = MIN(samples * info->bytes_per_frame, bytes_avail);
2210 rate->bytes_sent += ret;
2211 return ret;