target/arm: Drop tcg_temp_free from translator-sme.c
[qemu/armbru.git] / audio / audio.c
blob4290309d18be9c1cd80e87b864dc54eb37231b52
1 /*
2 * QEMU Audio subsystem
4 * Copyright (c) 2003-2005 Vassili Karpov (malc)
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
26 #include "audio.h"
27 #include "migration/vmstate.h"
28 #include "monitor/monitor.h"
29 #include "qemu/timer.h"
30 #include "qapi/error.h"
31 #include "qapi/clone-visitor.h"
32 #include "qapi/qobject-input-visitor.h"
33 #include "qapi/qapi-visit-audio.h"
34 #include "qapi/qapi-commands-audio.h"
35 #include "qemu/cutils.h"
36 #include "qemu/module.h"
37 #include "qemu/help_option.h"
38 #include "sysemu/sysemu.h"
39 #include "sysemu/replay.h"
40 #include "sysemu/runstate.h"
41 #include "ui/qemu-spice.h"
42 #include "trace.h"
44 #define AUDIO_CAP "audio"
45 #include "audio_int.h"
47 /* #define DEBUG_LIVE */
48 /* #define DEBUG_OUT */
49 /* #define DEBUG_CAPTURE */
50 /* #define DEBUG_POLL */
52 #define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
55 /* Order of CONFIG_AUDIO_DRIVERS is import.
56 The 1st one is the one used by default, that is the reason
57 that we generate the list.
59 const char *audio_prio_list[] = {
60 "spice",
61 CONFIG_AUDIO_DRIVERS
62 "none",
63 "wav",
64 NULL
67 static QLIST_HEAD(, audio_driver) audio_drivers;
68 static AudiodevListHead audiodevs = QSIMPLEQ_HEAD_INITIALIZER(audiodevs);
70 void audio_driver_register(audio_driver *drv)
72 QLIST_INSERT_HEAD(&audio_drivers, drv, next);
75 audio_driver *audio_driver_lookup(const char *name)
77 struct audio_driver *d;
78 Error *local_err = NULL;
79 int rv;
81 QLIST_FOREACH(d, &audio_drivers, next) {
82 if (strcmp(name, d->name) == 0) {
83 return d;
86 rv = audio_module_load(name, &local_err);
87 if (rv > 0) {
88 QLIST_FOREACH(d, &audio_drivers, next) {
89 if (strcmp(name, d->name) == 0) {
90 return d;
93 } else if (rv < 0) {
94 error_report_err(local_err);
96 return NULL;
99 static QTAILQ_HEAD(AudioStateHead, AudioState) audio_states =
100 QTAILQ_HEAD_INITIALIZER(audio_states);
102 const struct mixeng_volume nominal_volume = {
103 .mute = 0,
104 #ifdef FLOAT_MIXENG
105 .r = 1.0,
106 .l = 1.0,
107 #else
108 .r = 1ULL << 32,
109 .l = 1ULL << 32,
110 #endif
113 static bool legacy_config = true;
115 int audio_bug (const char *funcname, int cond)
117 if (cond) {
118 static int shown;
120 AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
121 if (!shown) {
122 shown = 1;
123 AUD_log (NULL, "Save all your work and restart without audio\n");
124 AUD_log (NULL, "I am sorry\n");
126 AUD_log (NULL, "Context:\n");
129 return cond;
132 static inline int audio_bits_to_index (int bits)
134 switch (bits) {
135 case 8:
136 return 0;
138 case 16:
139 return 1;
141 case 32:
142 return 2;
144 default:
145 audio_bug ("bits_to_index", 1);
146 AUD_log (NULL, "invalid bits %d\n", bits);
147 return 0;
151 void *audio_calloc (const char *funcname, int nmemb, size_t size)
153 int cond;
154 size_t len;
156 len = nmemb * size;
157 cond = !nmemb || !size;
158 cond |= nmemb < 0;
159 cond |= len < size;
161 if (audio_bug ("audio_calloc", cond)) {
162 AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
163 funcname);
164 AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
165 return NULL;
168 return g_malloc0 (len);
171 void AUD_vlog (const char *cap, const char *fmt, va_list ap)
173 if (cap) {
174 fprintf(stderr, "%s: ", cap);
177 vfprintf(stderr, fmt, ap);
180 void AUD_log (const char *cap, const char *fmt, ...)
182 va_list ap;
184 va_start (ap, fmt);
185 AUD_vlog (cap, fmt, ap);
186 va_end (ap);
189 static void audio_print_settings (struct audsettings *as)
191 dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
193 switch (as->fmt) {
194 case AUDIO_FORMAT_S8:
195 AUD_log (NULL, "S8");
196 break;
197 case AUDIO_FORMAT_U8:
198 AUD_log (NULL, "U8");
199 break;
200 case AUDIO_FORMAT_S16:
201 AUD_log (NULL, "S16");
202 break;
203 case AUDIO_FORMAT_U16:
204 AUD_log (NULL, "U16");
205 break;
206 case AUDIO_FORMAT_S32:
207 AUD_log (NULL, "S32");
208 break;
209 case AUDIO_FORMAT_U32:
210 AUD_log (NULL, "U32");
211 break;
212 case AUDIO_FORMAT_F32:
213 AUD_log (NULL, "F32");
214 break;
215 default:
216 AUD_log (NULL, "invalid(%d)", as->fmt);
217 break;
220 AUD_log (NULL, " endianness=");
221 switch (as->endianness) {
222 case 0:
223 AUD_log (NULL, "little");
224 break;
225 case 1:
226 AUD_log (NULL, "big");
227 break;
228 default:
229 AUD_log (NULL, "invalid");
230 break;
232 AUD_log (NULL, "\n");
235 static int audio_validate_settings (struct audsettings *as)
237 int invalid;
239 invalid = as->nchannels < 1;
240 invalid |= as->endianness != 0 && as->endianness != 1;
242 switch (as->fmt) {
243 case AUDIO_FORMAT_S8:
244 case AUDIO_FORMAT_U8:
245 case AUDIO_FORMAT_S16:
246 case AUDIO_FORMAT_U16:
247 case AUDIO_FORMAT_S32:
248 case AUDIO_FORMAT_U32:
249 case AUDIO_FORMAT_F32:
250 break;
251 default:
252 invalid = 1;
253 break;
256 invalid |= as->freq <= 0;
257 return invalid ? -1 : 0;
260 static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
262 int bits = 8;
263 bool is_signed = false, is_float = false;
265 switch (as->fmt) {
266 case AUDIO_FORMAT_S8:
267 is_signed = true;
268 /* fall through */
269 case AUDIO_FORMAT_U8:
270 break;
272 case AUDIO_FORMAT_S16:
273 is_signed = true;
274 /* fall through */
275 case AUDIO_FORMAT_U16:
276 bits = 16;
277 break;
279 case AUDIO_FORMAT_F32:
280 is_float = true;
281 /* fall through */
282 case AUDIO_FORMAT_S32:
283 is_signed = true;
284 /* fall through */
285 case AUDIO_FORMAT_U32:
286 bits = 32;
287 break;
289 default:
290 abort();
292 return info->freq == as->freq
293 && info->nchannels == as->nchannels
294 && info->is_signed == is_signed
295 && info->is_float == is_float
296 && info->bits == bits
297 && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
300 void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
302 int bits = 8, mul;
303 bool is_signed = false, is_float = false;
305 switch (as->fmt) {
306 case AUDIO_FORMAT_S8:
307 is_signed = true;
308 /* fall through */
309 case AUDIO_FORMAT_U8:
310 mul = 1;
311 break;
313 case AUDIO_FORMAT_S16:
314 is_signed = true;
315 /* fall through */
316 case AUDIO_FORMAT_U16:
317 bits = 16;
318 mul = 2;
319 break;
321 case AUDIO_FORMAT_F32:
322 is_float = true;
323 /* fall through */
324 case AUDIO_FORMAT_S32:
325 is_signed = true;
326 /* fall through */
327 case AUDIO_FORMAT_U32:
328 bits = 32;
329 mul = 4;
330 break;
332 default:
333 abort();
336 info->freq = as->freq;
337 info->bits = bits;
338 info->is_signed = is_signed;
339 info->is_float = is_float;
340 info->nchannels = as->nchannels;
341 info->bytes_per_frame = as->nchannels * mul;
342 info->bytes_per_second = info->freq * info->bytes_per_frame;
343 info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
346 void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
348 if (!len) {
349 return;
352 if (info->is_signed || info->is_float) {
353 memset(buf, 0x00, len * info->bytes_per_frame);
354 } else {
355 switch (info->bits) {
356 case 8:
357 memset(buf, 0x80, len * info->bytes_per_frame);
358 break;
360 case 16:
362 int i;
363 uint16_t *p = buf;
364 short s = INT16_MAX;
366 if (info->swap_endianness) {
367 s = bswap16 (s);
370 for (i = 0; i < len * info->nchannels; i++) {
371 p[i] = s;
374 break;
376 case 32:
378 int i;
379 uint32_t *p = buf;
380 int32_t s = INT32_MAX;
382 if (info->swap_endianness) {
383 s = bswap32 (s);
386 for (i = 0; i < len * info->nchannels; i++) {
387 p[i] = s;
390 break;
392 default:
393 AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
394 info->bits);
395 break;
401 * Capture
403 static void noop_conv (struct st_sample *dst, const void *src, int samples)
405 (void) src;
406 (void) dst;
407 (void) samples;
410 static CaptureVoiceOut *audio_pcm_capture_find_specific(AudioState *s,
411 struct audsettings *as)
413 CaptureVoiceOut *cap;
415 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
416 if (audio_pcm_info_eq (&cap->hw.info, as)) {
417 return cap;
420 return NULL;
423 static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
425 struct capture_callback *cb;
427 #ifdef DEBUG_CAPTURE
428 dolog ("notification %d sent\n", cmd);
429 #endif
430 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
431 cb->ops.notify (cb->opaque, cmd);
435 static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
437 if (cap->hw.enabled != enabled) {
438 audcnotification_e cmd;
439 cap->hw.enabled = enabled;
440 cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
441 audio_notify_capture (cap, cmd);
445 static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
447 HWVoiceOut *hw = &cap->hw;
448 SWVoiceOut *sw;
449 int enabled = 0;
451 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
452 if (sw->active) {
453 enabled = 1;
454 break;
457 audio_capture_maybe_changed (cap, enabled);
460 static void audio_detach_capture (HWVoiceOut *hw)
462 SWVoiceCap *sc = hw->cap_head.lh_first;
464 while (sc) {
465 SWVoiceCap *sc1 = sc->entries.le_next;
466 SWVoiceOut *sw = &sc->sw;
467 CaptureVoiceOut *cap = sc->cap;
468 int was_active = sw->active;
470 if (sw->rate) {
471 st_rate_stop (sw->rate);
472 sw->rate = NULL;
475 QLIST_REMOVE (sw, entries);
476 QLIST_REMOVE (sc, entries);
477 g_free (sc);
478 if (was_active) {
479 /* We have removed soft voice from the capture:
480 this might have changed the overall status of the capture
481 since this might have been the only active voice */
482 audio_recalc_and_notify_capture (cap);
484 sc = sc1;
488 static int audio_attach_capture (HWVoiceOut *hw)
490 AudioState *s = hw->s;
491 CaptureVoiceOut *cap;
493 audio_detach_capture (hw);
494 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
495 SWVoiceCap *sc;
496 SWVoiceOut *sw;
497 HWVoiceOut *hw_cap = &cap->hw;
499 sc = g_malloc0(sizeof(*sc));
501 sc->cap = cap;
502 sw = &sc->sw;
503 sw->hw = hw_cap;
504 sw->info = hw->info;
505 sw->empty = 1;
506 sw->active = hw->enabled;
507 sw->conv = noop_conv;
508 sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
509 sw->vol = nominal_volume;
510 sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
511 if (!sw->rate) {
512 dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
513 g_free (sw);
514 return -1;
516 QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
517 QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
518 #ifdef DEBUG_CAPTURE
519 sw->name = g_strdup_printf ("for %p %d,%d,%d",
520 hw, sw->info.freq, sw->info.bits,
521 sw->info.nchannels);
522 dolog ("Added %s active = %d\n", sw->name, sw->active);
523 #endif
524 if (sw->active) {
525 audio_capture_maybe_changed (cap, 1);
528 return 0;
532 * Hard voice (capture)
534 static size_t audio_pcm_hw_find_min_in (HWVoiceIn *hw)
536 SWVoiceIn *sw;
537 size_t m = hw->total_samples_captured;
539 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
540 if (sw->active) {
541 m = MIN (m, sw->total_hw_samples_acquired);
544 return m;
547 static size_t audio_pcm_hw_get_live_in(HWVoiceIn *hw)
549 size_t live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
550 if (audio_bug(__func__, live > hw->conv_buf->size)) {
551 dolog("live=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
552 return 0;
554 return live;
557 static size_t audio_pcm_hw_conv_in(HWVoiceIn *hw, void *pcm_buf, size_t samples)
559 size_t conv = 0;
560 STSampleBuffer *conv_buf = hw->conv_buf;
562 while (samples) {
563 uint8_t *src = advance(pcm_buf, conv * hw->info.bytes_per_frame);
564 size_t proc = MIN(samples, conv_buf->size - conv_buf->pos);
566 hw->conv(conv_buf->samples + conv_buf->pos, src, proc);
567 conv_buf->pos = (conv_buf->pos + proc) % conv_buf->size;
568 samples -= proc;
569 conv += proc;
572 return conv;
576 * Soft voice (capture)
578 static size_t audio_pcm_sw_read(SWVoiceIn *sw, void *buf, size_t size)
580 HWVoiceIn *hw = sw->hw;
581 size_t samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
582 struct st_sample *src, *dst = sw->buf;
584 live = hw->total_samples_captured - sw->total_hw_samples_acquired;
585 if (!live) {
586 return 0;
588 if (audio_bug(__func__, live > hw->conv_buf->size)) {
589 dolog("live_in=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
590 return 0;
593 rpos = audio_ring_posb(hw->conv_buf->pos, live, hw->conv_buf->size);
595 samples = size / sw->info.bytes_per_frame;
597 swlim = (live * sw->ratio) >> 32;
598 swlim = MIN (swlim, samples);
600 while (swlim) {
601 src = hw->conv_buf->samples + rpos;
602 if (hw->conv_buf->pos > rpos) {
603 isamp = hw->conv_buf->pos - rpos;
604 } else {
605 isamp = hw->conv_buf->size - rpos;
608 if (!isamp) {
609 break;
611 osamp = swlim;
613 st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
614 swlim -= osamp;
615 rpos = (rpos + isamp) % hw->conv_buf->size;
616 dst += osamp;
617 ret += osamp;
618 total += isamp;
621 if (!hw->pcm_ops->volume_in) {
622 mixeng_volume (sw->buf, ret, &sw->vol);
625 sw->clip (buf, sw->buf, ret);
626 sw->total_hw_samples_acquired += total;
627 return ret * sw->info.bytes_per_frame;
631 * Hard voice (playback)
633 static size_t audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
635 SWVoiceOut *sw;
636 size_t m = SIZE_MAX;
637 int nb_live = 0;
639 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
640 if (sw->active || !sw->empty) {
641 m = MIN (m, sw->total_hw_samples_mixed);
642 nb_live += 1;
646 *nb_livep = nb_live;
647 return m;
650 static size_t audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
652 size_t smin;
653 int nb_live1;
655 smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
656 if (nb_live) {
657 *nb_live = nb_live1;
660 if (nb_live1) {
661 size_t live = smin;
663 if (audio_bug(__func__, live > hw->mix_buf->size)) {
664 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
665 return 0;
667 return live;
669 return 0;
672 static size_t audio_pcm_hw_get_free(HWVoiceOut *hw)
674 return (hw->pcm_ops->buffer_get_free ? hw->pcm_ops->buffer_get_free(hw) :
675 INT_MAX) / hw->info.bytes_per_frame;
678 static void audio_pcm_hw_clip_out(HWVoiceOut *hw, void *pcm_buf, size_t len)
680 size_t clipped = 0;
681 size_t pos = hw->mix_buf->pos;
683 while (len) {
684 st_sample *src = hw->mix_buf->samples + pos;
685 uint8_t *dst = advance(pcm_buf, clipped * hw->info.bytes_per_frame);
686 size_t samples_till_end_of_buf = hw->mix_buf->size - pos;
687 size_t samples_to_clip = MIN(len, samples_till_end_of_buf);
689 hw->clip(dst, src, samples_to_clip);
691 pos = (pos + samples_to_clip) % hw->mix_buf->size;
692 len -= samples_to_clip;
693 clipped += samples_to_clip;
698 * Soft voice (playback)
700 static size_t audio_pcm_sw_write(SWVoiceOut *sw, void *buf, size_t size)
702 size_t hwsamples, samples, isamp, osamp, wpos, live, dead, left, blck;
703 size_t hw_free;
704 size_t ret = 0, pos = 0, total = 0;
706 if (!sw) {
707 return size;
710 hwsamples = sw->hw->mix_buf->size;
712 live = sw->total_hw_samples_mixed;
713 if (audio_bug(__func__, live > hwsamples)) {
714 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hwsamples);
715 return 0;
718 if (live == hwsamples) {
719 #ifdef DEBUG_OUT
720 dolog ("%s is full %zu\n", sw->name, live);
721 #endif
722 return 0;
725 wpos = (sw->hw->mix_buf->pos + live) % hwsamples;
727 dead = hwsamples - live;
728 hw_free = audio_pcm_hw_get_free(sw->hw);
729 hw_free = hw_free > live ? hw_free - live : 0;
730 samples = ((int64_t)MIN(dead, hw_free) << 32) / sw->ratio;
731 samples = MIN(samples, size / sw->info.bytes_per_frame);
732 if (samples) {
733 sw->conv(sw->buf, buf, samples);
735 if (!sw->hw->pcm_ops->volume_out) {
736 mixeng_volume(sw->buf, samples, &sw->vol);
740 while (samples) {
741 dead = hwsamples - live;
742 left = hwsamples - wpos;
743 blck = MIN (dead, left);
744 if (!blck) {
745 break;
747 isamp = samples;
748 osamp = blck;
749 st_rate_flow_mix (
750 sw->rate,
751 sw->buf + pos,
752 sw->hw->mix_buf->samples + wpos,
753 &isamp,
754 &osamp
756 ret += isamp;
757 samples -= isamp;
758 pos += isamp;
759 live += osamp;
760 wpos = (wpos + osamp) % hwsamples;
761 total += osamp;
764 sw->total_hw_samples_mixed += total;
765 sw->empty = sw->total_hw_samples_mixed == 0;
767 #ifdef DEBUG_OUT
768 dolog (
769 "%s: write size %zu ret %zu total sw %zu\n",
770 SW_NAME (sw),
771 size / sw->info.bytes_per_frame,
772 ret,
773 sw->total_hw_samples_mixed
775 #endif
777 return ret * sw->info.bytes_per_frame;
780 #ifdef DEBUG_AUDIO
781 static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
783 dolog("%s: bits %d, sign %d, float %d, freq %d, nchan %d\n",
784 cap, info->bits, info->is_signed, info->is_float, info->freq,
785 info->nchannels);
787 #endif
789 #define DAC
790 #include "audio_template.h"
791 #undef DAC
792 #include "audio_template.h"
795 * Timer
797 static int audio_is_timer_needed(AudioState *s)
799 HWVoiceIn *hwi = NULL;
800 HWVoiceOut *hwo = NULL;
802 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
803 if (!hwo->poll_mode) {
804 return 1;
807 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
808 if (!hwi->poll_mode) {
809 return 1;
812 return 0;
815 static void audio_reset_timer (AudioState *s)
817 if (audio_is_timer_needed(s)) {
818 timer_mod_anticipate_ns(s->ts,
819 qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
820 if (!s->timer_running) {
821 s->timer_running = true;
822 s->timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
823 trace_audio_timer_start(s->period_ticks / SCALE_MS);
825 } else {
826 timer_del(s->ts);
827 if (s->timer_running) {
828 s->timer_running = false;
829 trace_audio_timer_stop();
834 static void audio_timer (void *opaque)
836 int64_t now, diff;
837 AudioState *s = opaque;
839 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
840 diff = now - s->timer_last;
841 if (diff > s->period_ticks * 3 / 2) {
842 trace_audio_timer_delayed(diff / SCALE_MS);
844 s->timer_last = now;
846 audio_run(s, "timer");
847 audio_reset_timer(s);
851 * Public API
853 size_t AUD_write(SWVoiceOut *sw, void *buf, size_t size)
855 HWVoiceOut *hw;
857 if (!sw) {
858 /* XXX: Consider options */
859 return size;
861 hw = sw->hw;
863 if (!hw->enabled) {
864 dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
865 return 0;
868 if (audio_get_pdo_out(hw->s->dev)->mixing_engine) {
869 return audio_pcm_sw_write(sw, buf, size);
870 } else {
871 return hw->pcm_ops->write(hw, buf, size);
875 size_t AUD_read(SWVoiceIn *sw, void *buf, size_t size)
877 HWVoiceIn *hw;
879 if (!sw) {
880 /* XXX: Consider options */
881 return size;
883 hw = sw->hw;
885 if (!hw->enabled) {
886 dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
887 return 0;
890 if (audio_get_pdo_in(hw->s->dev)->mixing_engine) {
891 return audio_pcm_sw_read(sw, buf, size);
892 } else {
893 return hw->pcm_ops->read(hw, buf, size);
897 int AUD_get_buffer_size_out(SWVoiceOut *sw)
899 return sw->hw->samples * sw->hw->info.bytes_per_frame;
902 void AUD_set_active_out (SWVoiceOut *sw, int on)
904 HWVoiceOut *hw;
906 if (!sw) {
907 return;
910 hw = sw->hw;
911 if (sw->active != on) {
912 AudioState *s = sw->s;
913 SWVoiceOut *temp_sw;
914 SWVoiceCap *sc;
916 if (on) {
917 hw->pending_disable = 0;
918 if (!hw->enabled) {
919 hw->enabled = 1;
920 if (s->vm_running) {
921 if (hw->pcm_ops->enable_out) {
922 hw->pcm_ops->enable_out(hw, true);
924 audio_reset_timer (s);
927 } else {
928 if (hw->enabled) {
929 int nb_active = 0;
931 for (temp_sw = hw->sw_head.lh_first; temp_sw;
932 temp_sw = temp_sw->entries.le_next) {
933 nb_active += temp_sw->active != 0;
936 hw->pending_disable = nb_active == 1;
940 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
941 sc->sw.active = hw->enabled;
942 if (hw->enabled) {
943 audio_capture_maybe_changed (sc->cap, 1);
946 sw->active = on;
950 void AUD_set_active_in (SWVoiceIn *sw, int on)
952 HWVoiceIn *hw;
954 if (!sw) {
955 return;
958 hw = sw->hw;
959 if (sw->active != on) {
960 AudioState *s = sw->s;
961 SWVoiceIn *temp_sw;
963 if (on) {
964 if (!hw->enabled) {
965 hw->enabled = 1;
966 if (s->vm_running) {
967 if (hw->pcm_ops->enable_in) {
968 hw->pcm_ops->enable_in(hw, true);
970 audio_reset_timer (s);
973 sw->total_hw_samples_acquired = hw->total_samples_captured;
974 } else {
975 if (hw->enabled) {
976 int nb_active = 0;
978 for (temp_sw = hw->sw_head.lh_first; temp_sw;
979 temp_sw = temp_sw->entries.le_next) {
980 nb_active += temp_sw->active != 0;
983 if (nb_active == 1) {
984 hw->enabled = 0;
985 if (hw->pcm_ops->enable_in) {
986 hw->pcm_ops->enable_in(hw, false);
991 sw->active = on;
996 * audio_frontend_frames_in() - returns the number of frames the resampling
997 * code generates from frames_in frames
999 * @sw: audio recording frontend
1000 * @frames_in: number of frames
1002 static size_t audio_frontend_frames_in(SWVoiceIn *sw, size_t frames_in)
1004 return (int64_t)frames_in * sw->ratio >> 32;
1007 static size_t audio_get_avail (SWVoiceIn *sw)
1009 size_t live;
1011 if (!sw) {
1012 return 0;
1015 live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
1016 if (audio_bug(__func__, live > sw->hw->conv_buf->size)) {
1017 dolog("live=%zu sw->hw->conv_buf->size=%zu\n", live,
1018 sw->hw->conv_buf->size);
1019 return 0;
1022 ldebug (
1023 "%s: get_avail live %zu frontend frames %zu\n",
1024 SW_NAME (sw),
1025 live, audio_frontend_frames_in(sw, live)
1028 return live;
1032 * audio_frontend_frames_out() - returns the number of frames needed to
1033 * get frames_out frames after resampling
1035 * @sw: audio playback frontend
1036 * @frames_out: number of frames
1038 static size_t audio_frontend_frames_out(SWVoiceOut *sw, size_t frames_out)
1040 return ((int64_t)frames_out << 32) / sw->ratio;
1043 static size_t audio_get_free(SWVoiceOut *sw)
1045 size_t live, dead;
1047 if (!sw) {
1048 return 0;
1051 live = sw->total_hw_samples_mixed;
1053 if (audio_bug(__func__, live > sw->hw->mix_buf->size)) {
1054 dolog("live=%zu sw->hw->mix_buf->size=%zu\n", live,
1055 sw->hw->mix_buf->size);
1056 return 0;
1059 dead = sw->hw->mix_buf->size - live;
1061 #ifdef DEBUG_OUT
1062 dolog("%s: get_free live %zu dead %zu frontend frames %zu\n",
1063 SW_NAME(sw), live, dead, audio_frontend_frames_out(sw, dead));
1064 #endif
1066 return dead;
1069 static void audio_capture_mix_and_clear(HWVoiceOut *hw, size_t rpos,
1070 size_t samples)
1072 size_t n;
1074 if (hw->enabled) {
1075 SWVoiceCap *sc;
1077 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1078 SWVoiceOut *sw = &sc->sw;
1079 int rpos2 = rpos;
1081 n = samples;
1082 while (n) {
1083 size_t till_end_of_hw = hw->mix_buf->size - rpos2;
1084 size_t to_write = MIN(till_end_of_hw, n);
1085 size_t bytes = to_write * hw->info.bytes_per_frame;
1086 size_t written;
1088 sw->buf = hw->mix_buf->samples + rpos2;
1089 written = audio_pcm_sw_write (sw, NULL, bytes);
1090 if (written - bytes) {
1091 dolog("Could not mix %zu bytes into a capture "
1092 "buffer, mixed %zu\n",
1093 bytes, written);
1094 break;
1096 n -= to_write;
1097 rpos2 = (rpos2 + to_write) % hw->mix_buf->size;
1102 n = MIN(samples, hw->mix_buf->size - rpos);
1103 mixeng_clear(hw->mix_buf->samples + rpos, n);
1104 mixeng_clear(hw->mix_buf->samples, samples - n);
1107 static size_t audio_pcm_hw_run_out(HWVoiceOut *hw, size_t live)
1109 size_t clipped = 0;
1111 while (live) {
1112 size_t size = live * hw->info.bytes_per_frame;
1113 size_t decr, proc;
1114 void *buf = hw->pcm_ops->get_buffer_out(hw, &size);
1116 if (size == 0) {
1117 break;
1120 decr = MIN(size / hw->info.bytes_per_frame, live);
1121 if (buf) {
1122 audio_pcm_hw_clip_out(hw, buf, decr);
1124 proc = hw->pcm_ops->put_buffer_out(hw, buf,
1125 decr * hw->info.bytes_per_frame) /
1126 hw->info.bytes_per_frame;
1128 live -= proc;
1129 clipped += proc;
1130 hw->mix_buf->pos = (hw->mix_buf->pos + proc) % hw->mix_buf->size;
1132 if (proc == 0 || proc < decr) {
1133 break;
1137 if (hw->pcm_ops->run_buffer_out) {
1138 hw->pcm_ops->run_buffer_out(hw);
1141 return clipped;
1144 static void audio_run_out (AudioState *s)
1146 HWVoiceOut *hw = NULL;
1147 SWVoiceOut *sw;
1149 while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1150 size_t played, live, prev_rpos;
1151 size_t hw_free = audio_pcm_hw_get_free(hw);
1152 int nb_live;
1154 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1155 /* there is exactly 1 sw for each hw with no mixeng */
1156 sw = hw->sw_head.lh_first;
1158 if (hw->pending_disable) {
1159 hw->enabled = 0;
1160 hw->pending_disable = 0;
1161 if (hw->pcm_ops->enable_out) {
1162 hw->pcm_ops->enable_out(hw, false);
1166 if (sw->active) {
1167 sw->callback.fn(sw->callback.opaque,
1168 hw_free * sw->info.bytes_per_frame);
1171 if (hw->pcm_ops->run_buffer_out) {
1172 hw->pcm_ops->run_buffer_out(hw);
1175 continue;
1178 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1179 if (sw->active) {
1180 size_t sw_free = audio_get_free(sw);
1181 size_t free;
1183 if (hw_free > sw->total_hw_samples_mixed) {
1184 free = audio_frontend_frames_out(sw,
1185 MIN(sw_free, hw_free - sw->total_hw_samples_mixed));
1186 } else {
1187 free = 0;
1189 if (free > 0) {
1190 sw->callback.fn(sw->callback.opaque,
1191 free * sw->info.bytes_per_frame);
1196 live = audio_pcm_hw_get_live_out (hw, &nb_live);
1197 if (!nb_live) {
1198 live = 0;
1201 if (audio_bug(__func__, live > hw->mix_buf->size)) {
1202 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
1203 continue;
1206 if (hw->pending_disable && !nb_live) {
1207 SWVoiceCap *sc;
1208 #ifdef DEBUG_OUT
1209 dolog ("Disabling voice\n");
1210 #endif
1211 hw->enabled = 0;
1212 hw->pending_disable = 0;
1213 if (hw->pcm_ops->enable_out) {
1214 hw->pcm_ops->enable_out(hw, false);
1216 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1217 sc->sw.active = 0;
1218 audio_recalc_and_notify_capture (sc->cap);
1220 continue;
1223 if (!live) {
1224 if (hw->pcm_ops->run_buffer_out) {
1225 hw->pcm_ops->run_buffer_out(hw);
1227 continue;
1230 prev_rpos = hw->mix_buf->pos;
1231 played = audio_pcm_hw_run_out(hw, live);
1232 replay_audio_out(&played);
1233 if (audio_bug(__func__, hw->mix_buf->pos >= hw->mix_buf->size)) {
1234 dolog("hw->mix_buf->pos=%zu hw->mix_buf->size=%zu played=%zu\n",
1235 hw->mix_buf->pos, hw->mix_buf->size, played);
1236 hw->mix_buf->pos = 0;
1239 #ifdef DEBUG_OUT
1240 dolog("played=%zu\n", played);
1241 #endif
1243 if (played) {
1244 hw->ts_helper += played;
1245 audio_capture_mix_and_clear (hw, prev_rpos, played);
1248 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1249 if (!sw->active && sw->empty) {
1250 continue;
1253 if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1254 dolog("played=%zu sw->total_hw_samples_mixed=%zu\n",
1255 played, sw->total_hw_samples_mixed);
1256 played = sw->total_hw_samples_mixed;
1259 sw->total_hw_samples_mixed -= played;
1261 if (!sw->total_hw_samples_mixed) {
1262 sw->empty = 1;
1268 static size_t audio_pcm_hw_run_in(HWVoiceIn *hw, size_t samples)
1270 size_t conv = 0;
1272 if (hw->pcm_ops->run_buffer_in) {
1273 hw->pcm_ops->run_buffer_in(hw);
1276 while (samples) {
1277 size_t proc;
1278 size_t size = samples * hw->info.bytes_per_frame;
1279 void *buf = hw->pcm_ops->get_buffer_in(hw, &size);
1281 assert(size % hw->info.bytes_per_frame == 0);
1282 if (size == 0) {
1283 break;
1286 proc = audio_pcm_hw_conv_in(hw, buf, size / hw->info.bytes_per_frame);
1288 samples -= proc;
1289 conv += proc;
1290 hw->pcm_ops->put_buffer_in(hw, buf, proc * hw->info.bytes_per_frame);
1293 return conv;
1296 static void audio_run_in (AudioState *s)
1298 HWVoiceIn *hw = NULL;
1300 if (!audio_get_pdo_in(s->dev)->mixing_engine) {
1301 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1302 /* there is exactly 1 sw for each hw with no mixeng */
1303 SWVoiceIn *sw = hw->sw_head.lh_first;
1304 if (sw->active) {
1305 sw->callback.fn(sw->callback.opaque, INT_MAX);
1308 return;
1311 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1312 SWVoiceIn *sw;
1313 size_t captured = 0, min;
1315 if (replay_mode != REPLAY_MODE_PLAY) {
1316 captured = audio_pcm_hw_run_in(
1317 hw, hw->conv_buf->size - audio_pcm_hw_get_live_in(hw));
1319 replay_audio_in(&captured, hw->conv_buf->samples, &hw->conv_buf->pos,
1320 hw->conv_buf->size);
1322 min = audio_pcm_hw_find_min_in (hw);
1323 hw->total_samples_captured += captured - min;
1324 hw->ts_helper += captured;
1326 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1327 sw->total_hw_samples_acquired -= min;
1329 if (sw->active) {
1330 size_t sw_avail = audio_get_avail(sw);
1331 size_t avail;
1333 avail = audio_frontend_frames_in(sw, sw_avail);
1334 if (avail > 0) {
1335 sw->callback.fn(sw->callback.opaque,
1336 avail * sw->info.bytes_per_frame);
1343 static void audio_run_capture (AudioState *s)
1345 CaptureVoiceOut *cap;
1347 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1348 size_t live, rpos, captured;
1349 HWVoiceOut *hw = &cap->hw;
1350 SWVoiceOut *sw;
1352 captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1353 rpos = hw->mix_buf->pos;
1354 while (live) {
1355 size_t left = hw->mix_buf->size - rpos;
1356 size_t to_capture = MIN(live, left);
1357 struct st_sample *src;
1358 struct capture_callback *cb;
1360 src = hw->mix_buf->samples + rpos;
1361 hw->clip (cap->buf, src, to_capture);
1362 mixeng_clear (src, to_capture);
1364 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1365 cb->ops.capture (cb->opaque, cap->buf,
1366 to_capture * hw->info.bytes_per_frame);
1368 rpos = (rpos + to_capture) % hw->mix_buf->size;
1369 live -= to_capture;
1371 hw->mix_buf->pos = rpos;
1373 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1374 if (!sw->active && sw->empty) {
1375 continue;
1378 if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1379 dolog("captured=%zu sw->total_hw_samples_mixed=%zu\n",
1380 captured, sw->total_hw_samples_mixed);
1381 captured = sw->total_hw_samples_mixed;
1384 sw->total_hw_samples_mixed -= captured;
1385 sw->empty = sw->total_hw_samples_mixed == 0;
1390 void audio_run(AudioState *s, const char *msg)
1392 audio_run_out(s);
1393 audio_run_in(s);
1394 audio_run_capture(s);
1396 #ifdef DEBUG_POLL
1398 static double prevtime;
1399 double currtime;
1400 struct timeval tv;
1402 if (gettimeofday (&tv, NULL)) {
1403 perror ("audio_run: gettimeofday");
1404 return;
1407 currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1408 dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1409 prevtime = currtime;
1411 #endif
1414 void audio_generic_run_buffer_in(HWVoiceIn *hw)
1416 if (unlikely(!hw->buf_emul)) {
1417 hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1418 hw->buf_emul = g_malloc(hw->size_emul);
1419 hw->pos_emul = hw->pending_emul = 0;
1422 while (hw->pending_emul < hw->size_emul) {
1423 size_t read_len = MIN(hw->size_emul - hw->pos_emul,
1424 hw->size_emul - hw->pending_emul);
1425 size_t read = hw->pcm_ops->read(hw, hw->buf_emul + hw->pos_emul,
1426 read_len);
1427 hw->pending_emul += read;
1428 hw->pos_emul = (hw->pos_emul + read) % hw->size_emul;
1429 if (read < read_len) {
1430 break;
1435 void *audio_generic_get_buffer_in(HWVoiceIn *hw, size_t *size)
1437 size_t start;
1439 start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1440 assert(start < hw->size_emul);
1442 *size = MIN(*size, hw->pending_emul);
1443 *size = MIN(*size, hw->size_emul - start);
1444 return hw->buf_emul + start;
1447 void audio_generic_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
1449 assert(size <= hw->pending_emul);
1450 hw->pending_emul -= size;
1453 size_t audio_generic_buffer_get_free(HWVoiceOut *hw)
1455 if (hw->buf_emul) {
1456 return hw->size_emul - hw->pending_emul;
1457 } else {
1458 return hw->samples * hw->info.bytes_per_frame;
1462 void audio_generic_run_buffer_out(HWVoiceOut *hw)
1464 while (hw->pending_emul) {
1465 size_t write_len, written, start;
1467 start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1468 assert(start < hw->size_emul);
1470 write_len = MIN(hw->pending_emul, hw->size_emul - start);
1472 written = hw->pcm_ops->write(hw, hw->buf_emul + start, write_len);
1473 hw->pending_emul -= written;
1475 if (written < write_len) {
1476 break;
1481 void *audio_generic_get_buffer_out(HWVoiceOut *hw, size_t *size)
1483 if (unlikely(!hw->buf_emul)) {
1484 hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1485 hw->buf_emul = g_malloc(hw->size_emul);
1486 hw->pos_emul = hw->pending_emul = 0;
1489 *size = MIN(hw->size_emul - hw->pending_emul,
1490 hw->size_emul - hw->pos_emul);
1491 return hw->buf_emul + hw->pos_emul;
1494 size_t audio_generic_put_buffer_out(HWVoiceOut *hw, void *buf, size_t size)
1496 assert(buf == hw->buf_emul + hw->pos_emul &&
1497 size + hw->pending_emul <= hw->size_emul);
1499 hw->pending_emul += size;
1500 hw->pos_emul = (hw->pos_emul + size) % hw->size_emul;
1502 return size;
1505 size_t audio_generic_write(HWVoiceOut *hw, void *buf, size_t size)
1507 size_t total = 0;
1509 if (hw->pcm_ops->buffer_get_free) {
1510 size_t free = hw->pcm_ops->buffer_get_free(hw);
1512 size = MIN(size, free);
1515 while (total < size) {
1516 size_t dst_size = size - total;
1517 size_t copy_size, proc;
1518 void *dst = hw->pcm_ops->get_buffer_out(hw, &dst_size);
1520 if (dst_size == 0) {
1521 break;
1524 copy_size = MIN(size - total, dst_size);
1525 if (dst) {
1526 memcpy(dst, (char *)buf + total, copy_size);
1528 proc = hw->pcm_ops->put_buffer_out(hw, dst, copy_size);
1529 total += proc;
1531 if (proc == 0 || proc < copy_size) {
1532 break;
1536 return total;
1539 size_t audio_generic_read(HWVoiceIn *hw, void *buf, size_t size)
1541 size_t total = 0;
1543 if (hw->pcm_ops->run_buffer_in) {
1544 hw->pcm_ops->run_buffer_in(hw);
1547 while (total < size) {
1548 size_t src_size = size - total;
1549 void *src = hw->pcm_ops->get_buffer_in(hw, &src_size);
1551 if (src_size == 0) {
1552 break;
1555 memcpy((char *)buf + total, src, src_size);
1556 hw->pcm_ops->put_buffer_in(hw, src, src_size);
1557 total += src_size;
1560 return total;
1563 static int audio_driver_init(AudioState *s, struct audio_driver *drv,
1564 bool msg, Audiodev *dev)
1566 s->drv_opaque = drv->init(dev);
1568 if (s->drv_opaque) {
1569 if (!drv->pcm_ops->get_buffer_in) {
1570 drv->pcm_ops->get_buffer_in = audio_generic_get_buffer_in;
1571 drv->pcm_ops->put_buffer_in = audio_generic_put_buffer_in;
1573 if (!drv->pcm_ops->get_buffer_out) {
1574 drv->pcm_ops->get_buffer_out = audio_generic_get_buffer_out;
1575 drv->pcm_ops->put_buffer_out = audio_generic_put_buffer_out;
1578 audio_init_nb_voices_out(s, drv);
1579 audio_init_nb_voices_in(s, drv);
1580 s->drv = drv;
1581 return 0;
1582 } else {
1583 if (msg) {
1584 dolog("Could not init `%s' audio driver\n", drv->name);
1586 return -1;
1590 static void audio_vm_change_state_handler (void *opaque, bool running,
1591 RunState state)
1593 AudioState *s = opaque;
1594 HWVoiceOut *hwo = NULL;
1595 HWVoiceIn *hwi = NULL;
1597 s->vm_running = running;
1598 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
1599 if (hwo->pcm_ops->enable_out) {
1600 hwo->pcm_ops->enable_out(hwo, running);
1604 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
1605 if (hwi->pcm_ops->enable_in) {
1606 hwi->pcm_ops->enable_in(hwi, running);
1609 audio_reset_timer (s);
1612 static void free_audio_state(AudioState *s)
1614 HWVoiceOut *hwo, *hwon;
1615 HWVoiceIn *hwi, *hwin;
1617 QLIST_FOREACH_SAFE(hwo, &s->hw_head_out, entries, hwon) {
1618 SWVoiceCap *sc;
1620 if (hwo->enabled && hwo->pcm_ops->enable_out) {
1621 hwo->pcm_ops->enable_out(hwo, false);
1623 hwo->pcm_ops->fini_out (hwo);
1625 for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1626 CaptureVoiceOut *cap = sc->cap;
1627 struct capture_callback *cb;
1629 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1630 cb->ops.destroy (cb->opaque);
1633 QLIST_REMOVE(hwo, entries);
1636 QLIST_FOREACH_SAFE(hwi, &s->hw_head_in, entries, hwin) {
1637 if (hwi->enabled && hwi->pcm_ops->enable_in) {
1638 hwi->pcm_ops->enable_in(hwi, false);
1640 hwi->pcm_ops->fini_in (hwi);
1641 QLIST_REMOVE(hwi, entries);
1644 if (s->drv) {
1645 s->drv->fini (s->drv_opaque);
1646 s->drv = NULL;
1649 if (s->dev) {
1650 qapi_free_Audiodev(s->dev);
1651 s->dev = NULL;
1654 if (s->ts) {
1655 timer_free(s->ts);
1656 s->ts = NULL;
1659 g_free(s);
1662 void audio_cleanup(void)
1664 while (!QTAILQ_EMPTY(&audio_states)) {
1665 AudioState *s = QTAILQ_FIRST(&audio_states);
1666 QTAILQ_REMOVE(&audio_states, s, list);
1667 free_audio_state(s);
1671 static bool vmstate_audio_needed(void *opaque)
1674 * Never needed, this vmstate only exists in case
1675 * an old qemu sends it to us.
1677 return false;
1680 static const VMStateDescription vmstate_audio = {
1681 .name = "audio",
1682 .version_id = 1,
1683 .minimum_version_id = 1,
1684 .needed = vmstate_audio_needed,
1685 .fields = (VMStateField[]) {
1686 VMSTATE_END_OF_LIST()
1690 static void audio_validate_opts(Audiodev *dev, Error **errp);
1692 static AudiodevListEntry *audiodev_find(
1693 AudiodevListHead *head, const char *drvname)
1695 AudiodevListEntry *e;
1696 QSIMPLEQ_FOREACH(e, head, next) {
1697 if (strcmp(AudiodevDriver_str(e->dev->driver), drvname) == 0) {
1698 return e;
1702 return NULL;
1706 * if we have dev, this function was called because of an -audiodev argument =>
1707 * initialize a new state with it
1708 * if dev == NULL => legacy implicit initialization, return the already created
1709 * state or create a new one
1711 static AudioState *audio_init(Audiodev *dev, const char *name)
1713 static bool atexit_registered;
1714 size_t i;
1715 int done = 0;
1716 const char *drvname = NULL;
1717 VMChangeStateEntry *e;
1718 AudioState *s;
1719 struct audio_driver *driver;
1720 /* silence gcc warning about uninitialized variable */
1721 AudiodevListHead head = QSIMPLEQ_HEAD_INITIALIZER(head);
1723 if (using_spice) {
1725 * When using spice allow the spice audio driver being picked
1726 * as default.
1728 * Temporary hack. Using audio devices without explicit
1729 * audiodev= property is already deprecated. Same goes for
1730 * the -soundhw switch. Once this support gets finally
1731 * removed we can also drop the concept of a default audio
1732 * backend and this can go away.
1734 driver = audio_driver_lookup("spice");
1735 if (driver) {
1736 driver->can_be_default = 1;
1740 if (dev) {
1741 /* -audiodev option */
1742 legacy_config = false;
1743 drvname = AudiodevDriver_str(dev->driver);
1744 } else if (!QTAILQ_EMPTY(&audio_states)) {
1745 if (!legacy_config) {
1746 dolog("Device %s: audiodev default parameter is deprecated, please "
1747 "specify audiodev=%s\n", name,
1748 QTAILQ_FIRST(&audio_states)->dev->id);
1750 return QTAILQ_FIRST(&audio_states);
1751 } else {
1752 /* legacy implicit initialization */
1753 head = audio_handle_legacy_opts();
1755 * In case of legacy initialization, all Audiodevs in the list will have
1756 * the same configuration (except the driver), so it doesn't matter which
1757 * one we chose. We need an Audiodev to set up AudioState before we can
1758 * init a driver. Also note that dev at this point is still in the
1759 * list.
1761 dev = QSIMPLEQ_FIRST(&head)->dev;
1762 audio_validate_opts(dev, &error_abort);
1765 s = g_new0(AudioState, 1);
1766 s->dev = dev;
1768 QLIST_INIT (&s->hw_head_out);
1769 QLIST_INIT (&s->hw_head_in);
1770 QLIST_INIT (&s->cap_head);
1771 if (!atexit_registered) {
1772 atexit(audio_cleanup);
1773 atexit_registered = true;
1776 s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1778 s->nb_hw_voices_out = audio_get_pdo_out(dev)->voices;
1779 s->nb_hw_voices_in = audio_get_pdo_in(dev)->voices;
1781 if (s->nb_hw_voices_out < 1) {
1782 dolog ("Bogus number of playback voices %d, setting to 1\n",
1783 s->nb_hw_voices_out);
1784 s->nb_hw_voices_out = 1;
1787 if (s->nb_hw_voices_in < 0) {
1788 dolog ("Bogus number of capture voices %d, setting to 0\n",
1789 s->nb_hw_voices_in);
1790 s->nb_hw_voices_in = 0;
1793 if (drvname) {
1794 driver = audio_driver_lookup(drvname);
1795 if (driver) {
1796 done = !audio_driver_init(s, driver, true, dev);
1797 } else {
1798 dolog ("Unknown audio driver `%s'\n", drvname);
1800 if (!done) {
1801 free_audio_state(s);
1802 return NULL;
1804 } else {
1805 for (i = 0; audio_prio_list[i]; i++) {
1806 AudiodevListEntry *e = audiodev_find(&head, audio_prio_list[i]);
1807 driver = audio_driver_lookup(audio_prio_list[i]);
1809 if (e && driver) {
1810 s->dev = dev = e->dev;
1811 audio_validate_opts(dev, &error_abort);
1812 done = !audio_driver_init(s, driver, false, dev);
1813 if (done) {
1814 e->dev = NULL;
1815 break;
1820 audio_free_audiodev_list(&head);
1822 if (!done) {
1823 driver = audio_driver_lookup("none");
1824 done = !audio_driver_init(s, driver, false, dev);
1825 assert(done);
1826 dolog("warning: Using timer based audio emulation\n");
1829 if (dev->timer_period <= 0) {
1830 s->period_ticks = 1;
1831 } else {
1832 s->period_ticks = dev->timer_period * (int64_t)SCALE_US;
1835 e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1836 if (!e) {
1837 dolog ("warning: Could not register change state handler\n"
1838 "(Audio can continue looping even after stopping the VM)\n");
1841 QTAILQ_INSERT_TAIL(&audio_states, s, list);
1842 QLIST_INIT (&s->card_head);
1843 vmstate_register (NULL, 0, &vmstate_audio, s);
1844 return s;
1847 void audio_free_audiodev_list(AudiodevListHead *head)
1849 AudiodevListEntry *e;
1850 while ((e = QSIMPLEQ_FIRST(head))) {
1851 QSIMPLEQ_REMOVE_HEAD(head, next);
1852 qapi_free_Audiodev(e->dev);
1853 g_free(e);
1857 void AUD_register_card (const char *name, QEMUSoundCard *card)
1859 if (!card->state) {
1860 card->state = audio_init(NULL, name);
1863 card->name = g_strdup (name);
1864 memset (&card->entries, 0, sizeof (card->entries));
1865 QLIST_INSERT_HEAD(&card->state->card_head, card, entries);
1868 void AUD_remove_card (QEMUSoundCard *card)
1870 QLIST_REMOVE (card, entries);
1871 g_free (card->name);
1874 static struct audio_pcm_ops capture_pcm_ops;
1876 CaptureVoiceOut *AUD_add_capture(
1877 AudioState *s,
1878 struct audsettings *as,
1879 struct audio_capture_ops *ops,
1880 void *cb_opaque
1883 CaptureVoiceOut *cap;
1884 struct capture_callback *cb;
1886 if (!s) {
1887 if (!legacy_config) {
1888 dolog("Capturing without setting an audiodev is deprecated\n");
1890 s = audio_init(NULL, NULL);
1893 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1894 dolog("Can't capture with mixeng disabled\n");
1895 return NULL;
1898 if (audio_validate_settings (as)) {
1899 dolog ("Invalid settings were passed when trying to add capture\n");
1900 audio_print_settings (as);
1901 return NULL;
1904 cb = g_malloc0(sizeof(*cb));
1905 cb->ops = *ops;
1906 cb->opaque = cb_opaque;
1908 cap = audio_pcm_capture_find_specific(s, as);
1909 if (cap) {
1910 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1911 return cap;
1912 } else {
1913 HWVoiceOut *hw;
1914 CaptureVoiceOut *cap;
1916 cap = g_malloc0(sizeof(*cap));
1918 hw = &cap->hw;
1919 hw->s = s;
1920 hw->pcm_ops = &capture_pcm_ops;
1921 QLIST_INIT (&hw->sw_head);
1922 QLIST_INIT (&cap->cb_head);
1924 /* XXX find a more elegant way */
1925 hw->samples = 4096 * 4;
1926 audio_pcm_hw_alloc_resources_out(hw);
1928 audio_pcm_init_info (&hw->info, as);
1930 cap->buf = g_malloc0_n(hw->mix_buf->size, hw->info.bytes_per_frame);
1932 if (hw->info.is_float) {
1933 hw->clip = mixeng_clip_float[hw->info.nchannels == 2];
1934 } else {
1935 hw->clip = mixeng_clip
1936 [hw->info.nchannels == 2]
1937 [hw->info.is_signed]
1938 [hw->info.swap_endianness]
1939 [audio_bits_to_index(hw->info.bits)];
1942 QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1943 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1945 QLIST_FOREACH(hw, &s->hw_head_out, entries) {
1946 audio_attach_capture (hw);
1948 return cap;
1952 void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1954 struct capture_callback *cb;
1956 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1957 if (cb->opaque == cb_opaque) {
1958 cb->ops.destroy (cb_opaque);
1959 QLIST_REMOVE (cb, entries);
1960 g_free (cb);
1962 if (!cap->cb_head.lh_first) {
1963 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
1965 while (sw) {
1966 SWVoiceCap *sc = (SWVoiceCap *) sw;
1967 #ifdef DEBUG_CAPTURE
1968 dolog ("freeing %s\n", sw->name);
1969 #endif
1971 sw1 = sw->entries.le_next;
1972 if (sw->rate) {
1973 st_rate_stop (sw->rate);
1974 sw->rate = NULL;
1976 QLIST_REMOVE (sw, entries);
1977 QLIST_REMOVE (sc, entries);
1978 g_free (sc);
1979 sw = sw1;
1981 QLIST_REMOVE (cap, entries);
1982 g_free (cap->hw.mix_buf);
1983 g_free (cap->buf);
1984 g_free (cap);
1986 return;
1991 void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
1993 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1994 audio_set_volume_out(sw, &vol);
1997 void audio_set_volume_out(SWVoiceOut *sw, Volume *vol)
1999 if (sw) {
2000 HWVoiceOut *hw = sw->hw;
2002 sw->vol.mute = vol->mute;
2003 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
2004 sw->vol.r = nominal_volume.l * vol->vol[vol->channels > 1 ? 1 : 0] /
2005 255;
2007 if (hw->pcm_ops->volume_out) {
2008 hw->pcm_ops->volume_out(hw, vol);
2013 void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
2015 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
2016 audio_set_volume_in(sw, &vol);
2019 void audio_set_volume_in(SWVoiceIn *sw, Volume *vol)
2021 if (sw) {
2022 HWVoiceIn *hw = sw->hw;
2024 sw->vol.mute = vol->mute;
2025 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
2026 sw->vol.r = nominal_volume.r * vol->vol[vol->channels > 1 ? 1 : 0] /
2027 255;
2029 if (hw->pcm_ops->volume_in) {
2030 hw->pcm_ops->volume_in(hw, vol);
2035 void audio_create_pdos(Audiodev *dev)
2037 switch (dev->driver) {
2038 #define CASE(DRIVER, driver, pdo_name) \
2039 case AUDIODEV_DRIVER_##DRIVER: \
2040 if (!dev->u.driver.in) { \
2041 dev->u.driver.in = g_malloc0( \
2042 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
2044 if (!dev->u.driver.out) { \
2045 dev->u.driver.out = g_malloc0( \
2046 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
2048 break
2050 CASE(NONE, none, );
2051 #ifdef CONFIG_AUDIO_ALSA
2052 CASE(ALSA, alsa, Alsa);
2053 #endif
2054 #ifdef CONFIG_AUDIO_COREAUDIO
2055 CASE(COREAUDIO, coreaudio, Coreaudio);
2056 #endif
2057 #ifdef CONFIG_DBUS_DISPLAY
2058 CASE(DBUS, dbus, );
2059 #endif
2060 #ifdef CONFIG_AUDIO_DSOUND
2061 CASE(DSOUND, dsound, );
2062 #endif
2063 #ifdef CONFIG_AUDIO_JACK
2064 CASE(JACK, jack, Jack);
2065 #endif
2066 #ifdef CONFIG_AUDIO_OSS
2067 CASE(OSS, oss, Oss);
2068 #endif
2069 #ifdef CONFIG_AUDIO_PA
2070 CASE(PA, pa, Pa);
2071 #endif
2072 #ifdef CONFIG_AUDIO_SDL
2073 CASE(SDL, sdl, Sdl);
2074 #endif
2075 #ifdef CONFIG_AUDIO_SNDIO
2076 CASE(SNDIO, sndio, );
2077 #endif
2078 #ifdef CONFIG_SPICE
2079 CASE(SPICE, spice, );
2080 #endif
2081 CASE(WAV, wav, );
2083 case AUDIODEV_DRIVER__MAX:
2084 abort();
2088 static void audio_validate_per_direction_opts(
2089 AudiodevPerDirectionOptions *pdo, Error **errp)
2091 if (!pdo->has_mixing_engine) {
2092 pdo->has_mixing_engine = true;
2093 pdo->mixing_engine = true;
2095 if (!pdo->has_fixed_settings) {
2096 pdo->has_fixed_settings = true;
2097 pdo->fixed_settings = pdo->mixing_engine;
2099 if (!pdo->fixed_settings &&
2100 (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
2101 error_setg(errp,
2102 "You can't use frequency, channels or format with fixed-settings=off");
2103 return;
2105 if (!pdo->mixing_engine && pdo->fixed_settings) {
2106 error_setg(errp, "You can't use fixed-settings without mixeng");
2107 return;
2110 if (!pdo->has_frequency) {
2111 pdo->has_frequency = true;
2112 pdo->frequency = 44100;
2114 if (!pdo->has_channels) {
2115 pdo->has_channels = true;
2116 pdo->channels = 2;
2118 if (!pdo->has_voices) {
2119 pdo->has_voices = true;
2120 pdo->voices = pdo->mixing_engine ? 1 : INT_MAX;
2122 if (!pdo->has_format) {
2123 pdo->has_format = true;
2124 pdo->format = AUDIO_FORMAT_S16;
2128 static void audio_validate_opts(Audiodev *dev, Error **errp)
2130 Error *err = NULL;
2132 audio_create_pdos(dev);
2134 audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
2135 if (err) {
2136 error_propagate(errp, err);
2137 return;
2140 audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
2141 if (err) {
2142 error_propagate(errp, err);
2143 return;
2146 if (!dev->has_timer_period) {
2147 dev->has_timer_period = true;
2148 dev->timer_period = 10000; /* 100Hz -> 10ms */
2152 void audio_help(void)
2154 int i;
2156 printf("Available audio drivers:\n");
2158 for (i = 0; i < AUDIODEV_DRIVER__MAX; i++) {
2159 audio_driver *driver = audio_driver_lookup(AudiodevDriver_str(i));
2160 if (driver) {
2161 printf("%s\n", driver->name);
2166 void audio_parse_option(const char *opt)
2168 Audiodev *dev = NULL;
2170 if (is_help_option(opt)) {
2171 audio_help();
2172 exit(EXIT_SUCCESS);
2174 Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
2175 visit_type_Audiodev(v, NULL, &dev, &error_fatal);
2176 visit_free(v);
2178 audio_define(dev);
2181 void audio_define(Audiodev *dev)
2183 AudiodevListEntry *e;
2185 audio_validate_opts(dev, &error_fatal);
2187 e = g_new0(AudiodevListEntry, 1);
2188 e->dev = dev;
2189 QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
2192 bool audio_init_audiodevs(void)
2194 AudiodevListEntry *e;
2196 QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2197 if (!audio_init(e->dev, NULL)) {
2198 return false;
2202 return true;
2205 audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
2207 return (audsettings) {
2208 .freq = pdo->frequency,
2209 .nchannels = pdo->channels,
2210 .fmt = pdo->format,
2211 .endianness = AUDIO_HOST_ENDIANNESS,
2215 int audioformat_bytes_per_sample(AudioFormat fmt)
2217 switch (fmt) {
2218 case AUDIO_FORMAT_U8:
2219 case AUDIO_FORMAT_S8:
2220 return 1;
2222 case AUDIO_FORMAT_U16:
2223 case AUDIO_FORMAT_S16:
2224 return 2;
2226 case AUDIO_FORMAT_U32:
2227 case AUDIO_FORMAT_S32:
2228 case AUDIO_FORMAT_F32:
2229 return 4;
2231 case AUDIO_FORMAT__MAX:
2234 abort();
2238 /* frames = freq * usec / 1e6 */
2239 int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
2240 audsettings *as, int def_usecs)
2242 uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
2243 return (as->freq * usecs + 500000) / 1000000;
2246 /* samples = channels * frames = channels * freq * usec / 1e6 */
2247 int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
2248 audsettings *as, int def_usecs)
2250 return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
2254 * bytes = bytes_per_sample * samples =
2255 * bytes_per_sample * channels * freq * usec / 1e6
2257 int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
2258 audsettings *as, int def_usecs)
2260 return audio_buffer_samples(pdo, as, def_usecs) *
2261 audioformat_bytes_per_sample(as->fmt);
2264 AudioState *audio_state_by_name(const char *name)
2266 AudioState *s;
2267 QTAILQ_FOREACH(s, &audio_states, list) {
2268 assert(s->dev);
2269 if (strcmp(name, s->dev->id) == 0) {
2270 return s;
2273 return NULL;
2276 const char *audio_get_id(QEMUSoundCard *card)
2278 if (card->state) {
2279 assert(card->state->dev);
2280 return card->state->dev->id;
2281 } else {
2282 return "";
2286 const char *audio_application_name(void)
2288 const char *vm_name;
2290 vm_name = qemu_get_vm_name();
2291 return vm_name ? vm_name : "qemu";
2294 void audio_rate_start(RateCtl *rate)
2296 memset(rate, 0, sizeof(RateCtl));
2297 rate->start_ticks = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2300 size_t audio_rate_peek_bytes(RateCtl *rate, struct audio_pcm_info *info)
2302 int64_t now;
2303 int64_t ticks;
2304 int64_t bytes;
2305 int64_t frames;
2307 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2308 ticks = now - rate->start_ticks;
2309 bytes = muldiv64(ticks, info->bytes_per_second, NANOSECONDS_PER_SECOND);
2310 frames = (bytes - rate->bytes_sent) / info->bytes_per_frame;
2311 if (frames < 0 || frames > 65536) {
2312 AUD_log(NULL, "Resetting rate control (%" PRId64 " frames)\n", frames);
2313 audio_rate_start(rate);
2314 frames = 0;
2317 return frames * info->bytes_per_frame;
2320 void audio_rate_add_bytes(RateCtl *rate, size_t bytes_used)
2322 rate->bytes_sent += bytes_used;
2325 size_t audio_rate_get_bytes(RateCtl *rate, struct audio_pcm_info *info,
2326 size_t bytes_avail)
2328 size_t bytes;
2330 bytes = audio_rate_peek_bytes(rate, info);
2331 bytes = MIN(bytes, bytes_avail);
2332 audio_rate_add_bytes(rate, bytes);
2334 return bytes;
2337 AudiodevList *qmp_query_audiodevs(Error **errp)
2339 AudiodevList *ret = NULL;
2340 AudiodevListEntry *e;
2341 QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2342 QAPI_LIST_PREPEND(ret, QAPI_CLONE(Audiodev, e->dev));
2344 return ret;