audio: propagate Error * out of audio_init
[qemu/kevin.git] / audio / audio.c
blob4289b7bf02898c0ddc07422837b7a72232992a4d
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 "qapi/qmp/qdict.h"
36 #include "qemu/cutils.h"
37 #include "qemu/error-report.h"
38 #include "qemu/log.h"
39 #include "qemu/module.h"
40 #include "qemu/help_option.h"
41 #include "sysemu/sysemu.h"
42 #include "sysemu/replay.h"
43 #include "sysemu/runstate.h"
44 #include "ui/qemu-spice.h"
45 #include "trace.h"
47 #define AUDIO_CAP "audio"
48 #include "audio_int.h"
50 /* #define DEBUG_LIVE */
51 /* #define DEBUG_OUT */
52 /* #define DEBUG_CAPTURE */
53 /* #define DEBUG_POLL */
55 #define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
58 /* Order of CONFIG_AUDIO_DRIVERS is import.
59 The 1st one is the one used by default, that is the reason
60 that we generate the list.
62 const char *audio_prio_list[] = {
63 "spice",
64 CONFIG_AUDIO_DRIVERS
65 "none",
66 NULL
69 static QLIST_HEAD(, audio_driver) audio_drivers;
70 static AudiodevListHead audiodevs =
71 QSIMPLEQ_HEAD_INITIALIZER(audiodevs);
72 static AudiodevListHead default_audiodevs =
73 QSIMPLEQ_HEAD_INITIALIZER(default_audiodevs);
76 void audio_driver_register(audio_driver *drv)
78 QLIST_INSERT_HEAD(&audio_drivers, drv, next);
81 static audio_driver *audio_driver_lookup(const char *name)
83 struct audio_driver *d;
84 Error *local_err = NULL;
85 int rv;
87 QLIST_FOREACH(d, &audio_drivers, next) {
88 if (strcmp(name, d->name) == 0) {
89 return d;
92 rv = audio_module_load(name, &local_err);
93 if (rv > 0) {
94 QLIST_FOREACH(d, &audio_drivers, next) {
95 if (strcmp(name, d->name) == 0) {
96 return d;
99 } else if (rv < 0) {
100 error_report_err(local_err);
102 return NULL;
105 static QTAILQ_HEAD(AudioStateHead, AudioState) audio_states =
106 QTAILQ_HEAD_INITIALIZER(audio_states);
108 const struct mixeng_volume nominal_volume = {
109 .mute = 0,
110 #ifdef FLOAT_MIXENG
111 .r = 1.0,
112 .l = 1.0,
113 #else
114 .r = 1ULL << 32,
115 .l = 1ULL << 32,
116 #endif
119 int audio_bug (const char *funcname, int cond)
121 if (cond) {
122 static int shown;
124 AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
125 if (!shown) {
126 shown = 1;
127 AUD_log (NULL, "Save all your work and restart without audio\n");
128 AUD_log (NULL, "I am sorry\n");
130 AUD_log (NULL, "Context:\n");
133 return cond;
136 static inline int audio_bits_to_index (int bits)
138 switch (bits) {
139 case 8:
140 return 0;
142 case 16:
143 return 1;
145 case 32:
146 return 2;
148 default:
149 audio_bug ("bits_to_index", 1);
150 AUD_log (NULL, "invalid bits %d\n", bits);
151 return 0;
155 void AUD_vlog (const char *cap, const char *fmt, va_list ap)
157 if (cap) {
158 fprintf(stderr, "%s: ", cap);
161 vfprintf(stderr, fmt, ap);
164 void AUD_log (const char *cap, const char *fmt, ...)
166 va_list ap;
168 va_start (ap, fmt);
169 AUD_vlog (cap, fmt, ap);
170 va_end (ap);
173 static void audio_print_settings (struct audsettings *as)
175 dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
177 switch (as->fmt) {
178 case AUDIO_FORMAT_S8:
179 AUD_log (NULL, "S8");
180 break;
181 case AUDIO_FORMAT_U8:
182 AUD_log (NULL, "U8");
183 break;
184 case AUDIO_FORMAT_S16:
185 AUD_log (NULL, "S16");
186 break;
187 case AUDIO_FORMAT_U16:
188 AUD_log (NULL, "U16");
189 break;
190 case AUDIO_FORMAT_S32:
191 AUD_log (NULL, "S32");
192 break;
193 case AUDIO_FORMAT_U32:
194 AUD_log (NULL, "U32");
195 break;
196 case AUDIO_FORMAT_F32:
197 AUD_log (NULL, "F32");
198 break;
199 default:
200 AUD_log (NULL, "invalid(%d)", as->fmt);
201 break;
204 AUD_log (NULL, " endianness=");
205 switch (as->endianness) {
206 case 0:
207 AUD_log (NULL, "little");
208 break;
209 case 1:
210 AUD_log (NULL, "big");
211 break;
212 default:
213 AUD_log (NULL, "invalid");
214 break;
216 AUD_log (NULL, "\n");
219 static int audio_validate_settings (struct audsettings *as)
221 int invalid;
223 invalid = as->nchannels < 1;
224 invalid |= as->endianness != 0 && as->endianness != 1;
226 switch (as->fmt) {
227 case AUDIO_FORMAT_S8:
228 case AUDIO_FORMAT_U8:
229 case AUDIO_FORMAT_S16:
230 case AUDIO_FORMAT_U16:
231 case AUDIO_FORMAT_S32:
232 case AUDIO_FORMAT_U32:
233 case AUDIO_FORMAT_F32:
234 break;
235 default:
236 invalid = 1;
237 break;
240 invalid |= as->freq <= 0;
241 return invalid ? -1 : 0;
244 static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
246 int bits = 8;
247 bool is_signed = false, is_float = false;
249 switch (as->fmt) {
250 case AUDIO_FORMAT_S8:
251 is_signed = true;
252 /* fall through */
253 case AUDIO_FORMAT_U8:
254 break;
256 case AUDIO_FORMAT_S16:
257 is_signed = true;
258 /* fall through */
259 case AUDIO_FORMAT_U16:
260 bits = 16;
261 break;
263 case AUDIO_FORMAT_F32:
264 is_float = true;
265 /* fall through */
266 case AUDIO_FORMAT_S32:
267 is_signed = true;
268 /* fall through */
269 case AUDIO_FORMAT_U32:
270 bits = 32;
271 break;
273 default:
274 abort();
276 return info->freq == as->freq
277 && info->nchannels == as->nchannels
278 && info->is_signed == is_signed
279 && info->is_float == is_float
280 && info->bits == bits
281 && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
284 void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
286 int bits = 8, mul;
287 bool is_signed = false, is_float = false;
289 switch (as->fmt) {
290 case AUDIO_FORMAT_S8:
291 is_signed = true;
292 /* fall through */
293 case AUDIO_FORMAT_U8:
294 mul = 1;
295 break;
297 case AUDIO_FORMAT_S16:
298 is_signed = true;
299 /* fall through */
300 case AUDIO_FORMAT_U16:
301 bits = 16;
302 mul = 2;
303 break;
305 case AUDIO_FORMAT_F32:
306 is_float = true;
307 /* fall through */
308 case AUDIO_FORMAT_S32:
309 is_signed = true;
310 /* fall through */
311 case AUDIO_FORMAT_U32:
312 bits = 32;
313 mul = 4;
314 break;
316 default:
317 abort();
320 info->freq = as->freq;
321 info->bits = bits;
322 info->is_signed = is_signed;
323 info->is_float = is_float;
324 info->nchannels = as->nchannels;
325 info->bytes_per_frame = as->nchannels * mul;
326 info->bytes_per_second = info->freq * info->bytes_per_frame;
327 info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
330 void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
332 if (!len) {
333 return;
336 if (info->is_signed || info->is_float) {
337 memset(buf, 0x00, len * info->bytes_per_frame);
338 } else {
339 switch (info->bits) {
340 case 8:
341 memset(buf, 0x80, len * info->bytes_per_frame);
342 break;
344 case 16:
346 int i;
347 uint16_t *p = buf;
348 short s = INT16_MAX;
350 if (info->swap_endianness) {
351 s = bswap16 (s);
354 for (i = 0; i < len * info->nchannels; i++) {
355 p[i] = s;
358 break;
360 case 32:
362 int i;
363 uint32_t *p = buf;
364 int32_t s = INT32_MAX;
366 if (info->swap_endianness) {
367 s = bswap32 (s);
370 for (i = 0; i < len * info->nchannels; i++) {
371 p[i] = s;
374 break;
376 default:
377 AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
378 info->bits);
379 break;
385 * Capture
387 static CaptureVoiceOut *audio_pcm_capture_find_specific(AudioState *s,
388 struct audsettings *as)
390 CaptureVoiceOut *cap;
392 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
393 if (audio_pcm_info_eq (&cap->hw.info, as)) {
394 return cap;
397 return NULL;
400 static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
402 struct capture_callback *cb;
404 #ifdef DEBUG_CAPTURE
405 dolog ("notification %d sent\n", cmd);
406 #endif
407 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
408 cb->ops.notify (cb->opaque, cmd);
412 static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
414 if (cap->hw.enabled != enabled) {
415 audcnotification_e cmd;
416 cap->hw.enabled = enabled;
417 cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
418 audio_notify_capture (cap, cmd);
422 static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
424 HWVoiceOut *hw = &cap->hw;
425 SWVoiceOut *sw;
426 int enabled = 0;
428 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
429 if (sw->active) {
430 enabled = 1;
431 break;
434 audio_capture_maybe_changed (cap, enabled);
437 static void audio_detach_capture (HWVoiceOut *hw)
439 SWVoiceCap *sc = hw->cap_head.lh_first;
441 while (sc) {
442 SWVoiceCap *sc1 = sc->entries.le_next;
443 SWVoiceOut *sw = &sc->sw;
444 CaptureVoiceOut *cap = sc->cap;
445 int was_active = sw->active;
447 if (sw->rate) {
448 st_rate_stop (sw->rate);
449 sw->rate = NULL;
452 QLIST_REMOVE (sw, entries);
453 QLIST_REMOVE (sc, entries);
454 g_free (sc);
455 if (was_active) {
456 /* We have removed soft voice from the capture:
457 this might have changed the overall status of the capture
458 since this might have been the only active voice */
459 audio_recalc_and_notify_capture (cap);
461 sc = sc1;
465 static int audio_attach_capture (HWVoiceOut *hw)
467 AudioState *s = hw->s;
468 CaptureVoiceOut *cap;
470 audio_detach_capture (hw);
471 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
472 SWVoiceCap *sc;
473 SWVoiceOut *sw;
474 HWVoiceOut *hw_cap = &cap->hw;
476 sc = g_malloc0(sizeof(*sc));
478 sc->cap = cap;
479 sw = &sc->sw;
480 sw->hw = hw_cap;
481 sw->info = hw->info;
482 sw->empty = 1;
483 sw->active = hw->enabled;
484 sw->vol = nominal_volume;
485 sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
486 QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
487 QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
488 #ifdef DEBUG_CAPTURE
489 sw->name = g_strdup_printf ("for %p %d,%d,%d",
490 hw, sw->info.freq, sw->info.bits,
491 sw->info.nchannels);
492 dolog ("Added %s active = %d\n", sw->name, sw->active);
493 #endif
494 if (sw->active) {
495 audio_capture_maybe_changed (cap, 1);
498 return 0;
502 * Hard voice (capture)
504 static size_t audio_pcm_hw_find_min_in (HWVoiceIn *hw)
506 SWVoiceIn *sw;
507 size_t m = hw->total_samples_captured;
509 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
510 if (sw->active) {
511 m = MIN (m, sw->total_hw_samples_acquired);
514 return m;
517 static size_t audio_pcm_hw_get_live_in(HWVoiceIn *hw)
519 size_t live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
520 if (audio_bug(__func__, live > hw->conv_buf.size)) {
521 dolog("live=%zu hw->conv_buf.size=%zu\n", live, hw->conv_buf.size);
522 return 0;
524 return live;
527 static size_t audio_pcm_hw_conv_in(HWVoiceIn *hw, void *pcm_buf, size_t samples)
529 size_t conv = 0;
530 STSampleBuffer *conv_buf = &hw->conv_buf;
532 while (samples) {
533 uint8_t *src = advance(pcm_buf, conv * hw->info.bytes_per_frame);
534 size_t proc = MIN(samples, conv_buf->size - conv_buf->pos);
536 hw->conv(conv_buf->buffer + conv_buf->pos, src, proc);
537 conv_buf->pos = (conv_buf->pos + proc) % conv_buf->size;
538 samples -= proc;
539 conv += proc;
542 return conv;
546 * Soft voice (capture)
548 static void audio_pcm_sw_resample_in(SWVoiceIn *sw,
549 size_t frames_in_max, size_t frames_out_max,
550 size_t *total_in, size_t *total_out)
552 HWVoiceIn *hw = sw->hw;
553 struct st_sample *src, *dst;
554 size_t live, rpos, frames_in, frames_out;
556 live = hw->total_samples_captured - sw->total_hw_samples_acquired;
557 rpos = audio_ring_posb(hw->conv_buf.pos, live, hw->conv_buf.size);
559 /* resample conv_buf from rpos to end of buffer */
560 src = hw->conv_buf.buffer + rpos;
561 frames_in = MIN(frames_in_max, hw->conv_buf.size - rpos);
562 dst = sw->resample_buf.buffer;
563 frames_out = frames_out_max;
564 st_rate_flow(sw->rate, src, dst, &frames_in, &frames_out);
565 rpos += frames_in;
566 *total_in = frames_in;
567 *total_out = frames_out;
569 /* resample conv_buf from start of buffer if there are input frames left */
570 if (frames_in_max - frames_in && rpos == hw->conv_buf.size) {
571 src = hw->conv_buf.buffer;
572 frames_in = frames_in_max - frames_in;
573 dst += frames_out;
574 frames_out = frames_out_max - frames_out;
575 st_rate_flow(sw->rate, src, dst, &frames_in, &frames_out);
576 *total_in += frames_in;
577 *total_out += frames_out;
581 static size_t audio_pcm_sw_read(SWVoiceIn *sw, void *buf, size_t buf_len)
583 HWVoiceIn *hw = sw->hw;
584 size_t live, frames_out_max, total_in, total_out;
586 live = hw->total_samples_captured - sw->total_hw_samples_acquired;
587 if (!live) {
588 return 0;
590 if (audio_bug(__func__, live > hw->conv_buf.size)) {
591 dolog("live_in=%zu hw->conv_buf.size=%zu\n", live, hw->conv_buf.size);
592 return 0;
595 frames_out_max = MIN(buf_len / sw->info.bytes_per_frame,
596 sw->resample_buf.size);
598 audio_pcm_sw_resample_in(sw, live, frames_out_max, &total_in, &total_out);
600 if (!hw->pcm_ops->volume_in) {
601 mixeng_volume(sw->resample_buf.buffer, total_out, &sw->vol);
603 sw->clip(buf, sw->resample_buf.buffer, total_out);
605 sw->total_hw_samples_acquired += total_in;
606 return total_out * sw->info.bytes_per_frame;
610 * Hard voice (playback)
612 static size_t audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
614 SWVoiceOut *sw;
615 size_t m = SIZE_MAX;
616 int nb_live = 0;
618 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
619 if (sw->active || !sw->empty) {
620 m = MIN (m, sw->total_hw_samples_mixed);
621 nb_live += 1;
625 *nb_livep = nb_live;
626 return m;
629 static size_t audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
631 size_t smin;
632 int nb_live1;
634 smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
635 if (nb_live) {
636 *nb_live = nb_live1;
639 if (nb_live1) {
640 size_t live = smin;
642 if (audio_bug(__func__, live > hw->mix_buf.size)) {
643 dolog("live=%zu hw->mix_buf.size=%zu\n", live, hw->mix_buf.size);
644 return 0;
646 return live;
648 return 0;
651 static size_t audio_pcm_hw_get_free(HWVoiceOut *hw)
653 return (hw->pcm_ops->buffer_get_free ? hw->pcm_ops->buffer_get_free(hw) :
654 INT_MAX) / hw->info.bytes_per_frame;
657 static void audio_pcm_hw_clip_out(HWVoiceOut *hw, void *pcm_buf, size_t len)
659 size_t clipped = 0;
660 size_t pos = hw->mix_buf.pos;
662 while (len) {
663 st_sample *src = hw->mix_buf.buffer + pos;
664 uint8_t *dst = advance(pcm_buf, clipped * hw->info.bytes_per_frame);
665 size_t samples_till_end_of_buf = hw->mix_buf.size - pos;
666 size_t samples_to_clip = MIN(len, samples_till_end_of_buf);
668 hw->clip(dst, src, samples_to_clip);
670 pos = (pos + samples_to_clip) % hw->mix_buf.size;
671 len -= samples_to_clip;
672 clipped += samples_to_clip;
677 * Soft voice (playback)
679 static void audio_pcm_sw_resample_out(SWVoiceOut *sw,
680 size_t frames_in_max, size_t frames_out_max,
681 size_t *total_in, size_t *total_out)
683 HWVoiceOut *hw = sw->hw;
684 struct st_sample *src, *dst;
685 size_t live, wpos, frames_in, frames_out;
687 live = sw->total_hw_samples_mixed;
688 wpos = (hw->mix_buf.pos + live) % hw->mix_buf.size;
690 /* write to mix_buf from wpos to end of buffer */
691 src = sw->resample_buf.buffer;
692 frames_in = frames_in_max;
693 dst = hw->mix_buf.buffer + wpos;
694 frames_out = MIN(frames_out_max, hw->mix_buf.size - wpos);
695 st_rate_flow_mix(sw->rate, src, dst, &frames_in, &frames_out);
696 wpos += frames_out;
697 *total_in = frames_in;
698 *total_out = frames_out;
700 /* write to mix_buf from start of buffer if there are input frames left */
701 if (frames_in_max - frames_in > 0 && wpos == hw->mix_buf.size) {
702 src += frames_in;
703 frames_in = frames_in_max - frames_in;
704 dst = hw->mix_buf.buffer;
705 frames_out = frames_out_max - frames_out;
706 st_rate_flow_mix(sw->rate, src, dst, &frames_in, &frames_out);
707 *total_in += frames_in;
708 *total_out += frames_out;
712 static size_t audio_pcm_sw_write(SWVoiceOut *sw, void *buf, size_t buf_len)
714 HWVoiceOut *hw = sw->hw;
715 size_t live, dead, hw_free, sw_max, fe_max;
716 size_t frames_in_max, frames_out_max, total_in, total_out;
718 live = sw->total_hw_samples_mixed;
719 if (audio_bug(__func__, live > hw->mix_buf.size)) {
720 dolog("live=%zu hw->mix_buf.size=%zu\n", live, hw->mix_buf.size);
721 return 0;
724 if (live == hw->mix_buf.size) {
725 #ifdef DEBUG_OUT
726 dolog ("%s is full %zu\n", sw->name, live);
727 #endif
728 return 0;
731 dead = hw->mix_buf.size - live;
732 hw_free = audio_pcm_hw_get_free(hw);
733 hw_free = hw_free > live ? hw_free - live : 0;
734 frames_out_max = MIN(dead, hw_free);
735 sw_max = st_rate_frames_in(sw->rate, frames_out_max);
736 fe_max = MIN(buf_len / sw->info.bytes_per_frame + sw->resample_buf.pos,
737 sw->resample_buf.size);
738 frames_in_max = MIN(sw_max, fe_max);
740 if (!frames_in_max) {
741 return 0;
744 if (frames_in_max > sw->resample_buf.pos) {
745 sw->conv(sw->resample_buf.buffer + sw->resample_buf.pos,
746 buf, frames_in_max - sw->resample_buf.pos);
747 if (!sw->hw->pcm_ops->volume_out) {
748 mixeng_volume(sw->resample_buf.buffer + sw->resample_buf.pos,
749 frames_in_max - sw->resample_buf.pos, &sw->vol);
753 audio_pcm_sw_resample_out(sw, frames_in_max, frames_out_max,
754 &total_in, &total_out);
756 sw->total_hw_samples_mixed += total_out;
757 sw->empty = sw->total_hw_samples_mixed == 0;
760 * Upsampling may leave one audio frame in the resample buffer. Decrement
761 * total_in by one if there was a leftover frame from the previous resample
762 * pass in the resample buffer. Increment total_in by one if the current
763 * resample pass left one frame in the resample buffer.
765 if (frames_in_max - total_in == 1) {
766 /* copy one leftover audio frame to the beginning of the buffer */
767 *sw->resample_buf.buffer = *(sw->resample_buf.buffer + total_in);
768 total_in += 1 - sw->resample_buf.pos;
769 sw->resample_buf.pos = 1;
770 } else if (total_in >= sw->resample_buf.pos) {
771 total_in -= sw->resample_buf.pos;
772 sw->resample_buf.pos = 0;
775 #ifdef DEBUG_OUT
776 dolog (
777 "%s: write size %zu written %zu total mixed %zu\n",
778 SW_NAME(sw),
779 buf_len / sw->info.bytes_per_frame,
780 total_in,
781 sw->total_hw_samples_mixed
783 #endif
785 return total_in * sw->info.bytes_per_frame;
788 #ifdef DEBUG_AUDIO
789 static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
791 dolog("%s: bits %d, sign %d, float %d, freq %d, nchan %d\n",
792 cap, info->bits, info->is_signed, info->is_float, info->freq,
793 info->nchannels);
795 #endif
797 #define DAC
798 #include "audio_template.h"
799 #undef DAC
800 #include "audio_template.h"
803 * Timer
805 static int audio_is_timer_needed(AudioState *s)
807 HWVoiceIn *hwi = NULL;
808 HWVoiceOut *hwo = NULL;
810 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
811 if (!hwo->poll_mode) {
812 return 1;
815 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
816 if (!hwi->poll_mode) {
817 return 1;
820 return 0;
823 static void audio_reset_timer (AudioState *s)
825 if (audio_is_timer_needed(s)) {
826 timer_mod_anticipate_ns(s->ts,
827 qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
828 if (!s->timer_running) {
829 s->timer_running = true;
830 s->timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
831 trace_audio_timer_start(s->period_ticks / SCALE_MS);
833 } else {
834 timer_del(s->ts);
835 if (s->timer_running) {
836 s->timer_running = false;
837 trace_audio_timer_stop();
842 static void audio_timer (void *opaque)
844 int64_t now, diff;
845 AudioState *s = opaque;
847 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
848 diff = now - s->timer_last;
849 if (diff > s->period_ticks * 3 / 2) {
850 trace_audio_timer_delayed(diff / SCALE_MS);
852 s->timer_last = now;
854 audio_run(s, "timer");
855 audio_reset_timer(s);
859 * Public API
861 size_t AUD_write(SWVoiceOut *sw, void *buf, size_t size)
863 HWVoiceOut *hw;
865 if (!sw) {
866 /* XXX: Consider options */
867 return size;
869 hw = sw->hw;
871 if (!hw->enabled) {
872 dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
873 return 0;
876 if (audio_get_pdo_out(hw->s->dev)->mixing_engine) {
877 return audio_pcm_sw_write(sw, buf, size);
878 } else {
879 return hw->pcm_ops->write(hw, buf, size);
883 size_t AUD_read(SWVoiceIn *sw, void *buf, size_t size)
885 HWVoiceIn *hw;
887 if (!sw) {
888 /* XXX: Consider options */
889 return size;
891 hw = sw->hw;
893 if (!hw->enabled) {
894 dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
895 return 0;
898 if (audio_get_pdo_in(hw->s->dev)->mixing_engine) {
899 return audio_pcm_sw_read(sw, buf, size);
900 } else {
901 return hw->pcm_ops->read(hw, buf, size);
905 int AUD_get_buffer_size_out(SWVoiceOut *sw)
907 return sw->hw->samples * sw->hw->info.bytes_per_frame;
910 void AUD_set_active_out (SWVoiceOut *sw, int on)
912 HWVoiceOut *hw;
914 if (!sw) {
915 return;
918 hw = sw->hw;
919 if (sw->active != on) {
920 AudioState *s = sw->s;
921 SWVoiceOut *temp_sw;
922 SWVoiceCap *sc;
924 if (on) {
925 hw->pending_disable = 0;
926 if (!hw->enabled) {
927 hw->enabled = 1;
928 if (s->vm_running) {
929 if (hw->pcm_ops->enable_out) {
930 hw->pcm_ops->enable_out(hw, true);
932 audio_reset_timer (s);
935 } else {
936 if (hw->enabled) {
937 int nb_active = 0;
939 for (temp_sw = hw->sw_head.lh_first; temp_sw;
940 temp_sw = temp_sw->entries.le_next) {
941 nb_active += temp_sw->active != 0;
944 hw->pending_disable = nb_active == 1;
948 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
949 sc->sw.active = hw->enabled;
950 if (hw->enabled) {
951 audio_capture_maybe_changed (sc->cap, 1);
954 sw->active = on;
958 void AUD_set_active_in (SWVoiceIn *sw, int on)
960 HWVoiceIn *hw;
962 if (!sw) {
963 return;
966 hw = sw->hw;
967 if (sw->active != on) {
968 AudioState *s = sw->s;
969 SWVoiceIn *temp_sw;
971 if (on) {
972 if (!hw->enabled) {
973 hw->enabled = 1;
974 if (s->vm_running) {
975 if (hw->pcm_ops->enable_in) {
976 hw->pcm_ops->enable_in(hw, true);
978 audio_reset_timer (s);
981 sw->total_hw_samples_acquired = hw->total_samples_captured;
982 } else {
983 if (hw->enabled) {
984 int nb_active = 0;
986 for (temp_sw = hw->sw_head.lh_first; temp_sw;
987 temp_sw = temp_sw->entries.le_next) {
988 nb_active += temp_sw->active != 0;
991 if (nb_active == 1) {
992 hw->enabled = 0;
993 if (hw->pcm_ops->enable_in) {
994 hw->pcm_ops->enable_in(hw, false);
999 sw->active = on;
1003 static size_t audio_get_avail (SWVoiceIn *sw)
1005 size_t live;
1007 if (!sw) {
1008 return 0;
1011 live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
1012 if (audio_bug(__func__, live > sw->hw->conv_buf.size)) {
1013 dolog("live=%zu sw->hw->conv_buf.size=%zu\n", live,
1014 sw->hw->conv_buf.size);
1015 return 0;
1018 ldebug (
1019 "%s: get_avail live %zu frontend frames %u\n",
1020 SW_NAME (sw),
1021 live, st_rate_frames_out(sw->rate, live)
1024 return live;
1027 static size_t audio_get_free(SWVoiceOut *sw)
1029 size_t live, dead;
1031 if (!sw) {
1032 return 0;
1035 live = sw->total_hw_samples_mixed;
1037 if (audio_bug(__func__, live > sw->hw->mix_buf.size)) {
1038 dolog("live=%zu sw->hw->mix_buf.size=%zu\n", live,
1039 sw->hw->mix_buf.size);
1040 return 0;
1043 dead = sw->hw->mix_buf.size - live;
1045 #ifdef DEBUG_OUT
1046 dolog("%s: get_free live %zu dead %zu frontend frames %u\n",
1047 SW_NAME(sw), live, dead, st_rate_frames_in(sw->rate, dead));
1048 #endif
1050 return dead;
1053 static void audio_capture_mix_and_clear(HWVoiceOut *hw, size_t rpos,
1054 size_t samples)
1056 size_t n;
1058 if (hw->enabled) {
1059 SWVoiceCap *sc;
1061 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1062 SWVoiceOut *sw = &sc->sw;
1063 size_t rpos2 = rpos;
1065 n = samples;
1066 while (n) {
1067 size_t till_end_of_hw = hw->mix_buf.size - rpos2;
1068 size_t to_read = MIN(till_end_of_hw, n);
1069 size_t live, frames_in, frames_out;
1071 sw->resample_buf.buffer = hw->mix_buf.buffer + rpos2;
1072 sw->resample_buf.size = to_read;
1073 live = sw->total_hw_samples_mixed;
1075 audio_pcm_sw_resample_out(sw,
1076 to_read, sw->hw->mix_buf.size - live,
1077 &frames_in, &frames_out);
1079 sw->total_hw_samples_mixed += frames_out;
1080 sw->empty = sw->total_hw_samples_mixed == 0;
1082 if (to_read - frames_in) {
1083 dolog("Could not mix %zu frames into a capture "
1084 "buffer, mixed %zu\n",
1085 to_read, frames_in);
1086 break;
1088 n -= to_read;
1089 rpos2 = (rpos2 + to_read) % hw->mix_buf.size;
1094 n = MIN(samples, hw->mix_buf.size - rpos);
1095 mixeng_clear(hw->mix_buf.buffer + rpos, n);
1096 mixeng_clear(hw->mix_buf.buffer, samples - n);
1099 static size_t audio_pcm_hw_run_out(HWVoiceOut *hw, size_t live)
1101 size_t clipped = 0;
1103 while (live) {
1104 size_t size = live * hw->info.bytes_per_frame;
1105 size_t decr, proc;
1106 void *buf = hw->pcm_ops->get_buffer_out(hw, &size);
1108 if (size == 0) {
1109 break;
1112 decr = MIN(size / hw->info.bytes_per_frame, live);
1113 if (buf) {
1114 audio_pcm_hw_clip_out(hw, buf, decr);
1116 proc = hw->pcm_ops->put_buffer_out(hw, buf,
1117 decr * hw->info.bytes_per_frame) /
1118 hw->info.bytes_per_frame;
1120 live -= proc;
1121 clipped += proc;
1122 hw->mix_buf.pos = (hw->mix_buf.pos + proc) % hw->mix_buf.size;
1124 if (proc == 0 || proc < decr) {
1125 break;
1129 if (hw->pcm_ops->run_buffer_out) {
1130 hw->pcm_ops->run_buffer_out(hw);
1133 return clipped;
1136 static void audio_run_out (AudioState *s)
1138 HWVoiceOut *hw = NULL;
1139 SWVoiceOut *sw;
1141 while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1142 size_t played, live, prev_rpos;
1143 size_t hw_free = audio_pcm_hw_get_free(hw);
1144 int nb_live;
1146 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1147 /* there is exactly 1 sw for each hw with no mixeng */
1148 sw = hw->sw_head.lh_first;
1150 if (hw->pending_disable) {
1151 hw->enabled = 0;
1152 hw->pending_disable = 0;
1153 if (hw->pcm_ops->enable_out) {
1154 hw->pcm_ops->enable_out(hw, false);
1158 if (sw->active) {
1159 sw->callback.fn(sw->callback.opaque,
1160 hw_free * sw->info.bytes_per_frame);
1163 if (hw->pcm_ops->run_buffer_out) {
1164 hw->pcm_ops->run_buffer_out(hw);
1167 continue;
1170 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1171 if (sw->active) {
1172 size_t sw_free = audio_get_free(sw);
1173 size_t free;
1175 if (hw_free > sw->total_hw_samples_mixed) {
1176 free = st_rate_frames_in(sw->rate,
1177 MIN(sw_free, hw_free - sw->total_hw_samples_mixed));
1178 } else {
1179 free = 0;
1181 if (free > sw->resample_buf.pos) {
1182 free = MIN(free, sw->resample_buf.size)
1183 - sw->resample_buf.pos;
1184 sw->callback.fn(sw->callback.opaque,
1185 free * sw->info.bytes_per_frame);
1190 live = audio_pcm_hw_get_live_out (hw, &nb_live);
1191 if (!nb_live) {
1192 live = 0;
1195 if (audio_bug(__func__, live > hw->mix_buf.size)) {
1196 dolog("live=%zu hw->mix_buf.size=%zu\n", live, hw->mix_buf.size);
1197 continue;
1200 if (hw->pending_disable && !nb_live) {
1201 SWVoiceCap *sc;
1202 #ifdef DEBUG_OUT
1203 dolog ("Disabling voice\n");
1204 #endif
1205 hw->enabled = 0;
1206 hw->pending_disable = 0;
1207 if (hw->pcm_ops->enable_out) {
1208 hw->pcm_ops->enable_out(hw, false);
1210 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1211 sc->sw.active = 0;
1212 audio_recalc_and_notify_capture (sc->cap);
1214 continue;
1217 if (!live) {
1218 if (hw->pcm_ops->run_buffer_out) {
1219 hw->pcm_ops->run_buffer_out(hw);
1221 continue;
1224 prev_rpos = hw->mix_buf.pos;
1225 played = audio_pcm_hw_run_out(hw, live);
1226 replay_audio_out(&played);
1227 if (audio_bug(__func__, hw->mix_buf.pos >= hw->mix_buf.size)) {
1228 dolog("hw->mix_buf.pos=%zu hw->mix_buf.size=%zu played=%zu\n",
1229 hw->mix_buf.pos, hw->mix_buf.size, played);
1230 hw->mix_buf.pos = 0;
1233 #ifdef DEBUG_OUT
1234 dolog("played=%zu\n", played);
1235 #endif
1237 if (played) {
1238 hw->ts_helper += played;
1239 audio_capture_mix_and_clear (hw, prev_rpos, played);
1242 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1243 if (!sw->active && sw->empty) {
1244 continue;
1247 if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1248 dolog("played=%zu sw->total_hw_samples_mixed=%zu\n",
1249 played, sw->total_hw_samples_mixed);
1250 played = sw->total_hw_samples_mixed;
1253 sw->total_hw_samples_mixed -= played;
1255 if (!sw->total_hw_samples_mixed) {
1256 sw->empty = 1;
1262 static size_t audio_pcm_hw_run_in(HWVoiceIn *hw, size_t samples)
1264 size_t conv = 0;
1266 if (hw->pcm_ops->run_buffer_in) {
1267 hw->pcm_ops->run_buffer_in(hw);
1270 while (samples) {
1271 size_t proc;
1272 size_t size = samples * hw->info.bytes_per_frame;
1273 void *buf = hw->pcm_ops->get_buffer_in(hw, &size);
1275 assert(size % hw->info.bytes_per_frame == 0);
1276 if (size == 0) {
1277 break;
1280 proc = audio_pcm_hw_conv_in(hw, buf, size / hw->info.bytes_per_frame);
1282 samples -= proc;
1283 conv += proc;
1284 hw->pcm_ops->put_buffer_in(hw, buf, proc * hw->info.bytes_per_frame);
1287 return conv;
1290 static void audio_run_in (AudioState *s)
1292 HWVoiceIn *hw = NULL;
1294 if (!audio_get_pdo_in(s->dev)->mixing_engine) {
1295 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1296 /* there is exactly 1 sw for each hw with no mixeng */
1297 SWVoiceIn *sw = hw->sw_head.lh_first;
1298 if (sw->active) {
1299 sw->callback.fn(sw->callback.opaque, INT_MAX);
1302 return;
1305 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1306 SWVoiceIn *sw;
1307 size_t captured = 0, min;
1309 if (replay_mode != REPLAY_MODE_PLAY) {
1310 captured = audio_pcm_hw_run_in(
1311 hw, hw->conv_buf.size - audio_pcm_hw_get_live_in(hw));
1313 replay_audio_in(&captured, hw->conv_buf.buffer, &hw->conv_buf.pos,
1314 hw->conv_buf.size);
1316 min = audio_pcm_hw_find_min_in (hw);
1317 hw->total_samples_captured += captured - min;
1318 hw->ts_helper += captured;
1320 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1321 sw->total_hw_samples_acquired -= min;
1323 if (sw->active) {
1324 size_t sw_avail = audio_get_avail(sw);
1325 size_t avail;
1327 avail = st_rate_frames_out(sw->rate, sw_avail);
1328 if (avail > 0) {
1329 avail = MIN(avail, sw->resample_buf.size);
1330 sw->callback.fn(sw->callback.opaque,
1331 avail * sw->info.bytes_per_frame);
1338 static void audio_run_capture (AudioState *s)
1340 CaptureVoiceOut *cap;
1342 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1343 size_t live, rpos, captured;
1344 HWVoiceOut *hw = &cap->hw;
1345 SWVoiceOut *sw;
1347 captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1348 rpos = hw->mix_buf.pos;
1349 while (live) {
1350 size_t left = hw->mix_buf.size - rpos;
1351 size_t to_capture = MIN(live, left);
1352 struct st_sample *src;
1353 struct capture_callback *cb;
1355 src = hw->mix_buf.buffer + rpos;
1356 hw->clip (cap->buf, src, to_capture);
1357 mixeng_clear (src, to_capture);
1359 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1360 cb->ops.capture (cb->opaque, cap->buf,
1361 to_capture * hw->info.bytes_per_frame);
1363 rpos = (rpos + to_capture) % hw->mix_buf.size;
1364 live -= to_capture;
1366 hw->mix_buf.pos = rpos;
1368 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1369 if (!sw->active && sw->empty) {
1370 continue;
1373 if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1374 dolog("captured=%zu sw->total_hw_samples_mixed=%zu\n",
1375 captured, sw->total_hw_samples_mixed);
1376 captured = sw->total_hw_samples_mixed;
1379 sw->total_hw_samples_mixed -= captured;
1380 sw->empty = sw->total_hw_samples_mixed == 0;
1385 void audio_run(AudioState *s, const char *msg)
1387 audio_run_out(s);
1388 audio_run_in(s);
1389 audio_run_capture(s);
1391 #ifdef DEBUG_POLL
1393 static double prevtime;
1394 double currtime;
1395 struct timeval tv;
1397 if (gettimeofday (&tv, NULL)) {
1398 perror ("audio_run: gettimeofday");
1399 return;
1402 currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1403 dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1404 prevtime = currtime;
1406 #endif
1409 void audio_generic_run_buffer_in(HWVoiceIn *hw)
1411 if (unlikely(!hw->buf_emul)) {
1412 hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1413 hw->buf_emul = g_malloc(hw->size_emul);
1414 hw->pos_emul = hw->pending_emul = 0;
1417 while (hw->pending_emul < hw->size_emul) {
1418 size_t read_len = MIN(hw->size_emul - hw->pos_emul,
1419 hw->size_emul - hw->pending_emul);
1420 size_t read = hw->pcm_ops->read(hw, hw->buf_emul + hw->pos_emul,
1421 read_len);
1422 hw->pending_emul += read;
1423 hw->pos_emul = (hw->pos_emul + read) % hw->size_emul;
1424 if (read < read_len) {
1425 break;
1430 void *audio_generic_get_buffer_in(HWVoiceIn *hw, size_t *size)
1432 size_t start;
1434 start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1435 assert(start < hw->size_emul);
1437 *size = MIN(*size, hw->pending_emul);
1438 *size = MIN(*size, hw->size_emul - start);
1439 return hw->buf_emul + start;
1442 void audio_generic_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
1444 assert(size <= hw->pending_emul);
1445 hw->pending_emul -= size;
1448 size_t audio_generic_buffer_get_free(HWVoiceOut *hw)
1450 if (hw->buf_emul) {
1451 return hw->size_emul - hw->pending_emul;
1452 } else {
1453 return hw->samples * hw->info.bytes_per_frame;
1457 void audio_generic_run_buffer_out(HWVoiceOut *hw)
1459 while (hw->pending_emul) {
1460 size_t write_len, written, start;
1462 start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1463 assert(start < hw->size_emul);
1465 write_len = MIN(hw->pending_emul, hw->size_emul - start);
1467 written = hw->pcm_ops->write(hw, hw->buf_emul + start, write_len);
1468 hw->pending_emul -= written;
1470 if (written < write_len) {
1471 break;
1476 void *audio_generic_get_buffer_out(HWVoiceOut *hw, size_t *size)
1478 if (unlikely(!hw->buf_emul)) {
1479 hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1480 hw->buf_emul = g_malloc(hw->size_emul);
1481 hw->pos_emul = hw->pending_emul = 0;
1484 *size = MIN(hw->size_emul - hw->pending_emul,
1485 hw->size_emul - hw->pos_emul);
1486 return hw->buf_emul + hw->pos_emul;
1489 size_t audio_generic_put_buffer_out(HWVoiceOut *hw, void *buf, size_t size)
1491 assert(buf == hw->buf_emul + hw->pos_emul &&
1492 size + hw->pending_emul <= hw->size_emul);
1494 hw->pending_emul += size;
1495 hw->pos_emul = (hw->pos_emul + size) % hw->size_emul;
1497 return size;
1500 size_t audio_generic_write(HWVoiceOut *hw, void *buf, size_t size)
1502 size_t total = 0;
1504 if (hw->pcm_ops->buffer_get_free) {
1505 size_t free = hw->pcm_ops->buffer_get_free(hw);
1507 size = MIN(size, free);
1510 while (total < size) {
1511 size_t dst_size = size - total;
1512 size_t copy_size, proc;
1513 void *dst = hw->pcm_ops->get_buffer_out(hw, &dst_size);
1515 if (dst_size == 0) {
1516 break;
1519 copy_size = MIN(size - total, dst_size);
1520 if (dst) {
1521 memcpy(dst, (char *)buf + total, copy_size);
1523 proc = hw->pcm_ops->put_buffer_out(hw, dst, copy_size);
1524 total += proc;
1526 if (proc == 0 || proc < copy_size) {
1527 break;
1531 return total;
1534 size_t audio_generic_read(HWVoiceIn *hw, void *buf, size_t size)
1536 size_t total = 0;
1538 if (hw->pcm_ops->run_buffer_in) {
1539 hw->pcm_ops->run_buffer_in(hw);
1542 while (total < size) {
1543 size_t src_size = size - total;
1544 void *src = hw->pcm_ops->get_buffer_in(hw, &src_size);
1546 if (src_size == 0) {
1547 break;
1550 memcpy((char *)buf + total, src, src_size);
1551 hw->pcm_ops->put_buffer_in(hw, src, src_size);
1552 total += src_size;
1555 return total;
1558 static int audio_driver_init(AudioState *s, struct audio_driver *drv,
1559 Audiodev *dev, Error **errp)
1561 Error *local_err = NULL;
1563 s->drv_opaque = drv->init(dev, &local_err);
1565 if (s->drv_opaque) {
1566 if (!drv->pcm_ops->get_buffer_in) {
1567 drv->pcm_ops->get_buffer_in = audio_generic_get_buffer_in;
1568 drv->pcm_ops->put_buffer_in = audio_generic_put_buffer_in;
1570 if (!drv->pcm_ops->get_buffer_out) {
1571 drv->pcm_ops->get_buffer_out = audio_generic_get_buffer_out;
1572 drv->pcm_ops->put_buffer_out = audio_generic_put_buffer_out;
1575 audio_init_nb_voices_out(s, drv, 1);
1576 audio_init_nb_voices_in(s, drv, 0);
1577 s->drv = drv;
1578 return 0;
1579 } else {
1580 if (local_err) {
1581 error_propagate(errp, local_err);
1582 } else {
1583 error_setg(errp, "Could not init `%s' audio driver", drv->name);
1585 return -1;
1589 static void audio_vm_change_state_handler (void *opaque, bool running,
1590 RunState state)
1592 AudioState *s = opaque;
1593 HWVoiceOut *hwo = NULL;
1594 HWVoiceIn *hwi = NULL;
1596 s->vm_running = running;
1597 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
1598 if (hwo->pcm_ops->enable_out) {
1599 hwo->pcm_ops->enable_out(hwo, running);
1603 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
1604 if (hwi->pcm_ops->enable_in) {
1605 hwi->pcm_ops->enable_in(hwi, running);
1608 audio_reset_timer (s);
1611 static void free_audio_state(AudioState *s)
1613 HWVoiceOut *hwo, *hwon;
1614 HWVoiceIn *hwi, *hwin;
1616 QLIST_FOREACH_SAFE(hwo, &s->hw_head_out, entries, hwon) {
1617 SWVoiceCap *sc;
1619 if (hwo->enabled && hwo->pcm_ops->enable_out) {
1620 hwo->pcm_ops->enable_out(hwo, false);
1622 hwo->pcm_ops->fini_out (hwo);
1624 for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1625 CaptureVoiceOut *cap = sc->cap;
1626 struct capture_callback *cb;
1628 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1629 cb->ops.destroy (cb->opaque);
1632 QLIST_REMOVE(hwo, entries);
1635 QLIST_FOREACH_SAFE(hwi, &s->hw_head_in, entries, hwin) {
1636 if (hwi->enabled && hwi->pcm_ops->enable_in) {
1637 hwi->pcm_ops->enable_in(hwi, false);
1639 hwi->pcm_ops->fini_in (hwi);
1640 QLIST_REMOVE(hwi, entries);
1643 if (s->drv) {
1644 s->drv->fini (s->drv_opaque);
1645 s->drv = NULL;
1648 if (s->dev) {
1649 qapi_free_Audiodev(s->dev);
1650 s->dev = NULL;
1653 if (s->ts) {
1654 timer_free(s->ts);
1655 s->ts = NULL;
1658 g_free(s);
1661 void audio_cleanup(void)
1663 while (!QTAILQ_EMPTY(&audio_states)) {
1664 AudioState *s = QTAILQ_FIRST(&audio_states);
1665 QTAILQ_REMOVE(&audio_states, s, list);
1666 free_audio_state(s);
1670 static bool vmstate_audio_needed(void *opaque)
1673 * Never needed, this vmstate only exists in case
1674 * an old qemu sends it to us.
1676 return false;
1679 static const VMStateDescription vmstate_audio = {
1680 .name = "audio",
1681 .version_id = 1,
1682 .minimum_version_id = 1,
1683 .needed = vmstate_audio_needed,
1684 .fields = (VMStateField[]) {
1685 VMSTATE_END_OF_LIST()
1689 static void audio_validate_opts(Audiodev *dev, Error **errp);
1691 static void audio_create_default_audiodevs(void)
1693 const char *drvname = getenv("QEMU_AUDIO_DRV");
1695 /* QEMU_AUDIO_DRV=none is used by libqtest. */
1696 if (drvname && !g_str_equal(drvname, "none")) {
1697 error_report("Please use -audiodev instead of QEMU_AUDIO_*");
1698 exit(1);
1701 for (int i = 0; audio_prio_list[i]; i++) {
1702 if (drvname && !g_str_equal(drvname, audio_prio_list[i])) {
1703 continue;
1706 if (audio_driver_lookup(audio_prio_list[i])) {
1707 QDict *dict = qdict_new();
1708 Audiodev *dev = NULL;
1709 AudiodevListEntry *e;
1710 Visitor *v;
1712 qdict_put_str(dict, "driver", audio_prio_list[i]);
1713 qdict_put_str(dict, "id", "#default");
1715 v = qobject_input_visitor_new_keyval(QOBJECT(dict));
1716 qobject_unref(dict);
1717 visit_type_Audiodev(v, NULL, &dev, &error_fatal);
1718 visit_free(v);
1720 audio_validate_opts(dev, &error_abort);
1721 e = g_new0(AudiodevListEntry, 1);
1722 e->dev = dev;
1723 QSIMPLEQ_INSERT_TAIL(&default_audiodevs, e, next);
1729 * if we have dev, this function was called because of an -audiodev argument =>
1730 * initialize a new state with it
1731 * if dev == NULL => legacy implicit initialization, return the already created
1732 * state or create a new one
1734 static AudioState *audio_init(Audiodev *dev, Error **errp)
1736 static bool atexit_registered;
1737 int done = 0;
1738 const char *drvname;
1739 VMChangeStateEntry *vmse;
1740 AudioState *s;
1741 struct audio_driver *driver;
1743 s = g_new0(AudioState, 1);
1745 QLIST_INIT (&s->hw_head_out);
1746 QLIST_INIT (&s->hw_head_in);
1747 QLIST_INIT (&s->cap_head);
1748 if (!atexit_registered) {
1749 atexit(audio_cleanup);
1750 atexit_registered = true;
1753 s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1755 if (dev) {
1756 /* -audiodev option */
1757 s->dev = dev;
1758 drvname = AudiodevDriver_str(dev->driver);
1759 driver = audio_driver_lookup(drvname);
1760 if (driver) {
1761 done = !audio_driver_init(s, driver, dev, errp);
1762 } else {
1763 error_setg(errp, "Unknown audio driver `%s'\n", drvname);
1765 if (!done) {
1766 goto out;
1768 } else {
1769 for (;;) {
1770 AudiodevListEntry *e = QSIMPLEQ_FIRST(&default_audiodevs);
1771 if (!e) {
1772 error_setg(errp, "no default audio driver available");
1773 goto out;
1775 s->dev = dev = e->dev;
1776 drvname = AudiodevDriver_str(dev->driver);
1777 driver = audio_driver_lookup(drvname);
1778 if (!audio_driver_init(s, driver, dev, NULL)) {
1779 break;
1781 QSIMPLEQ_REMOVE_HEAD(&default_audiodevs, next);
1785 if (dev->timer_period <= 0) {
1786 s->period_ticks = 1;
1787 } else {
1788 s->period_ticks = dev->timer_period * (int64_t)SCALE_US;
1791 vmse = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1792 if (!vmse) {
1793 dolog ("warning: Could not register change state handler\n"
1794 "(Audio can continue looping even after stopping the VM)\n");
1797 QTAILQ_INSERT_TAIL(&audio_states, s, list);
1798 QLIST_INIT (&s->card_head);
1799 vmstate_register (NULL, 0, &vmstate_audio, s);
1800 return s;
1802 out:
1803 free_audio_state(s);
1804 return NULL;
1807 bool AUD_register_card (const char *name, QEMUSoundCard *card, Error **errp)
1809 if (!card->state) {
1810 if (!QTAILQ_EMPTY(&audio_states)) {
1811 if (QSIMPLEQ_EMPTY(&default_audiodevs)) {
1812 dolog("Device %s: audiodev default parameter is deprecated, please "
1813 "specify audiodev=%s\n", name,
1814 QTAILQ_FIRST(&audio_states)->dev->id);
1816 card->state = QTAILQ_FIRST(&audio_states);
1817 } else {
1818 if (QSIMPLEQ_EMPTY(&default_audiodevs)) {
1819 audio_create_default_audiodevs();
1821 card->state = audio_init(NULL, errp);
1822 if (!card->state) {
1823 return false;
1828 card->name = g_strdup (name);
1829 memset (&card->entries, 0, sizeof (card->entries));
1830 QLIST_INSERT_HEAD(&card->state->card_head, card, entries);
1832 return true;
1835 void AUD_remove_card (QEMUSoundCard *card)
1837 QLIST_REMOVE (card, entries);
1838 g_free (card->name);
1841 static struct audio_pcm_ops capture_pcm_ops;
1843 CaptureVoiceOut *AUD_add_capture(
1844 AudioState *s,
1845 struct audsettings *as,
1846 struct audio_capture_ops *ops,
1847 void *cb_opaque
1850 CaptureVoiceOut *cap;
1851 struct capture_callback *cb;
1853 if (!s) {
1854 error_report("Capturing without setting an audiodev is not supported");
1855 abort();
1858 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1859 dolog("Can't capture with mixeng disabled\n");
1860 return NULL;
1863 if (audio_validate_settings (as)) {
1864 dolog ("Invalid settings were passed when trying to add capture\n");
1865 audio_print_settings (as);
1866 return NULL;
1869 cb = g_malloc0(sizeof(*cb));
1870 cb->ops = *ops;
1871 cb->opaque = cb_opaque;
1873 cap = audio_pcm_capture_find_specific(s, as);
1874 if (cap) {
1875 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1876 } else {
1877 HWVoiceOut *hw;
1879 cap = g_malloc0(sizeof(*cap));
1881 hw = &cap->hw;
1882 hw->s = s;
1883 hw->pcm_ops = &capture_pcm_ops;
1884 QLIST_INIT (&hw->sw_head);
1885 QLIST_INIT (&cap->cb_head);
1887 /* XXX find a more elegant way */
1888 hw->samples = 4096 * 4;
1889 audio_pcm_hw_alloc_resources_out(hw);
1891 audio_pcm_init_info (&hw->info, as);
1893 cap->buf = g_malloc0_n(hw->mix_buf.size, hw->info.bytes_per_frame);
1895 if (hw->info.is_float) {
1896 hw->clip = mixeng_clip_float[hw->info.nchannels == 2];
1897 } else {
1898 hw->clip = mixeng_clip
1899 [hw->info.nchannels == 2]
1900 [hw->info.is_signed]
1901 [hw->info.swap_endianness]
1902 [audio_bits_to_index(hw->info.bits)];
1905 QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1906 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1908 QLIST_FOREACH(hw, &s->hw_head_out, entries) {
1909 audio_attach_capture (hw);
1913 return cap;
1916 void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1918 struct capture_callback *cb;
1920 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1921 if (cb->opaque == cb_opaque) {
1922 cb->ops.destroy (cb_opaque);
1923 QLIST_REMOVE (cb, entries);
1924 g_free (cb);
1926 if (!cap->cb_head.lh_first) {
1927 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
1929 while (sw) {
1930 SWVoiceCap *sc = (SWVoiceCap *) sw;
1931 #ifdef DEBUG_CAPTURE
1932 dolog ("freeing %s\n", sw->name);
1933 #endif
1935 sw1 = sw->entries.le_next;
1936 if (sw->rate) {
1937 st_rate_stop (sw->rate);
1938 sw->rate = NULL;
1940 QLIST_REMOVE (sw, entries);
1941 QLIST_REMOVE (sc, entries);
1942 g_free (sc);
1943 sw = sw1;
1945 QLIST_REMOVE (cap, entries);
1946 g_free(cap->hw.mix_buf.buffer);
1947 g_free (cap->buf);
1948 g_free (cap);
1950 return;
1955 void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
1957 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1958 audio_set_volume_out(sw, &vol);
1961 void audio_set_volume_out(SWVoiceOut *sw, Volume *vol)
1963 if (sw) {
1964 HWVoiceOut *hw = sw->hw;
1966 sw->vol.mute = vol->mute;
1967 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
1968 sw->vol.r = nominal_volume.l * vol->vol[vol->channels > 1 ? 1 : 0] /
1969 255;
1971 if (hw->pcm_ops->volume_out) {
1972 hw->pcm_ops->volume_out(hw, vol);
1977 void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
1979 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1980 audio_set_volume_in(sw, &vol);
1983 void audio_set_volume_in(SWVoiceIn *sw, Volume *vol)
1985 if (sw) {
1986 HWVoiceIn *hw = sw->hw;
1988 sw->vol.mute = vol->mute;
1989 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
1990 sw->vol.r = nominal_volume.r * vol->vol[vol->channels > 1 ? 1 : 0] /
1991 255;
1993 if (hw->pcm_ops->volume_in) {
1994 hw->pcm_ops->volume_in(hw, vol);
1999 void audio_create_pdos(Audiodev *dev)
2001 switch (dev->driver) {
2002 #define CASE(DRIVER, driver, pdo_name) \
2003 case AUDIODEV_DRIVER_##DRIVER: \
2004 if (!dev->u.driver.in) { \
2005 dev->u.driver.in = g_malloc0( \
2006 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
2008 if (!dev->u.driver.out) { \
2009 dev->u.driver.out = g_malloc0( \
2010 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
2012 break
2014 CASE(NONE, none, );
2015 #ifdef CONFIG_AUDIO_ALSA
2016 CASE(ALSA, alsa, Alsa);
2017 #endif
2018 #ifdef CONFIG_AUDIO_COREAUDIO
2019 CASE(COREAUDIO, coreaudio, Coreaudio);
2020 #endif
2021 #ifdef CONFIG_DBUS_DISPLAY
2022 CASE(DBUS, dbus, );
2023 #endif
2024 #ifdef CONFIG_AUDIO_DSOUND
2025 CASE(DSOUND, dsound, );
2026 #endif
2027 #ifdef CONFIG_AUDIO_JACK
2028 CASE(JACK, jack, Jack);
2029 #endif
2030 #ifdef CONFIG_AUDIO_OSS
2031 CASE(OSS, oss, Oss);
2032 #endif
2033 #ifdef CONFIG_AUDIO_PA
2034 CASE(PA, pa, Pa);
2035 #endif
2036 #ifdef CONFIG_AUDIO_PIPEWIRE
2037 CASE(PIPEWIRE, pipewire, Pipewire);
2038 #endif
2039 #ifdef CONFIG_AUDIO_SDL
2040 CASE(SDL, sdl, Sdl);
2041 #endif
2042 #ifdef CONFIG_AUDIO_SNDIO
2043 CASE(SNDIO, sndio, );
2044 #endif
2045 #ifdef CONFIG_SPICE
2046 CASE(SPICE, spice, );
2047 #endif
2048 CASE(WAV, wav, );
2050 case AUDIODEV_DRIVER__MAX:
2051 abort();
2055 static void audio_validate_per_direction_opts(
2056 AudiodevPerDirectionOptions *pdo, Error **errp)
2058 if (!pdo->has_mixing_engine) {
2059 pdo->has_mixing_engine = true;
2060 pdo->mixing_engine = true;
2062 if (!pdo->has_fixed_settings) {
2063 pdo->has_fixed_settings = true;
2064 pdo->fixed_settings = pdo->mixing_engine;
2066 if (!pdo->fixed_settings &&
2067 (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
2068 error_setg(errp,
2069 "You can't use frequency, channels or format with fixed-settings=off");
2070 return;
2072 if (!pdo->mixing_engine && pdo->fixed_settings) {
2073 error_setg(errp, "You can't use fixed-settings without mixeng");
2074 return;
2077 if (!pdo->has_frequency) {
2078 pdo->has_frequency = true;
2079 pdo->frequency = 44100;
2081 if (!pdo->has_channels) {
2082 pdo->has_channels = true;
2083 pdo->channels = 2;
2085 if (!pdo->has_voices) {
2086 pdo->has_voices = true;
2087 pdo->voices = pdo->mixing_engine ? 1 : INT_MAX;
2089 if (!pdo->has_format) {
2090 pdo->has_format = true;
2091 pdo->format = AUDIO_FORMAT_S16;
2095 static void audio_validate_opts(Audiodev *dev, Error **errp)
2097 Error *err = NULL;
2099 audio_create_pdos(dev);
2101 audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
2102 if (err) {
2103 error_propagate(errp, err);
2104 return;
2107 audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
2108 if (err) {
2109 error_propagate(errp, err);
2110 return;
2113 if (!dev->has_timer_period) {
2114 dev->has_timer_period = true;
2115 dev->timer_period = 10000; /* 100Hz -> 10ms */
2119 void audio_help(void)
2121 int i;
2123 printf("Available audio drivers:\n");
2125 for (i = 0; i < AUDIODEV_DRIVER__MAX; i++) {
2126 audio_driver *driver = audio_driver_lookup(AudiodevDriver_str(i));
2127 if (driver) {
2128 printf("%s\n", driver->name);
2133 void audio_parse_option(const char *opt)
2135 Audiodev *dev = NULL;
2137 if (is_help_option(opt)) {
2138 audio_help();
2139 exit(EXIT_SUCCESS);
2141 Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
2142 visit_type_Audiodev(v, NULL, &dev, &error_fatal);
2143 visit_free(v);
2145 audio_define(dev);
2148 void audio_define(Audiodev *dev)
2150 AudiodevListEntry *e;
2152 audio_validate_opts(dev, &error_fatal);
2154 e = g_new0(AudiodevListEntry, 1);
2155 e->dev = dev;
2156 QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
2159 void audio_init_audiodevs(void)
2161 AudiodevListEntry *e;
2163 QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2164 audio_init(e->dev, &error_fatal);
2168 audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
2170 return (audsettings) {
2171 .freq = pdo->frequency,
2172 .nchannels = pdo->channels,
2173 .fmt = pdo->format,
2174 .endianness = AUDIO_HOST_ENDIANNESS,
2178 int audioformat_bytes_per_sample(AudioFormat fmt)
2180 switch (fmt) {
2181 case AUDIO_FORMAT_U8:
2182 case AUDIO_FORMAT_S8:
2183 return 1;
2185 case AUDIO_FORMAT_U16:
2186 case AUDIO_FORMAT_S16:
2187 return 2;
2189 case AUDIO_FORMAT_U32:
2190 case AUDIO_FORMAT_S32:
2191 case AUDIO_FORMAT_F32:
2192 return 4;
2194 case AUDIO_FORMAT__MAX:
2197 abort();
2201 /* frames = freq * usec / 1e6 */
2202 int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
2203 audsettings *as, int def_usecs)
2205 uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
2206 return (as->freq * usecs + 500000) / 1000000;
2209 /* samples = channels * frames = channels * freq * usec / 1e6 */
2210 int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
2211 audsettings *as, int def_usecs)
2213 return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
2217 * bytes = bytes_per_sample * samples =
2218 * bytes_per_sample * channels * freq * usec / 1e6
2220 int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
2221 audsettings *as, int def_usecs)
2223 return audio_buffer_samples(pdo, as, def_usecs) *
2224 audioformat_bytes_per_sample(as->fmt);
2227 AudioState *audio_state_by_name(const char *name, Error **errp)
2229 AudioState *s;
2230 QTAILQ_FOREACH(s, &audio_states, list) {
2231 assert(s->dev);
2232 if (strcmp(name, s->dev->id) == 0) {
2233 return s;
2236 error_setg(errp, "audiodev '%s' not found", name);
2237 return NULL;
2240 const char *audio_get_id(QEMUSoundCard *card)
2242 if (card->state) {
2243 assert(card->state->dev);
2244 return card->state->dev->id;
2245 } else {
2246 return "";
2250 const char *audio_application_name(void)
2252 const char *vm_name;
2254 vm_name = qemu_get_vm_name();
2255 return vm_name ? vm_name : "qemu";
2258 void audio_rate_start(RateCtl *rate)
2260 memset(rate, 0, sizeof(RateCtl));
2261 rate->start_ticks = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2264 size_t audio_rate_peek_bytes(RateCtl *rate, struct audio_pcm_info *info)
2266 int64_t now;
2267 int64_t ticks;
2268 int64_t bytes;
2269 int64_t frames;
2271 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2272 ticks = now - rate->start_ticks;
2273 bytes = muldiv64(ticks, info->bytes_per_second, NANOSECONDS_PER_SECOND);
2274 frames = (bytes - rate->bytes_sent) / info->bytes_per_frame;
2275 if (frames < 0 || frames > 65536) {
2276 AUD_log(NULL, "Resetting rate control (%" PRId64 " frames)\n", frames);
2277 audio_rate_start(rate);
2278 frames = 0;
2281 return frames * info->bytes_per_frame;
2284 void audio_rate_add_bytes(RateCtl *rate, size_t bytes_used)
2286 rate->bytes_sent += bytes_used;
2289 size_t audio_rate_get_bytes(RateCtl *rate, struct audio_pcm_info *info,
2290 size_t bytes_avail)
2292 size_t bytes;
2294 bytes = audio_rate_peek_bytes(rate, info);
2295 bytes = MIN(bytes, bytes_avail);
2296 audio_rate_add_bytes(rate, bytes);
2298 return bytes;
2301 AudiodevList *qmp_query_audiodevs(Error **errp)
2303 AudiodevList *ret = NULL;
2304 AudiodevListEntry *e;
2305 QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2306 QAPI_LIST_PREPEND(ret, QAPI_CLONE(Audiodev, e->dev));
2308 return ret;