coverity: put NUBus under m68k component
[qemu.git] / audio / audio.c
blob76b8735b44a270736886d7a04c306b81c23e624d
1 /*
2 * QEMU Audio subsystem
4 * Copyright (c) 2003-2005 Vassili Karpov (malc)
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
26 #include "audio.h"
27 #include "migration/vmstate.h"
28 #include "monitor/monitor.h"
29 #include "qemu/timer.h"
30 #include "qapi/error.h"
31 #include "qapi/qobject-input-visitor.h"
32 #include "qapi/qapi-visit-audio.h"
33 #include "qemu/cutils.h"
34 #include "qemu/module.h"
35 #include "sysemu/sysemu.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");
122 return cond;
125 static inline int audio_bits_to_index (int bits)
127 switch (bits) {
128 case 8:
129 return 0;
131 case 16:
132 return 1;
134 case 32:
135 return 2;
137 default:
138 audio_bug ("bits_to_index", 1);
139 AUD_log (NULL, "invalid bits %d\n", bits);
140 abort();
144 void *audio_calloc (const char *funcname, int nmemb, size_t size)
146 int cond;
147 size_t len;
149 len = nmemb * size;
150 cond = !nmemb || !size;
151 cond |= nmemb < 0;
152 cond |= len < size;
154 if (audio_bug ("audio_calloc", cond)) {
155 AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
156 funcname);
157 AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
158 abort();
161 return g_malloc0 (len);
164 void AUD_vlog (const char *cap, const char *fmt, va_list ap)
166 if (cap) {
167 fprintf(stderr, "%s: ", cap);
170 vfprintf(stderr, fmt, ap);
173 void AUD_log (const char *cap, const char *fmt, ...)
175 va_list ap;
177 va_start (ap, fmt);
178 AUD_vlog (cap, fmt, ap);
179 va_end (ap);
182 static void audio_print_settings (struct audsettings *as)
184 dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
186 switch (as->fmt) {
187 case AUDIO_FORMAT_S8:
188 AUD_log (NULL, "S8");
189 break;
190 case AUDIO_FORMAT_U8:
191 AUD_log (NULL, "U8");
192 break;
193 case AUDIO_FORMAT_S16:
194 AUD_log (NULL, "S16");
195 break;
196 case AUDIO_FORMAT_U16:
197 AUD_log (NULL, "U16");
198 break;
199 case AUDIO_FORMAT_S32:
200 AUD_log (NULL, "S32");
201 break;
202 case AUDIO_FORMAT_U32:
203 AUD_log (NULL, "U32");
204 break;
205 case AUDIO_FORMAT_F32:
206 AUD_log (NULL, "F32");
207 break;
208 default:
209 AUD_log (NULL, "invalid(%d)", as->fmt);
210 break;
213 AUD_log (NULL, " endianness=");
214 switch (as->endianness) {
215 case 0:
216 AUD_log (NULL, "little");
217 break;
218 case 1:
219 AUD_log (NULL, "big");
220 break;
221 default:
222 AUD_log (NULL, "invalid");
223 break;
225 AUD_log (NULL, "\n");
228 static int audio_validate_settings (struct audsettings *as)
230 int invalid;
232 invalid = as->nchannels < 1;
233 invalid |= as->endianness != 0 && as->endianness != 1;
235 switch (as->fmt) {
236 case AUDIO_FORMAT_S8:
237 case AUDIO_FORMAT_U8:
238 case AUDIO_FORMAT_S16:
239 case AUDIO_FORMAT_U16:
240 case AUDIO_FORMAT_S32:
241 case AUDIO_FORMAT_U32:
242 case AUDIO_FORMAT_F32:
243 break;
244 default:
245 invalid = 1;
246 break;
249 invalid |= as->freq <= 0;
250 return invalid ? -1 : 0;
253 static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
255 int bits = 8;
256 bool is_signed = false, is_float = false;
258 switch (as->fmt) {
259 case AUDIO_FORMAT_S8:
260 is_signed = true;
261 /* fall through */
262 case AUDIO_FORMAT_U8:
263 break;
265 case AUDIO_FORMAT_S16:
266 is_signed = true;
267 /* fall through */
268 case AUDIO_FORMAT_U16:
269 bits = 16;
270 break;
272 case AUDIO_FORMAT_F32:
273 is_float = true;
274 /* fall through */
275 case AUDIO_FORMAT_S32:
276 is_signed = true;
277 /* fall through */
278 case AUDIO_FORMAT_U32:
279 bits = 32;
280 break;
282 default:
283 abort();
285 return info->freq == as->freq
286 && info->nchannels == as->nchannels
287 && info->is_signed == is_signed
288 && info->is_float == is_float
289 && info->bits == bits
290 && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
293 void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
295 int bits = 8, mul;
296 bool is_signed = false, is_float = false;
298 switch (as->fmt) {
299 case AUDIO_FORMAT_S8:
300 is_signed = true;
301 /* fall through */
302 case AUDIO_FORMAT_U8:
303 mul = 1;
304 break;
306 case AUDIO_FORMAT_S16:
307 is_signed = true;
308 /* fall through */
309 case AUDIO_FORMAT_U16:
310 bits = 16;
311 mul = 2;
312 break;
314 case AUDIO_FORMAT_F32:
315 is_float = true;
316 /* fall through */
317 case AUDIO_FORMAT_S32:
318 is_signed = true;
319 /* fall through */
320 case AUDIO_FORMAT_U32:
321 bits = 32;
322 mul = 4;
323 break;
325 default:
326 abort();
329 info->freq = as->freq;
330 info->bits = bits;
331 info->is_signed = is_signed;
332 info->is_float = is_float;
333 info->nchannels = as->nchannels;
334 info->bytes_per_frame = as->nchannels * mul;
335 info->bytes_per_second = info->freq * info->bytes_per_frame;
336 info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
339 void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
341 if (!len) {
342 return;
345 if (info->is_signed || info->is_float) {
346 memset(buf, 0x00, len * info->bytes_per_frame);
347 } else {
348 switch (info->bits) {
349 case 8:
350 memset(buf, 0x80, len * info->bytes_per_frame);
351 break;
353 case 16:
355 int i;
356 uint16_t *p = buf;
357 short s = INT16_MAX;
359 if (info->swap_endianness) {
360 s = bswap16 (s);
363 for (i = 0; i < len * info->nchannels; i++) {
364 p[i] = s;
367 break;
369 case 32:
371 int i;
372 uint32_t *p = buf;
373 int32_t s = INT32_MAX;
375 if (info->swap_endianness) {
376 s = bswap32 (s);
379 for (i = 0; i < len * info->nchannels; i++) {
380 p[i] = s;
383 break;
385 default:
386 AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
387 info->bits);
388 break;
394 * Capture
396 static void noop_conv (struct st_sample *dst, const void *src, int samples)
398 (void) src;
399 (void) dst;
400 (void) samples;
403 static CaptureVoiceOut *audio_pcm_capture_find_specific(AudioState *s,
404 struct audsettings *as)
406 CaptureVoiceOut *cap;
408 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
409 if (audio_pcm_info_eq (&cap->hw.info, as)) {
410 return cap;
413 return NULL;
416 static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
418 struct capture_callback *cb;
420 #ifdef DEBUG_CAPTURE
421 dolog ("notification %d sent\n", cmd);
422 #endif
423 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
424 cb->ops.notify (cb->opaque, cmd);
428 static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
430 if (cap->hw.enabled != enabled) {
431 audcnotification_e cmd;
432 cap->hw.enabled = enabled;
433 cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
434 audio_notify_capture (cap, cmd);
438 static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
440 HWVoiceOut *hw = &cap->hw;
441 SWVoiceOut *sw;
442 int enabled = 0;
444 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
445 if (sw->active) {
446 enabled = 1;
447 break;
450 audio_capture_maybe_changed (cap, enabled);
453 static void audio_detach_capture (HWVoiceOut *hw)
455 SWVoiceCap *sc = hw->cap_head.lh_first;
457 while (sc) {
458 SWVoiceCap *sc1 = sc->entries.le_next;
459 SWVoiceOut *sw = &sc->sw;
460 CaptureVoiceOut *cap = sc->cap;
461 int was_active = sw->active;
463 if (sw->rate) {
464 st_rate_stop (sw->rate);
465 sw->rate = NULL;
468 QLIST_REMOVE (sw, entries);
469 QLIST_REMOVE (sc, entries);
470 g_free (sc);
471 if (was_active) {
472 /* We have removed soft voice from the capture:
473 this might have changed the overall status of the capture
474 since this might have been the only active voice */
475 audio_recalc_and_notify_capture (cap);
477 sc = sc1;
481 static int audio_attach_capture (HWVoiceOut *hw)
483 AudioState *s = hw->s;
484 CaptureVoiceOut *cap;
486 audio_detach_capture (hw);
487 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
488 SWVoiceCap *sc;
489 SWVoiceOut *sw;
490 HWVoiceOut *hw_cap = &cap->hw;
492 sc = g_malloc0(sizeof(*sc));
494 sc->cap = cap;
495 sw = &sc->sw;
496 sw->hw = hw_cap;
497 sw->info = hw->info;
498 sw->empty = 1;
499 sw->active = hw->enabled;
500 sw->conv = noop_conv;
501 sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
502 sw->vol = nominal_volume;
503 sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
504 if (!sw->rate) {
505 dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
506 g_free (sw);
507 return -1;
509 QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
510 QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
511 #ifdef DEBUG_CAPTURE
512 sw->name = g_strdup_printf ("for %p %d,%d,%d",
513 hw, sw->info.freq, sw->info.bits,
514 sw->info.nchannels);
515 dolog ("Added %s active = %d\n", sw->name, sw->active);
516 #endif
517 if (sw->active) {
518 audio_capture_maybe_changed (cap, 1);
521 return 0;
525 * Hard voice (capture)
527 static size_t audio_pcm_hw_find_min_in (HWVoiceIn *hw)
529 SWVoiceIn *sw;
530 size_t m = hw->total_samples_captured;
532 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
533 if (sw->active) {
534 m = MIN (m, sw->total_hw_samples_acquired);
537 return m;
540 static size_t audio_pcm_hw_get_live_in(HWVoiceIn *hw)
542 size_t live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
543 if (audio_bug(__func__, live > hw->conv_buf->size)) {
544 dolog("live=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
545 abort();
547 return live;
550 static size_t audio_pcm_hw_conv_in(HWVoiceIn *hw, void *pcm_buf, size_t samples)
552 size_t conv = 0;
553 STSampleBuffer *conv_buf = hw->conv_buf;
555 while (samples) {
556 uint8_t *src = advance(pcm_buf, conv * hw->info.bytes_per_frame);
557 size_t proc = MIN(samples, conv_buf->size - conv_buf->pos);
559 hw->conv(conv_buf->samples + conv_buf->pos, src, proc);
560 conv_buf->pos = (conv_buf->pos + proc) % conv_buf->size;
561 samples -= proc;
562 conv += proc;
565 return conv;
569 * Soft voice (capture)
571 static size_t audio_pcm_sw_read(SWVoiceIn *sw, void *buf, size_t size)
573 HWVoiceIn *hw = sw->hw;
574 size_t samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
575 struct st_sample *src, *dst = sw->buf;
577 live = hw->total_samples_captured - sw->total_hw_samples_acquired;
578 if (!live) {
579 return 0;
581 if (audio_bug(__func__, live > hw->conv_buf->size)) {
582 dolog("live_in=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
583 abort();
586 rpos = audio_ring_posb(hw->conv_buf->pos, live, hw->conv_buf->size);
588 samples = size / sw->info.bytes_per_frame;
590 swlim = (live * sw->ratio) >> 32;
591 swlim = MIN (swlim, samples);
593 while (swlim) {
594 src = hw->conv_buf->samples + rpos;
595 if (hw->conv_buf->pos > rpos) {
596 isamp = hw->conv_buf->pos - rpos;
597 } else {
598 isamp = hw->conv_buf->size - rpos;
601 if (!isamp) {
602 break;
604 osamp = swlim;
606 st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
607 swlim -= osamp;
608 rpos = (rpos + isamp) % hw->conv_buf->size;
609 dst += osamp;
610 ret += osamp;
611 total += isamp;
614 if (!hw->pcm_ops->volume_in) {
615 mixeng_volume (sw->buf, ret, &sw->vol);
618 sw->clip (buf, sw->buf, ret);
619 sw->total_hw_samples_acquired += total;
620 return ret * sw->info.bytes_per_frame;
624 * Hard voice (playback)
626 static size_t audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
628 SWVoiceOut *sw;
629 size_t m = SIZE_MAX;
630 int nb_live = 0;
632 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
633 if (sw->active || !sw->empty) {
634 m = MIN (m, sw->total_hw_samples_mixed);
635 nb_live += 1;
639 *nb_livep = nb_live;
640 return m;
643 static size_t audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
645 size_t smin;
646 int nb_live1;
648 smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
649 if (nb_live) {
650 *nb_live = nb_live1;
653 if (nb_live1) {
654 size_t live = smin;
656 if (audio_bug(__func__, live > hw->mix_buf->size)) {
657 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
658 abort();
660 return live;
662 return 0;
665 static size_t audio_pcm_hw_get_free(HWVoiceOut *hw)
667 return (hw->pcm_ops->buffer_get_free ? hw->pcm_ops->buffer_get_free(hw) :
668 INT_MAX) / hw->info.bytes_per_frame;
671 static void audio_pcm_hw_clip_out(HWVoiceOut *hw, void *pcm_buf, size_t len)
673 size_t clipped = 0;
674 size_t pos = hw->mix_buf->pos;
676 while (len) {
677 st_sample *src = hw->mix_buf->samples + pos;
678 uint8_t *dst = advance(pcm_buf, clipped * hw->info.bytes_per_frame);
679 size_t samples_till_end_of_buf = hw->mix_buf->size - pos;
680 size_t samples_to_clip = MIN(len, samples_till_end_of_buf);
682 hw->clip(dst, src, samples_to_clip);
684 pos = (pos + samples_to_clip) % hw->mix_buf->size;
685 len -= samples_to_clip;
686 clipped += samples_to_clip;
691 * Soft voice (playback)
693 static size_t audio_pcm_sw_write(SWVoiceOut *sw, void *buf, size_t size)
695 size_t hwsamples, samples, isamp, osamp, wpos, live, dead, left, blck;
696 size_t hw_free;
697 size_t ret = 0, pos = 0, total = 0;
699 if (!sw) {
700 return size;
703 hwsamples = sw->hw->mix_buf->size;
705 live = sw->total_hw_samples_mixed;
706 if (audio_bug(__func__, live > hwsamples)) {
707 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hwsamples);
708 abort();
711 if (live == hwsamples) {
712 #ifdef DEBUG_OUT
713 dolog ("%s is full %zu\n", sw->name, live);
714 #endif
715 return 0;
718 wpos = (sw->hw->mix_buf->pos + live) % hwsamples;
720 dead = hwsamples - live;
721 hw_free = audio_pcm_hw_get_free(sw->hw);
722 hw_free = hw_free > live ? hw_free - live : 0;
723 samples = ((int64_t)MIN(dead, hw_free) << 32) / sw->ratio;
724 samples = MIN(samples, size / sw->info.bytes_per_frame);
725 if (samples) {
726 sw->conv(sw->buf, buf, samples);
728 if (!sw->hw->pcm_ops->volume_out) {
729 mixeng_volume(sw->buf, samples, &sw->vol);
733 while (samples) {
734 dead = hwsamples - live;
735 left = hwsamples - wpos;
736 blck = MIN (dead, left);
737 if (!blck) {
738 break;
740 isamp = samples;
741 osamp = blck;
742 st_rate_flow_mix (
743 sw->rate,
744 sw->buf + pos,
745 sw->hw->mix_buf->samples + wpos,
746 &isamp,
747 &osamp
749 ret += isamp;
750 samples -= isamp;
751 pos += isamp;
752 live += osamp;
753 wpos = (wpos + osamp) % hwsamples;
754 total += osamp;
757 sw->total_hw_samples_mixed += total;
758 sw->empty = sw->total_hw_samples_mixed == 0;
760 #ifdef DEBUG_OUT
761 dolog (
762 "%s: write size %zu ret %zu total sw %zu\n",
763 SW_NAME (sw),
764 size / sw->info.bytes_per_frame,
765 ret,
766 sw->total_hw_samples_mixed
768 #endif
770 return ret * sw->info.bytes_per_frame;
773 #ifdef DEBUG_AUDIO
774 static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
776 dolog("%s: bits %d, sign %d, float %d, freq %d, nchan %d\n",
777 cap, info->bits, info->is_signed, info->is_float, info->freq,
778 info->nchannels);
780 #endif
782 #define DAC
783 #include "audio_template.h"
784 #undef DAC
785 #include "audio_template.h"
788 * Timer
790 static int audio_is_timer_needed(AudioState *s)
792 HWVoiceIn *hwi = NULL;
793 HWVoiceOut *hwo = NULL;
795 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
796 if (!hwo->poll_mode) {
797 return 1;
800 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
801 if (!hwi->poll_mode) {
802 return 1;
805 return 0;
808 static void audio_reset_timer (AudioState *s)
810 if (audio_is_timer_needed(s)) {
811 timer_mod_anticipate_ns(s->ts,
812 qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
813 if (!s->timer_running) {
814 s->timer_running = true;
815 s->timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
816 trace_audio_timer_start(s->period_ticks / SCALE_MS);
818 } else {
819 timer_del(s->ts);
820 if (s->timer_running) {
821 s->timer_running = false;
822 trace_audio_timer_stop();
827 static void audio_timer (void *opaque)
829 int64_t now, diff;
830 AudioState *s = opaque;
832 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
833 diff = now - s->timer_last;
834 if (diff > s->period_ticks * 3 / 2) {
835 trace_audio_timer_delayed(diff / SCALE_MS);
837 s->timer_last = now;
839 audio_run(s, "timer");
840 audio_reset_timer(s);
844 * Public API
846 size_t AUD_write(SWVoiceOut *sw, void *buf, size_t size)
848 HWVoiceOut *hw;
850 if (!sw) {
851 /* XXX: Consider options */
852 return size;
854 hw = sw->hw;
856 if (!hw->enabled) {
857 dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
858 return 0;
861 if (audio_get_pdo_out(hw->s->dev)->mixing_engine) {
862 return audio_pcm_sw_write(sw, buf, size);
863 } else {
864 return hw->pcm_ops->write(hw, buf, size);
868 size_t AUD_read(SWVoiceIn *sw, void *buf, size_t size)
870 HWVoiceIn *hw;
872 if (!sw) {
873 /* XXX: Consider options */
874 return size;
876 hw = sw->hw;
878 if (!hw->enabled) {
879 dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
880 return 0;
883 if (audio_get_pdo_in(hw->s->dev)->mixing_engine) {
884 return audio_pcm_sw_read(sw, buf, size);
885 } else {
886 return hw->pcm_ops->read(hw, buf, size);
890 int AUD_get_buffer_size_out(SWVoiceOut *sw)
892 return sw->hw->samples * sw->hw->info.bytes_per_frame;
895 void AUD_set_active_out (SWVoiceOut *sw, int on)
897 HWVoiceOut *hw;
899 if (!sw) {
900 return;
903 hw = sw->hw;
904 if (sw->active != on) {
905 AudioState *s = sw->s;
906 SWVoiceOut *temp_sw;
907 SWVoiceCap *sc;
909 if (on) {
910 hw->pending_disable = 0;
911 if (!hw->enabled) {
912 hw->enabled = 1;
913 if (s->vm_running) {
914 if (hw->pcm_ops->enable_out) {
915 hw->pcm_ops->enable_out(hw, true);
917 audio_reset_timer (s);
920 } else {
921 if (hw->enabled) {
922 int nb_active = 0;
924 for (temp_sw = hw->sw_head.lh_first; temp_sw;
925 temp_sw = temp_sw->entries.le_next) {
926 nb_active += temp_sw->active != 0;
929 hw->pending_disable = nb_active == 1;
933 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
934 sc->sw.active = hw->enabled;
935 if (hw->enabled) {
936 audio_capture_maybe_changed (sc->cap, 1);
939 sw->active = on;
943 void AUD_set_active_in (SWVoiceIn *sw, int on)
945 HWVoiceIn *hw;
947 if (!sw) {
948 return;
951 hw = sw->hw;
952 if (sw->active != on) {
953 AudioState *s = sw->s;
954 SWVoiceIn *temp_sw;
956 if (on) {
957 if (!hw->enabled) {
958 hw->enabled = 1;
959 if (s->vm_running) {
960 if (hw->pcm_ops->enable_in) {
961 hw->pcm_ops->enable_in(hw, true);
963 audio_reset_timer (s);
966 sw->total_hw_samples_acquired = hw->total_samples_captured;
967 } else {
968 if (hw->enabled) {
969 int nb_active = 0;
971 for (temp_sw = hw->sw_head.lh_first; temp_sw;
972 temp_sw = temp_sw->entries.le_next) {
973 nb_active += temp_sw->active != 0;
976 if (nb_active == 1) {
977 hw->enabled = 0;
978 if (hw->pcm_ops->enable_in) {
979 hw->pcm_ops->enable_in(hw, false);
984 sw->active = on;
988 static size_t audio_get_avail (SWVoiceIn *sw)
990 size_t live;
992 if (!sw) {
993 return 0;
996 live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
997 if (audio_bug(__func__, live > sw->hw->conv_buf->size)) {
998 dolog("live=%zu sw->hw->conv_buf->size=%zu\n", live,
999 sw->hw->conv_buf->size);
1000 abort();
1003 ldebug (
1004 "%s: get_avail live %zu ret %" PRId64 "\n",
1005 SW_NAME (sw),
1006 live, (((int64_t) live << 32) / sw->ratio) * sw->info.bytes_per_frame
1009 return (((int64_t) live << 32) / sw->ratio) * sw->info.bytes_per_frame;
1012 static size_t audio_sw_bytes_free(SWVoiceOut *sw, size_t free)
1014 return (((int64_t)free << 32) / sw->ratio) * sw->info.bytes_per_frame;
1017 static size_t audio_get_free(SWVoiceOut *sw)
1019 size_t live, dead;
1021 if (!sw) {
1022 return 0;
1025 live = sw->total_hw_samples_mixed;
1027 if (audio_bug(__func__, live > sw->hw->mix_buf->size)) {
1028 dolog("live=%zu sw->hw->mix_buf->size=%zu\n", live,
1029 sw->hw->mix_buf->size);
1030 abort();
1033 dead = sw->hw->mix_buf->size - live;
1035 #ifdef DEBUG_OUT
1036 dolog("%s: get_free live %zu dead %zu sw_bytes %zu\n",
1037 SW_NAME(sw), live, dead, audio_sw_bytes_free(sw, dead));
1038 #endif
1040 return dead;
1043 static void audio_capture_mix_and_clear(HWVoiceOut *hw, size_t rpos,
1044 size_t samples)
1046 size_t n;
1048 if (hw->enabled) {
1049 SWVoiceCap *sc;
1051 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1052 SWVoiceOut *sw = &sc->sw;
1053 int rpos2 = rpos;
1055 n = samples;
1056 while (n) {
1057 size_t till_end_of_hw = hw->mix_buf->size - rpos2;
1058 size_t to_write = MIN(till_end_of_hw, n);
1059 size_t bytes = to_write * hw->info.bytes_per_frame;
1060 size_t written;
1062 sw->buf = hw->mix_buf->samples + rpos2;
1063 written = audio_pcm_sw_write (sw, NULL, bytes);
1064 if (written - bytes) {
1065 dolog("Could not mix %zu bytes into a capture "
1066 "buffer, mixed %zu\n",
1067 bytes, written);
1068 break;
1070 n -= to_write;
1071 rpos2 = (rpos2 + to_write) % hw->mix_buf->size;
1076 n = MIN(samples, hw->mix_buf->size - rpos);
1077 mixeng_clear(hw->mix_buf->samples + rpos, n);
1078 mixeng_clear(hw->mix_buf->samples, samples - n);
1081 static size_t audio_pcm_hw_run_out(HWVoiceOut *hw, size_t live)
1083 size_t clipped = 0;
1085 while (live) {
1086 size_t size = live * hw->info.bytes_per_frame;
1087 size_t decr, proc;
1088 void *buf = hw->pcm_ops->get_buffer_out(hw, &size);
1090 if (size == 0) {
1091 break;
1094 decr = MIN(size / hw->info.bytes_per_frame, live);
1095 if (buf) {
1096 audio_pcm_hw_clip_out(hw, buf, decr);
1098 proc = hw->pcm_ops->put_buffer_out(hw, buf,
1099 decr * hw->info.bytes_per_frame) /
1100 hw->info.bytes_per_frame;
1102 live -= proc;
1103 clipped += proc;
1104 hw->mix_buf->pos = (hw->mix_buf->pos + proc) % hw->mix_buf->size;
1106 if (proc == 0 || proc < decr) {
1107 break;
1111 if (hw->pcm_ops->run_buffer_out) {
1112 hw->pcm_ops->run_buffer_out(hw);
1115 return clipped;
1118 static void audio_run_out (AudioState *s)
1120 HWVoiceOut *hw = NULL;
1121 SWVoiceOut *sw;
1123 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1124 while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1125 /* there is exactly 1 sw for each hw with no mixeng */
1126 sw = hw->sw_head.lh_first;
1128 if (hw->pending_disable) {
1129 hw->enabled = 0;
1130 hw->pending_disable = 0;
1131 if (hw->pcm_ops->enable_out) {
1132 hw->pcm_ops->enable_out(hw, false);
1136 if (sw->active) {
1137 sw->callback.fn(sw->callback.opaque, INT_MAX);
1140 return;
1143 while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1144 size_t played, live, prev_rpos;
1145 size_t hw_free = audio_pcm_hw_get_free(hw);
1146 int nb_live;
1148 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1149 if (sw->active) {
1150 size_t sw_free = audio_get_free(sw);
1151 size_t free;
1153 if (hw_free > sw->total_hw_samples_mixed) {
1154 free = audio_sw_bytes_free(sw,
1155 MIN(sw_free, hw_free - sw->total_hw_samples_mixed));
1156 } else {
1157 free = 0;
1159 if (free > 0) {
1160 sw->callback.fn(sw->callback.opaque, free);
1165 live = audio_pcm_hw_get_live_out (hw, &nb_live);
1166 if (!nb_live) {
1167 live = 0;
1170 if (audio_bug(__func__, live > hw->mix_buf->size)) {
1171 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
1172 abort();
1175 if (hw->pending_disable && !nb_live) {
1176 SWVoiceCap *sc;
1177 #ifdef DEBUG_OUT
1178 dolog ("Disabling voice\n");
1179 #endif
1180 hw->enabled = 0;
1181 hw->pending_disable = 0;
1182 if (hw->pcm_ops->enable_out) {
1183 hw->pcm_ops->enable_out(hw, false);
1185 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1186 sc->sw.active = 0;
1187 audio_recalc_and_notify_capture (sc->cap);
1189 continue;
1192 if (!live) {
1193 if (hw->pcm_ops->run_buffer_out) {
1194 hw->pcm_ops->run_buffer_out(hw);
1196 continue;
1199 prev_rpos = hw->mix_buf->pos;
1200 played = audio_pcm_hw_run_out(hw, live);
1201 replay_audio_out(&played);
1202 if (audio_bug(__func__, hw->mix_buf->pos >= hw->mix_buf->size)) {
1203 dolog("hw->mix_buf->pos=%zu hw->mix_buf->size=%zu played=%zu\n",
1204 hw->mix_buf->pos, hw->mix_buf->size, played);
1205 abort();
1208 #ifdef DEBUG_OUT
1209 dolog("played=%zu\n", played);
1210 #endif
1212 if (played) {
1213 hw->ts_helper += played;
1214 audio_capture_mix_and_clear (hw, prev_rpos, played);
1217 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1218 if (!sw->active && sw->empty) {
1219 continue;
1222 if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1223 dolog("played=%zu sw->total_hw_samples_mixed=%zu\n",
1224 played, sw->total_hw_samples_mixed);
1225 abort();
1228 sw->total_hw_samples_mixed -= played;
1230 if (!sw->total_hw_samples_mixed) {
1231 sw->empty = 1;
1237 static size_t audio_pcm_hw_run_in(HWVoiceIn *hw, size_t samples)
1239 size_t conv = 0;
1241 if (hw->pcm_ops->run_buffer_in) {
1242 hw->pcm_ops->run_buffer_in(hw);
1245 while (samples) {
1246 size_t proc;
1247 size_t size = samples * hw->info.bytes_per_frame;
1248 void *buf = hw->pcm_ops->get_buffer_in(hw, &size);
1250 assert(size % hw->info.bytes_per_frame == 0);
1251 if (size == 0) {
1252 break;
1255 proc = audio_pcm_hw_conv_in(hw, buf, size / hw->info.bytes_per_frame);
1257 samples -= proc;
1258 conv += proc;
1259 hw->pcm_ops->put_buffer_in(hw, buf, proc * hw->info.bytes_per_frame);
1262 return conv;
1265 static void audio_run_in (AudioState *s)
1267 HWVoiceIn *hw = NULL;
1269 if (!audio_get_pdo_in(s->dev)->mixing_engine) {
1270 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1271 /* there is exactly 1 sw for each hw with no mixeng */
1272 SWVoiceIn *sw = hw->sw_head.lh_first;
1273 if (sw->active) {
1274 sw->callback.fn(sw->callback.opaque, INT_MAX);
1277 return;
1280 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1281 SWVoiceIn *sw;
1282 size_t captured = 0, min;
1284 if (replay_mode != REPLAY_MODE_PLAY) {
1285 captured = audio_pcm_hw_run_in(
1286 hw, hw->conv_buf->size - audio_pcm_hw_get_live_in(hw));
1288 replay_audio_in(&captured, hw->conv_buf->samples, &hw->conv_buf->pos,
1289 hw->conv_buf->size);
1291 min = audio_pcm_hw_find_min_in (hw);
1292 hw->total_samples_captured += captured - min;
1293 hw->ts_helper += captured;
1295 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1296 sw->total_hw_samples_acquired -= min;
1298 if (sw->active) {
1299 size_t avail;
1301 avail = audio_get_avail (sw);
1302 if (avail > 0) {
1303 sw->callback.fn (sw->callback.opaque, avail);
1310 static void audio_run_capture (AudioState *s)
1312 CaptureVoiceOut *cap;
1314 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1315 size_t live, rpos, captured;
1316 HWVoiceOut *hw = &cap->hw;
1317 SWVoiceOut *sw;
1319 captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1320 rpos = hw->mix_buf->pos;
1321 while (live) {
1322 size_t left = hw->mix_buf->size - rpos;
1323 size_t to_capture = MIN(live, left);
1324 struct st_sample *src;
1325 struct capture_callback *cb;
1327 src = hw->mix_buf->samples + rpos;
1328 hw->clip (cap->buf, src, to_capture);
1329 mixeng_clear (src, to_capture);
1331 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1332 cb->ops.capture (cb->opaque, cap->buf,
1333 to_capture * hw->info.bytes_per_frame);
1335 rpos = (rpos + to_capture) % hw->mix_buf->size;
1336 live -= to_capture;
1338 hw->mix_buf->pos = rpos;
1340 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1341 if (!sw->active && sw->empty) {
1342 continue;
1345 if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1346 dolog("captured=%zu sw->total_hw_samples_mixed=%zu\n",
1347 captured, sw->total_hw_samples_mixed);
1348 abort();
1351 sw->total_hw_samples_mixed -= captured;
1352 sw->empty = sw->total_hw_samples_mixed == 0;
1357 void audio_run(AudioState *s, const char *msg)
1359 audio_run_out(s);
1360 audio_run_in(s);
1361 audio_run_capture(s);
1363 #ifdef DEBUG_POLL
1365 static double prevtime;
1366 double currtime;
1367 struct timeval tv;
1369 if (gettimeofday (&tv, NULL)) {
1370 perror ("audio_run: gettimeofday");
1371 return;
1374 currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1375 dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1376 prevtime = currtime;
1378 #endif
1381 void audio_generic_run_buffer_in(HWVoiceIn *hw)
1383 if (unlikely(!hw->buf_emul)) {
1384 hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1385 hw->buf_emul = g_malloc(hw->size_emul);
1386 hw->pos_emul = hw->pending_emul = 0;
1389 while (hw->pending_emul < hw->size_emul) {
1390 size_t read_len = MIN(hw->size_emul - hw->pos_emul,
1391 hw->size_emul - hw->pending_emul);
1392 size_t read = hw->pcm_ops->read(hw, hw->buf_emul + hw->pos_emul,
1393 read_len);
1394 hw->pending_emul += read;
1395 hw->pos_emul = (hw->pos_emul + read) % hw->size_emul;
1396 if (read < read_len) {
1397 break;
1402 void *audio_generic_get_buffer_in(HWVoiceIn *hw, size_t *size)
1404 size_t start;
1406 start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1407 assert(start < hw->size_emul);
1409 *size = MIN(*size, hw->pending_emul);
1410 *size = MIN(*size, hw->size_emul - start);
1411 return hw->buf_emul + start;
1414 void audio_generic_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
1416 assert(size <= hw->pending_emul);
1417 hw->pending_emul -= size;
1420 size_t audio_generic_buffer_get_free(HWVoiceOut *hw)
1422 if (hw->buf_emul) {
1423 return hw->size_emul - hw->pending_emul;
1424 } else {
1425 return hw->samples * hw->info.bytes_per_frame;
1429 void audio_generic_run_buffer_out(HWVoiceOut *hw)
1431 while (hw->pending_emul) {
1432 size_t write_len, written, start;
1434 start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1435 assert(start < hw->size_emul);
1437 write_len = MIN(hw->pending_emul, hw->size_emul - start);
1439 written = hw->pcm_ops->write(hw, hw->buf_emul + start, write_len);
1440 hw->pending_emul -= written;
1442 if (written < write_len) {
1443 break;
1448 void *audio_generic_get_buffer_out(HWVoiceOut *hw, size_t *size)
1450 if (unlikely(!hw->buf_emul)) {
1451 hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1452 hw->buf_emul = g_malloc(hw->size_emul);
1453 hw->pos_emul = hw->pending_emul = 0;
1456 *size = MIN(hw->size_emul - hw->pending_emul,
1457 hw->size_emul - hw->pos_emul);
1458 return hw->buf_emul + hw->pos_emul;
1461 size_t audio_generic_put_buffer_out(HWVoiceOut *hw, void *buf, size_t size)
1463 assert(buf == hw->buf_emul + hw->pos_emul &&
1464 size + hw->pending_emul <= hw->size_emul);
1466 hw->pending_emul += size;
1467 hw->pos_emul = (hw->pos_emul + size) % hw->size_emul;
1469 return size;
1472 size_t audio_generic_write(HWVoiceOut *hw, void *buf, size_t size)
1474 size_t total = 0;
1476 if (hw->pcm_ops->buffer_get_free) {
1477 size_t free = hw->pcm_ops->buffer_get_free(hw);
1479 size = MIN(size, free);
1482 while (total < size) {
1483 size_t dst_size = size - total;
1484 size_t copy_size, proc;
1485 void *dst = hw->pcm_ops->get_buffer_out(hw, &dst_size);
1487 if (dst_size == 0) {
1488 break;
1491 copy_size = MIN(size - total, dst_size);
1492 if (dst) {
1493 memcpy(dst, (char *)buf + total, copy_size);
1495 proc = hw->pcm_ops->put_buffer_out(hw, dst, copy_size);
1496 total += proc;
1498 if (proc == 0 || proc < copy_size) {
1499 break;
1503 if (hw->pcm_ops->run_buffer_out) {
1504 hw->pcm_ops->run_buffer_out(hw);
1507 return total;
1510 size_t audio_generic_read(HWVoiceIn *hw, void *buf, size_t size)
1512 size_t total = 0;
1514 if (hw->pcm_ops->run_buffer_in) {
1515 hw->pcm_ops->run_buffer_in(hw);
1518 while (total < size) {
1519 size_t src_size = size - total;
1520 void *src = hw->pcm_ops->get_buffer_in(hw, &src_size);
1522 if (src_size == 0) {
1523 break;
1526 memcpy((char *)buf + total, src, src_size);
1527 hw->pcm_ops->put_buffer_in(hw, src, src_size);
1528 total += src_size;
1531 return total;
1534 static int audio_driver_init(AudioState *s, struct audio_driver *drv,
1535 bool msg, Audiodev *dev)
1537 s->drv_opaque = drv->init(dev);
1539 if (s->drv_opaque) {
1540 if (!drv->pcm_ops->get_buffer_in) {
1541 drv->pcm_ops->get_buffer_in = audio_generic_get_buffer_in;
1542 drv->pcm_ops->put_buffer_in = audio_generic_put_buffer_in;
1544 if (!drv->pcm_ops->get_buffer_out) {
1545 drv->pcm_ops->get_buffer_out = audio_generic_get_buffer_out;
1546 drv->pcm_ops->put_buffer_out = audio_generic_put_buffer_out;
1549 audio_init_nb_voices_out(s, drv);
1550 audio_init_nb_voices_in(s, drv);
1551 s->drv = drv;
1552 return 0;
1553 } else {
1554 if (msg) {
1555 dolog("Could not init `%s' audio driver\n", drv->name);
1557 return -1;
1561 static void audio_vm_change_state_handler (void *opaque, bool running,
1562 RunState state)
1564 AudioState *s = opaque;
1565 HWVoiceOut *hwo = NULL;
1566 HWVoiceIn *hwi = NULL;
1568 s->vm_running = running;
1569 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
1570 if (hwo->pcm_ops->enable_out) {
1571 hwo->pcm_ops->enable_out(hwo, running);
1575 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
1576 if (hwi->pcm_ops->enable_in) {
1577 hwi->pcm_ops->enable_in(hwi, running);
1580 audio_reset_timer (s);
1583 static void free_audio_state(AudioState *s)
1585 HWVoiceOut *hwo, *hwon;
1586 HWVoiceIn *hwi, *hwin;
1588 QLIST_FOREACH_SAFE(hwo, &s->hw_head_out, entries, hwon) {
1589 SWVoiceCap *sc;
1591 if (hwo->enabled && hwo->pcm_ops->enable_out) {
1592 hwo->pcm_ops->enable_out(hwo, false);
1594 hwo->pcm_ops->fini_out (hwo);
1596 for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1597 CaptureVoiceOut *cap = sc->cap;
1598 struct capture_callback *cb;
1600 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1601 cb->ops.destroy (cb->opaque);
1604 QLIST_REMOVE(hwo, entries);
1607 QLIST_FOREACH_SAFE(hwi, &s->hw_head_in, entries, hwin) {
1608 if (hwi->enabled && hwi->pcm_ops->enable_in) {
1609 hwi->pcm_ops->enable_in(hwi, false);
1611 hwi->pcm_ops->fini_in (hwi);
1612 QLIST_REMOVE(hwi, entries);
1615 if (s->drv) {
1616 s->drv->fini (s->drv_opaque);
1617 s->drv = NULL;
1620 if (s->dev) {
1621 qapi_free_Audiodev(s->dev);
1622 s->dev = NULL;
1625 if (s->ts) {
1626 timer_free(s->ts);
1627 s->ts = NULL;
1630 g_free(s);
1633 void audio_cleanup(void)
1635 while (!QTAILQ_EMPTY(&audio_states)) {
1636 AudioState *s = QTAILQ_FIRST(&audio_states);
1637 QTAILQ_REMOVE(&audio_states, s, list);
1638 free_audio_state(s);
1642 static bool vmstate_audio_needed(void *opaque)
1645 * Never needed, this vmstate only exists in case
1646 * an old qemu sends it to us.
1648 return false;
1651 static const VMStateDescription vmstate_audio = {
1652 .name = "audio",
1653 .version_id = 1,
1654 .minimum_version_id = 1,
1655 .needed = vmstate_audio_needed,
1656 .fields = (VMStateField[]) {
1657 VMSTATE_END_OF_LIST()
1661 static void audio_validate_opts(Audiodev *dev, Error **errp);
1663 static AudiodevListEntry *audiodev_find(
1664 AudiodevListHead *head, const char *drvname)
1666 AudiodevListEntry *e;
1667 QSIMPLEQ_FOREACH(e, head, next) {
1668 if (strcmp(AudiodevDriver_str(e->dev->driver), drvname) == 0) {
1669 return e;
1673 return NULL;
1677 * if we have dev, this function was called because of an -audiodev argument =>
1678 * initialize a new state with it
1679 * if dev == NULL => legacy implicit initialization, return the already created
1680 * state or create a new one
1682 static AudioState *audio_init(Audiodev *dev, const char *name)
1684 static bool atexit_registered;
1685 size_t i;
1686 int done = 0;
1687 const char *drvname = NULL;
1688 VMChangeStateEntry *e;
1689 AudioState *s;
1690 struct audio_driver *driver;
1691 /* silence gcc warning about uninitialized variable */
1692 AudiodevListHead head = QSIMPLEQ_HEAD_INITIALIZER(head);
1694 if (using_spice) {
1696 * When using spice allow the spice audio driver being picked
1697 * as default.
1699 * Temporary hack. Using audio devices without explicit
1700 * audiodev= property is already deprecated. Same goes for
1701 * the -soundhw switch. Once this support gets finally
1702 * removed we can also drop the concept of a default audio
1703 * backend and this can go away.
1705 driver = audio_driver_lookup("spice");
1706 if (driver) {
1707 driver->can_be_default = 1;
1711 if (dev) {
1712 /* -audiodev option */
1713 legacy_config = false;
1714 drvname = AudiodevDriver_str(dev->driver);
1715 } else if (!QTAILQ_EMPTY(&audio_states)) {
1716 if (!legacy_config) {
1717 dolog("Device %s: audiodev default parameter is deprecated, please "
1718 "specify audiodev=%s\n", name,
1719 QTAILQ_FIRST(&audio_states)->dev->id);
1721 return QTAILQ_FIRST(&audio_states);
1722 } else {
1723 /* legacy implicit initialization */
1724 head = audio_handle_legacy_opts();
1726 * In case of legacy initialization, all Audiodevs in the list will have
1727 * the same configuration (except the driver), so it doesn't matter which
1728 * one we chose. We need an Audiodev to set up AudioState before we can
1729 * init a driver. Also note that dev at this point is still in the
1730 * list.
1732 dev = QSIMPLEQ_FIRST(&head)->dev;
1733 audio_validate_opts(dev, &error_abort);
1736 s = g_new0(AudioState, 1);
1737 s->dev = dev;
1739 QLIST_INIT (&s->hw_head_out);
1740 QLIST_INIT (&s->hw_head_in);
1741 QLIST_INIT (&s->cap_head);
1742 if (!atexit_registered) {
1743 atexit(audio_cleanup);
1744 atexit_registered = true;
1747 s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1749 s->nb_hw_voices_out = audio_get_pdo_out(dev)->voices;
1750 s->nb_hw_voices_in = audio_get_pdo_in(dev)->voices;
1752 if (s->nb_hw_voices_out <= 0) {
1753 dolog ("Bogus number of playback voices %d, setting to 1\n",
1754 s->nb_hw_voices_out);
1755 s->nb_hw_voices_out = 1;
1758 if (s->nb_hw_voices_in <= 0) {
1759 dolog ("Bogus number of capture voices %d, setting to 0\n",
1760 s->nb_hw_voices_in);
1761 s->nb_hw_voices_in = 0;
1764 if (drvname) {
1765 driver = audio_driver_lookup(drvname);
1766 if (driver) {
1767 done = !audio_driver_init(s, driver, true, dev);
1768 } else {
1769 dolog ("Unknown audio driver `%s'\n", drvname);
1771 if (!done) {
1772 free_audio_state(s);
1773 return NULL;
1775 } else {
1776 for (i = 0; audio_prio_list[i]; i++) {
1777 AudiodevListEntry *e = audiodev_find(&head, audio_prio_list[i]);
1778 driver = audio_driver_lookup(audio_prio_list[i]);
1780 if (e && driver) {
1781 s->dev = dev = e->dev;
1782 audio_validate_opts(dev, &error_abort);
1783 done = !audio_driver_init(s, driver, false, dev);
1784 if (done) {
1785 e->dev = NULL;
1786 break;
1791 audio_free_audiodev_list(&head);
1793 if (!done) {
1794 driver = audio_driver_lookup("none");
1795 done = !audio_driver_init(s, driver, false, dev);
1796 assert(done);
1797 dolog("warning: Using timer based audio emulation\n");
1800 if (dev->timer_period <= 0) {
1801 s->period_ticks = 1;
1802 } else {
1803 s->period_ticks = dev->timer_period * (int64_t)SCALE_US;
1806 e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1807 if (!e) {
1808 dolog ("warning: Could not register change state handler\n"
1809 "(Audio can continue looping even after stopping the VM)\n");
1812 QTAILQ_INSERT_TAIL(&audio_states, s, list);
1813 QLIST_INIT (&s->card_head);
1814 vmstate_register (NULL, 0, &vmstate_audio, s);
1815 return s;
1818 void audio_free_audiodev_list(AudiodevListHead *head)
1820 AudiodevListEntry *e;
1821 while ((e = QSIMPLEQ_FIRST(head))) {
1822 QSIMPLEQ_REMOVE_HEAD(head, next);
1823 qapi_free_Audiodev(e->dev);
1824 g_free(e);
1828 void AUD_register_card (const char *name, QEMUSoundCard *card)
1830 if (!card->state) {
1831 card->state = audio_init(NULL, name);
1834 card->name = g_strdup (name);
1835 memset (&card->entries, 0, sizeof (card->entries));
1836 QLIST_INSERT_HEAD(&card->state->card_head, card, entries);
1839 void AUD_remove_card (QEMUSoundCard *card)
1841 QLIST_REMOVE (card, entries);
1842 g_free (card->name);
1845 static struct audio_pcm_ops capture_pcm_ops;
1847 CaptureVoiceOut *AUD_add_capture(
1848 AudioState *s,
1849 struct audsettings *as,
1850 struct audio_capture_ops *ops,
1851 void *cb_opaque
1854 CaptureVoiceOut *cap;
1855 struct capture_callback *cb;
1857 if (!s) {
1858 if (!legacy_config) {
1859 dolog("Capturing without setting an audiodev is deprecated\n");
1861 s = audio_init(NULL, NULL);
1864 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1865 dolog("Can't capture with mixeng disabled\n");
1866 return NULL;
1869 if (audio_validate_settings (as)) {
1870 dolog ("Invalid settings were passed when trying to add capture\n");
1871 audio_print_settings (as);
1872 return NULL;
1875 cb = g_malloc0(sizeof(*cb));
1876 cb->ops = *ops;
1877 cb->opaque = cb_opaque;
1879 cap = audio_pcm_capture_find_specific(s, as);
1880 if (cap) {
1881 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1882 return cap;
1883 } else {
1884 HWVoiceOut *hw;
1885 CaptureVoiceOut *cap;
1887 cap = g_malloc0(sizeof(*cap));
1889 hw = &cap->hw;
1890 hw->s = s;
1891 hw->pcm_ops = &capture_pcm_ops;
1892 QLIST_INIT (&hw->sw_head);
1893 QLIST_INIT (&cap->cb_head);
1895 /* XXX find a more elegant way */
1896 hw->samples = 4096 * 4;
1897 audio_pcm_hw_alloc_resources_out(hw);
1899 audio_pcm_init_info (&hw->info, as);
1901 cap->buf = g_malloc0_n(hw->mix_buf->size, hw->info.bytes_per_frame);
1903 if (hw->info.is_float) {
1904 hw->clip = mixeng_clip_float[hw->info.nchannels == 2];
1905 } else {
1906 hw->clip = mixeng_clip
1907 [hw->info.nchannels == 2]
1908 [hw->info.is_signed]
1909 [hw->info.swap_endianness]
1910 [audio_bits_to_index(hw->info.bits)];
1913 QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1914 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1916 QLIST_FOREACH(hw, &s->hw_head_out, entries) {
1917 audio_attach_capture (hw);
1919 return cap;
1923 void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1925 struct capture_callback *cb;
1927 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1928 if (cb->opaque == cb_opaque) {
1929 cb->ops.destroy (cb_opaque);
1930 QLIST_REMOVE (cb, entries);
1931 g_free (cb);
1933 if (!cap->cb_head.lh_first) {
1934 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
1936 while (sw) {
1937 SWVoiceCap *sc = (SWVoiceCap *) sw;
1938 #ifdef DEBUG_CAPTURE
1939 dolog ("freeing %s\n", sw->name);
1940 #endif
1942 sw1 = sw->entries.le_next;
1943 if (sw->rate) {
1944 st_rate_stop (sw->rate);
1945 sw->rate = NULL;
1947 QLIST_REMOVE (sw, entries);
1948 QLIST_REMOVE (sc, entries);
1949 g_free (sc);
1950 sw = sw1;
1952 QLIST_REMOVE (cap, entries);
1953 g_free (cap->hw.mix_buf);
1954 g_free (cap->buf);
1955 g_free (cap);
1957 return;
1962 void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
1964 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1965 audio_set_volume_out(sw, &vol);
1968 void audio_set_volume_out(SWVoiceOut *sw, Volume *vol)
1970 if (sw) {
1971 HWVoiceOut *hw = sw->hw;
1973 sw->vol.mute = vol->mute;
1974 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
1975 sw->vol.r = nominal_volume.l * vol->vol[vol->channels > 1 ? 1 : 0] /
1976 255;
1978 if (hw->pcm_ops->volume_out) {
1979 hw->pcm_ops->volume_out(hw, vol);
1984 void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
1986 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1987 audio_set_volume_in(sw, &vol);
1990 void audio_set_volume_in(SWVoiceIn *sw, Volume *vol)
1992 if (sw) {
1993 HWVoiceIn *hw = sw->hw;
1995 sw->vol.mute = vol->mute;
1996 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
1997 sw->vol.r = nominal_volume.r * vol->vol[vol->channels > 1 ? 1 : 0] /
1998 255;
2000 if (hw->pcm_ops->volume_in) {
2001 hw->pcm_ops->volume_in(hw, vol);
2006 void audio_create_pdos(Audiodev *dev)
2008 switch (dev->driver) {
2009 #define CASE(DRIVER, driver, pdo_name) \
2010 case AUDIODEV_DRIVER_##DRIVER: \
2011 if (!dev->u.driver.has_in) { \
2012 dev->u.driver.in = g_malloc0( \
2013 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
2014 dev->u.driver.has_in = true; \
2016 if (!dev->u.driver.has_out) { \
2017 dev->u.driver.out = g_malloc0( \
2018 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
2019 dev->u.driver.has_out = true; \
2021 break
2023 CASE(NONE, none, );
2024 CASE(ALSA, alsa, Alsa);
2025 CASE(COREAUDIO, coreaudio, Coreaudio);
2026 CASE(DBUS, dbus, );
2027 CASE(DSOUND, dsound, );
2028 CASE(JACK, jack, Jack);
2029 CASE(OSS, oss, Oss);
2030 CASE(PA, pa, Pa);
2031 CASE(SDL, sdl, Sdl);
2032 CASE(SPICE, spice, );
2033 CASE(WAV, wav, );
2035 case AUDIODEV_DRIVER__MAX:
2036 abort();
2040 static void audio_validate_per_direction_opts(
2041 AudiodevPerDirectionOptions *pdo, Error **errp)
2043 if (!pdo->has_mixing_engine) {
2044 pdo->has_mixing_engine = true;
2045 pdo->mixing_engine = true;
2047 if (!pdo->has_fixed_settings) {
2048 pdo->has_fixed_settings = true;
2049 pdo->fixed_settings = pdo->mixing_engine;
2051 if (!pdo->fixed_settings &&
2052 (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
2053 error_setg(errp,
2054 "You can't use frequency, channels or format with fixed-settings=off");
2055 return;
2057 if (!pdo->mixing_engine && pdo->fixed_settings) {
2058 error_setg(errp, "You can't use fixed-settings without mixeng");
2059 return;
2062 if (!pdo->has_frequency) {
2063 pdo->has_frequency = true;
2064 pdo->frequency = 44100;
2066 if (!pdo->has_channels) {
2067 pdo->has_channels = true;
2068 pdo->channels = 2;
2070 if (!pdo->has_voices) {
2071 pdo->has_voices = true;
2072 pdo->voices = pdo->mixing_engine ? 1 : INT_MAX;
2074 if (!pdo->has_format) {
2075 pdo->has_format = true;
2076 pdo->format = AUDIO_FORMAT_S16;
2080 static void audio_validate_opts(Audiodev *dev, Error **errp)
2082 Error *err = NULL;
2084 audio_create_pdos(dev);
2086 audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
2087 if (err) {
2088 error_propagate(errp, err);
2089 return;
2092 audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
2093 if (err) {
2094 error_propagate(errp, err);
2095 return;
2098 if (!dev->has_timer_period) {
2099 dev->has_timer_period = true;
2100 dev->timer_period = 10000; /* 100Hz -> 10ms */
2104 void audio_parse_option(const char *opt)
2106 Audiodev *dev = NULL;
2108 Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
2109 visit_type_Audiodev(v, NULL, &dev, &error_fatal);
2110 visit_free(v);
2112 audio_define(dev);
2115 void audio_define(Audiodev *dev)
2117 AudiodevListEntry *e;
2119 audio_validate_opts(dev, &error_fatal);
2121 e = g_new0(AudiodevListEntry, 1);
2122 e->dev = dev;
2123 QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
2126 bool audio_init_audiodevs(void)
2128 AudiodevListEntry *e;
2130 QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2131 if (!audio_init(e->dev, NULL)) {
2132 return false;
2136 return true;
2139 audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
2141 return (audsettings) {
2142 .freq = pdo->frequency,
2143 .nchannels = pdo->channels,
2144 .fmt = pdo->format,
2145 .endianness = AUDIO_HOST_ENDIANNESS,
2149 int audioformat_bytes_per_sample(AudioFormat fmt)
2151 switch (fmt) {
2152 case AUDIO_FORMAT_U8:
2153 case AUDIO_FORMAT_S8:
2154 return 1;
2156 case AUDIO_FORMAT_U16:
2157 case AUDIO_FORMAT_S16:
2158 return 2;
2160 case AUDIO_FORMAT_U32:
2161 case AUDIO_FORMAT_S32:
2162 case AUDIO_FORMAT_F32:
2163 return 4;
2165 case AUDIO_FORMAT__MAX:
2168 abort();
2172 /* frames = freq * usec / 1e6 */
2173 int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
2174 audsettings *as, int def_usecs)
2176 uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
2177 return (as->freq * usecs + 500000) / 1000000;
2180 /* samples = channels * frames = channels * freq * usec / 1e6 */
2181 int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
2182 audsettings *as, int def_usecs)
2184 return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
2188 * bytes = bytes_per_sample * samples =
2189 * bytes_per_sample * channels * freq * usec / 1e6
2191 int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
2192 audsettings *as, int def_usecs)
2194 return audio_buffer_samples(pdo, as, def_usecs) *
2195 audioformat_bytes_per_sample(as->fmt);
2198 AudioState *audio_state_by_name(const char *name)
2200 AudioState *s;
2201 QTAILQ_FOREACH(s, &audio_states, list) {
2202 assert(s->dev);
2203 if (strcmp(name, s->dev->id) == 0) {
2204 return s;
2207 return NULL;
2210 const char *audio_get_id(QEMUSoundCard *card)
2212 if (card->state) {
2213 assert(card->state->dev);
2214 return card->state->dev->id;
2215 } else {
2216 return "";
2220 const char *audio_application_name(void)
2222 const char *vm_name;
2224 vm_name = qemu_get_vm_name();
2225 return vm_name ? vm_name : "qemu";
2228 void audio_rate_start(RateCtl *rate)
2230 memset(rate, 0, sizeof(RateCtl));
2231 rate->start_ticks = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2234 size_t audio_rate_get_bytes(struct audio_pcm_info *info, RateCtl *rate,
2235 size_t bytes_avail)
2237 int64_t now;
2238 int64_t ticks;
2239 int64_t bytes;
2240 int64_t samples;
2241 size_t ret;
2243 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2244 ticks = now - rate->start_ticks;
2245 bytes = muldiv64(ticks, info->bytes_per_second, NANOSECONDS_PER_SECOND);
2246 samples = (bytes - rate->bytes_sent) / info->bytes_per_frame;
2247 if (samples < 0 || samples > 65536) {
2248 AUD_log(NULL, "Resetting rate control (%" PRId64 " samples)\n", samples);
2249 audio_rate_start(rate);
2250 samples = 0;
2253 ret = MIN(samples * info->bytes_per_frame, bytes_avail);
2254 rate->bytes_sent += ret;
2255 return ret;