target/ppc: use Vsr macros in BCD helpers
[qemu/ar7.git] / audio / audio.c
blob7128ee98dc97e08ea2890f5cc7a56c92243af668
1 /*
2 * QEMU Audio subsystem
4 * Copyright (c) 2003-2005 Vassili Karpov (malc)
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
26 #include "audio.h"
27 #include "migration/vmstate.h"
28 #include "monitor/monitor.h"
29 #include "qemu/timer.h"
30 #include "qapi/error.h"
31 #include "qapi/qobject-input-visitor.h"
32 #include "qapi/qapi-visit-audio.h"
33 #include "qemu/cutils.h"
34 #include "qemu/module.h"
35 #include "sysemu/replay.h"
36 #include "sysemu/runstate.h"
37 #include "trace.h"
39 #define AUDIO_CAP "audio"
40 #include "audio_int.h"
42 /* #define DEBUG_LIVE */
43 /* #define DEBUG_OUT */
44 /* #define DEBUG_CAPTURE */
45 /* #define DEBUG_POLL */
47 #define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
50 /* Order of CONFIG_AUDIO_DRIVERS is import.
51 The 1st one is the one used by default, that is the reason
52 that we generate the list.
54 const char *audio_prio_list[] = {
55 "spice",
56 CONFIG_AUDIO_DRIVERS
57 "none",
58 "wav",
59 NULL
62 static QLIST_HEAD(, audio_driver) audio_drivers;
63 static AudiodevListHead audiodevs = QSIMPLEQ_HEAD_INITIALIZER(audiodevs);
65 void audio_driver_register(audio_driver *drv)
67 QLIST_INSERT_HEAD(&audio_drivers, drv, next);
70 audio_driver *audio_driver_lookup(const char *name)
72 struct audio_driver *d;
74 QLIST_FOREACH(d, &audio_drivers, next) {
75 if (strcmp(name, d->name) == 0) {
76 return d;
80 audio_module_load_one(name);
81 QLIST_FOREACH(d, &audio_drivers, next) {
82 if (strcmp(name, d->name) == 0) {
83 return d;
87 return NULL;
90 static QTAILQ_HEAD(AudioStateHead, AudioState) audio_states =
91 QTAILQ_HEAD_INITIALIZER(audio_states);
93 const struct mixeng_volume nominal_volume = {
94 .mute = 0,
95 #ifdef FLOAT_MIXENG
96 .r = 1.0,
97 .l = 1.0,
98 #else
99 .r = 1ULL << 32,
100 .l = 1ULL << 32,
101 #endif
104 static bool legacy_config = true;
106 #ifdef AUDIO_IS_FLAWLESS_AND_NO_CHECKS_ARE_REQURIED
107 #error No its not
108 #else
109 int audio_bug (const char *funcname, int cond)
111 if (cond) {
112 static int shown;
114 AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
115 if (!shown) {
116 shown = 1;
117 AUD_log (NULL, "Save all your work and restart without audio\n");
118 AUD_log (NULL, "I am sorry\n");
120 AUD_log (NULL, "Context:\n");
122 #if defined AUDIO_BREAKPOINT_ON_BUG
123 # if defined HOST_I386
124 # if defined __GNUC__
125 __asm__ ("int3");
126 # elif defined _MSC_VER
127 _asm _emit 0xcc;
128 # else
129 abort ();
130 # endif
131 # else
132 abort ();
133 # endif
134 #endif
137 return cond;
139 #endif
141 static inline int audio_bits_to_index (int bits)
143 switch (bits) {
144 case 8:
145 return 0;
147 case 16:
148 return 1;
150 case 32:
151 return 2;
153 default:
154 audio_bug ("bits_to_index", 1);
155 AUD_log (NULL, "invalid bits %d\n", bits);
156 return 0;
160 void *audio_calloc (const char *funcname, int nmemb, size_t size)
162 int cond;
163 size_t len;
165 len = nmemb * size;
166 cond = !nmemb || !size;
167 cond |= nmemb < 0;
168 cond |= len < size;
170 if (audio_bug ("audio_calloc", cond)) {
171 AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
172 funcname);
173 AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
174 return NULL;
177 return g_malloc0 (len);
180 void AUD_vlog (const char *cap, const char *fmt, va_list ap)
182 if (cap) {
183 fprintf(stderr, "%s: ", cap);
186 vfprintf(stderr, fmt, ap);
189 void AUD_log (const char *cap, const char *fmt, ...)
191 va_list ap;
193 va_start (ap, fmt);
194 AUD_vlog (cap, fmt, ap);
195 va_end (ap);
198 static void audio_print_settings (struct audsettings *as)
200 dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
202 switch (as->fmt) {
203 case AUDIO_FORMAT_S8:
204 AUD_log (NULL, "S8");
205 break;
206 case AUDIO_FORMAT_U8:
207 AUD_log (NULL, "U8");
208 break;
209 case AUDIO_FORMAT_S16:
210 AUD_log (NULL, "S16");
211 break;
212 case AUDIO_FORMAT_U16:
213 AUD_log (NULL, "U16");
214 break;
215 case AUDIO_FORMAT_S32:
216 AUD_log (NULL, "S32");
217 break;
218 case AUDIO_FORMAT_U32:
219 AUD_log (NULL, "U32");
220 break;
221 default:
222 AUD_log (NULL, "invalid(%d)", as->fmt);
223 break;
226 AUD_log (NULL, " endianness=");
227 switch (as->endianness) {
228 case 0:
229 AUD_log (NULL, "little");
230 break;
231 case 1:
232 AUD_log (NULL, "big");
233 break;
234 default:
235 AUD_log (NULL, "invalid");
236 break;
238 AUD_log (NULL, "\n");
241 static int audio_validate_settings (struct audsettings *as)
243 int invalid;
245 invalid = as->nchannels != 1 && as->nchannels != 2;
246 invalid |= as->endianness != 0 && as->endianness != 1;
248 switch (as->fmt) {
249 case AUDIO_FORMAT_S8:
250 case AUDIO_FORMAT_U8:
251 case AUDIO_FORMAT_S16:
252 case AUDIO_FORMAT_U16:
253 case AUDIO_FORMAT_S32:
254 case AUDIO_FORMAT_U32:
255 break;
256 default:
257 invalid = 1;
258 break;
261 invalid |= as->freq <= 0;
262 return invalid ? -1 : 0;
265 static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
267 int bits = 8, sign = 0;
269 switch (as->fmt) {
270 case AUDIO_FORMAT_S8:
271 sign = 1;
272 /* fall through */
273 case AUDIO_FORMAT_U8:
274 break;
276 case AUDIO_FORMAT_S16:
277 sign = 1;
278 /* fall through */
279 case AUDIO_FORMAT_U16:
280 bits = 16;
281 break;
283 case AUDIO_FORMAT_S32:
284 sign = 1;
285 /* fall through */
286 case AUDIO_FORMAT_U32:
287 bits = 32;
288 break;
290 default:
291 abort();
293 return info->freq == as->freq
294 && info->nchannels == as->nchannels
295 && info->sign == sign
296 && info->bits == bits
297 && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
300 void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
302 int bits = 8, sign = 0, shift = 0;
304 switch (as->fmt) {
305 case AUDIO_FORMAT_S8:
306 sign = 1;
307 case AUDIO_FORMAT_U8:
308 break;
310 case AUDIO_FORMAT_S16:
311 sign = 1;
312 /* fall through */
313 case AUDIO_FORMAT_U16:
314 bits = 16;
315 shift = 1;
316 break;
318 case AUDIO_FORMAT_S32:
319 sign = 1;
320 /* fall through */
321 case AUDIO_FORMAT_U32:
322 bits = 32;
323 shift = 2;
324 break;
326 default:
327 abort();
330 info->freq = as->freq;
331 info->bits = bits;
332 info->sign = sign;
333 info->nchannels = as->nchannels;
334 info->shift = (as->nchannels == 2) + shift;
335 info->align = (1 << info->shift) - 1;
336 info->bytes_per_second = info->freq << info->shift;
337 info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
340 void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
342 if (!len) {
343 return;
346 if (info->sign) {
347 memset (buf, 0x00, len << info->shift);
349 else {
350 switch (info->bits) {
351 case 8:
352 memset (buf, 0x80, len << info->shift);
353 break;
355 case 16:
357 int i;
358 uint16_t *p = buf;
359 int shift = info->nchannels - 1;
360 short s = INT16_MAX;
362 if (info->swap_endianness) {
363 s = bswap16 (s);
366 for (i = 0; i < len << shift; i++) {
367 p[i] = s;
370 break;
372 case 32:
374 int i;
375 uint32_t *p = buf;
376 int shift = info->nchannels - 1;
377 int32_t s = INT32_MAX;
379 if (info->swap_endianness) {
380 s = bswap32 (s);
383 for (i = 0; i < len << shift; i++) {
384 p[i] = s;
387 break;
389 default:
390 AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
391 info->bits);
392 break;
398 * Capture
400 static void noop_conv (struct st_sample *dst, const void *src, int samples)
402 (void) src;
403 (void) dst;
404 (void) samples;
407 static CaptureVoiceOut *audio_pcm_capture_find_specific(AudioState *s,
408 struct audsettings *as)
410 CaptureVoiceOut *cap;
412 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
413 if (audio_pcm_info_eq (&cap->hw.info, as)) {
414 return cap;
417 return NULL;
420 static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
422 struct capture_callback *cb;
424 #ifdef DEBUG_CAPTURE
425 dolog ("notification %d sent\n", cmd);
426 #endif
427 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
428 cb->ops.notify (cb->opaque, cmd);
432 static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
434 if (cap->hw.enabled != enabled) {
435 audcnotification_e cmd;
436 cap->hw.enabled = enabled;
437 cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
438 audio_notify_capture (cap, cmd);
442 static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
444 HWVoiceOut *hw = &cap->hw;
445 SWVoiceOut *sw;
446 int enabled = 0;
448 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
449 if (sw->active) {
450 enabled = 1;
451 break;
454 audio_capture_maybe_changed (cap, enabled);
457 static void audio_detach_capture (HWVoiceOut *hw)
459 SWVoiceCap *sc = hw->cap_head.lh_first;
461 while (sc) {
462 SWVoiceCap *sc1 = sc->entries.le_next;
463 SWVoiceOut *sw = &sc->sw;
464 CaptureVoiceOut *cap = sc->cap;
465 int was_active = sw->active;
467 if (sw->rate) {
468 st_rate_stop (sw->rate);
469 sw->rate = NULL;
472 QLIST_REMOVE (sw, entries);
473 QLIST_REMOVE (sc, entries);
474 g_free (sc);
475 if (was_active) {
476 /* We have removed soft voice from the capture:
477 this might have changed the overall status of the capture
478 since this might have been the only active voice */
479 audio_recalc_and_notify_capture (cap);
481 sc = sc1;
485 static int audio_attach_capture (HWVoiceOut *hw)
487 AudioState *s = hw->s;
488 CaptureVoiceOut *cap;
490 audio_detach_capture (hw);
491 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
492 SWVoiceCap *sc;
493 SWVoiceOut *sw;
494 HWVoiceOut *hw_cap = &cap->hw;
496 sc = g_malloc0(sizeof(*sc));
498 sc->cap = cap;
499 sw = &sc->sw;
500 sw->hw = hw_cap;
501 sw->info = hw->info;
502 sw->empty = 1;
503 sw->active = hw->enabled;
504 sw->conv = noop_conv;
505 sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
506 sw->vol = nominal_volume;
507 sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
508 if (!sw->rate) {
509 dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
510 g_free (sw);
511 return -1;
513 QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
514 QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
515 #ifdef DEBUG_CAPTURE
516 sw->name = g_strdup_printf ("for %p %d,%d,%d",
517 hw, sw->info.freq, sw->info.bits,
518 sw->info.nchannels);
519 dolog ("Added %s active = %d\n", sw->name, sw->active);
520 #endif
521 if (sw->active) {
522 audio_capture_maybe_changed (cap, 1);
525 return 0;
529 * Hard voice (capture)
531 static size_t audio_pcm_hw_find_min_in (HWVoiceIn *hw)
533 SWVoiceIn *sw;
534 size_t m = hw->total_samples_captured;
536 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
537 if (sw->active) {
538 m = MIN (m, sw->total_hw_samples_acquired);
541 return m;
544 static size_t audio_pcm_hw_get_live_in(HWVoiceIn *hw)
546 size_t live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
547 if (audio_bug(__func__, live > hw->conv_buf->size)) {
548 dolog("live=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
549 return 0;
551 return live;
554 static void audio_pcm_hw_clip_out(HWVoiceOut *hw, void *pcm_buf, size_t len)
556 size_t clipped = 0;
557 size_t pos = hw->mix_buf->pos;
559 while (len) {
560 st_sample *src = hw->mix_buf->samples + pos;
561 uint8_t *dst = advance(pcm_buf, clipped << hw->info.shift);
562 size_t samples_till_end_of_buf = hw->mix_buf->size - pos;
563 size_t samples_to_clip = MIN(len, samples_till_end_of_buf);
565 hw->clip(dst, src, samples_to_clip);
567 pos = (pos + samples_to_clip) % hw->mix_buf->size;
568 len -= samples_to_clip;
569 clipped += samples_to_clip;
574 * Soft voice (capture)
576 static size_t audio_pcm_sw_get_rpos_in(SWVoiceIn *sw)
578 HWVoiceIn *hw = sw->hw;
579 ssize_t live = hw->total_samples_captured - sw->total_hw_samples_acquired;
580 ssize_t rpos;
582 if (audio_bug(__func__, live < 0 || live > hw->conv_buf->size)) {
583 dolog("live=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
584 return 0;
587 rpos = hw->conv_buf->pos - live;
588 if (rpos >= 0) {
589 return rpos;
591 else {
592 return hw->conv_buf->size + rpos;
596 static size_t audio_pcm_sw_read(SWVoiceIn *sw, void *buf, size_t size)
598 HWVoiceIn *hw = sw->hw;
599 size_t samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
600 struct st_sample *src, *dst = sw->buf;
602 rpos = audio_pcm_sw_get_rpos_in(sw) % hw->conv_buf->size;
604 live = hw->total_samples_captured - sw->total_hw_samples_acquired;
605 if (audio_bug(__func__, live > hw->conv_buf->size)) {
606 dolog("live_in=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
607 return 0;
610 samples = size >> sw->info.shift;
611 if (!live) {
612 return 0;
615 swlim = (live * sw->ratio) >> 32;
616 swlim = MIN (swlim, samples);
618 while (swlim) {
619 src = hw->conv_buf->samples + rpos;
620 if (hw->conv_buf->pos > rpos) {
621 isamp = hw->conv_buf->pos - rpos;
622 } else {
623 isamp = hw->conv_buf->size - rpos;
626 if (!isamp) {
627 break;
629 osamp = swlim;
631 st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
632 swlim -= osamp;
633 rpos = (rpos + isamp) % hw->conv_buf->size;
634 dst += osamp;
635 ret += osamp;
636 total += isamp;
639 if (!hw->pcm_ops->volume_in) {
640 mixeng_volume (sw->buf, ret, &sw->vol);
643 sw->clip (buf, sw->buf, ret);
644 sw->total_hw_samples_acquired += total;
645 return ret << sw->info.shift;
649 * Hard voice (playback)
651 static size_t audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
653 SWVoiceOut *sw;
654 size_t m = SIZE_MAX;
655 int nb_live = 0;
657 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
658 if (sw->active || !sw->empty) {
659 m = MIN (m, sw->total_hw_samples_mixed);
660 nb_live += 1;
664 *nb_livep = nb_live;
665 return m;
668 static size_t audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
670 size_t smin;
671 int nb_live1;
673 smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
674 if (nb_live) {
675 *nb_live = nb_live1;
678 if (nb_live1) {
679 size_t live = smin;
681 if (audio_bug(__func__, live > hw->mix_buf->size)) {
682 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
683 return 0;
685 return live;
687 return 0;
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, swlim, blck;
696 size_t ret = 0, pos = 0, total = 0;
698 if (!sw) {
699 return size;
702 hwsamples = sw->hw->mix_buf->size;
704 live = sw->total_hw_samples_mixed;
705 if (audio_bug(__func__, live > hwsamples)) {
706 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hwsamples);
707 return 0;
710 if (live == hwsamples) {
711 #ifdef DEBUG_OUT
712 dolog ("%s is full %d\n", sw->name, live);
713 #endif
714 return 0;
717 wpos = (sw->hw->mix_buf->pos + live) % hwsamples;
718 samples = size >> sw->info.shift;
720 dead = hwsamples - live;
721 swlim = ((int64_t) dead << 32) / sw->ratio;
722 swlim = MIN (swlim, samples);
723 if (swlim) {
724 sw->conv (sw->buf, buf, swlim);
726 if (!sw->hw->pcm_ops->volume_out) {
727 mixeng_volume (sw->buf, swlim, &sw->vol);
731 while (swlim) {
732 dead = hwsamples - live;
733 left = hwsamples - wpos;
734 blck = MIN (dead, left);
735 if (!blck) {
736 break;
738 isamp = swlim;
739 osamp = blck;
740 st_rate_flow_mix (
741 sw->rate,
742 sw->buf + pos,
743 sw->hw->mix_buf->samples + wpos,
744 &isamp,
745 &osamp
747 ret += isamp;
748 swlim -= isamp;
749 pos += isamp;
750 live += osamp;
751 wpos = (wpos + osamp) % hwsamples;
752 total += osamp;
755 sw->total_hw_samples_mixed += total;
756 sw->empty = sw->total_hw_samples_mixed == 0;
758 #ifdef DEBUG_OUT
759 dolog (
760 "%s: write size %zu ret %zu total sw %zu\n",
761 SW_NAME (sw),
762 size >> sw->info.shift,
763 ret,
764 sw->total_hw_samples_mixed
766 #endif
768 return ret << sw->info.shift;
771 #ifdef DEBUG_AUDIO
772 static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
774 dolog ("%s: bits %d, sign %d, freq %d, nchan %d\n",
775 cap, info->bits, info->sign, info->freq, info->nchannels);
777 #endif
779 #define DAC
780 #include "audio_template.h"
781 #undef DAC
782 #include "audio_template.h"
785 * Timer
787 static int audio_is_timer_needed(AudioState *s)
789 HWVoiceIn *hwi = NULL;
790 HWVoiceOut *hwo = NULL;
792 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
793 if (!hwo->poll_mode) return 1;
795 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
796 if (!hwi->poll_mode) return 1;
798 return 0;
801 static void audio_reset_timer (AudioState *s)
803 if (audio_is_timer_needed(s)) {
804 timer_mod_anticipate_ns(s->ts,
805 qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
806 if (!s->timer_running) {
807 s->timer_running = true;
808 s->timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
809 trace_audio_timer_start(s->period_ticks / SCALE_MS);
811 } else {
812 timer_del(s->ts);
813 if (s->timer_running) {
814 s->timer_running = false;
815 trace_audio_timer_stop();
820 static void audio_timer (void *opaque)
822 int64_t now, diff;
823 AudioState *s = opaque;
825 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
826 diff = now - s->timer_last;
827 if (diff > s->period_ticks * 3 / 2) {
828 trace_audio_timer_delayed(diff / SCALE_MS);
830 s->timer_last = now;
832 audio_run(s, "timer");
833 audio_reset_timer(s);
837 * Public API
839 size_t AUD_write(SWVoiceOut *sw, void *buf, size_t size)
841 if (!sw) {
842 /* XXX: Consider options */
843 return size;
846 if (!sw->hw->enabled) {
847 dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
848 return 0;
851 return audio_pcm_sw_write(sw, buf, size);
854 size_t AUD_read(SWVoiceIn *sw, void *buf, size_t size)
856 if (!sw) {
857 /* XXX: Consider options */
858 return size;
861 if (!sw->hw->enabled) {
862 dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
863 return 0;
866 return audio_pcm_sw_read(sw, buf, size);
869 int AUD_get_buffer_size_out (SWVoiceOut *sw)
871 return sw->hw->mix_buf->size << sw->hw->info.shift;
874 void AUD_set_active_out (SWVoiceOut *sw, int on)
876 HWVoiceOut *hw;
878 if (!sw) {
879 return;
882 hw = sw->hw;
883 if (sw->active != on) {
884 AudioState *s = sw->s;
885 SWVoiceOut *temp_sw;
886 SWVoiceCap *sc;
888 if (on) {
889 hw->pending_disable = 0;
890 if (!hw->enabled) {
891 hw->enabled = 1;
892 if (s->vm_running) {
893 if (hw->pcm_ops->enable_out) {
894 hw->pcm_ops->enable_out(hw, true);
896 audio_reset_timer (s);
900 else {
901 if (hw->enabled) {
902 int nb_active = 0;
904 for (temp_sw = hw->sw_head.lh_first; temp_sw;
905 temp_sw = temp_sw->entries.le_next) {
906 nb_active += temp_sw->active != 0;
909 hw->pending_disable = nb_active == 1;
913 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
914 sc->sw.active = hw->enabled;
915 if (hw->enabled) {
916 audio_capture_maybe_changed (sc->cap, 1);
919 sw->active = on;
923 void AUD_set_active_in (SWVoiceIn *sw, int on)
925 HWVoiceIn *hw;
927 if (!sw) {
928 return;
931 hw = sw->hw;
932 if (sw->active != on) {
933 AudioState *s = sw->s;
934 SWVoiceIn *temp_sw;
936 if (on) {
937 if (!hw->enabled) {
938 hw->enabled = 1;
939 if (s->vm_running) {
940 if (hw->pcm_ops->enable_in) {
941 hw->pcm_ops->enable_in(hw, true);
943 audio_reset_timer (s);
946 sw->total_hw_samples_acquired = hw->total_samples_captured;
948 else {
949 if (hw->enabled) {
950 int nb_active = 0;
952 for (temp_sw = hw->sw_head.lh_first; temp_sw;
953 temp_sw = temp_sw->entries.le_next) {
954 nb_active += temp_sw->active != 0;
957 if (nb_active == 1) {
958 hw->enabled = 0;
959 if (hw->pcm_ops->enable_in) {
960 hw->pcm_ops->enable_in(hw, false);
965 sw->active = on;
969 static size_t audio_get_avail (SWVoiceIn *sw)
971 size_t live;
973 if (!sw) {
974 return 0;
977 live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
978 if (audio_bug(__func__, live > sw->hw->conv_buf->size)) {
979 dolog("live=%zu sw->hw->conv_buf->size=%zu\n", live,
980 sw->hw->conv_buf->size);
981 return 0;
984 ldebug (
985 "%s: get_avail live %d ret %" PRId64 "\n",
986 SW_NAME (sw),
987 live, (((int64_t) live << 32) / sw->ratio) << sw->info.shift
990 return (((int64_t) live << 32) / sw->ratio) << sw->info.shift;
993 static size_t audio_get_free(SWVoiceOut *sw)
995 size_t live, dead;
997 if (!sw) {
998 return 0;
1001 live = sw->total_hw_samples_mixed;
1003 if (audio_bug(__func__, live > sw->hw->mix_buf->size)) {
1004 dolog("live=%zu sw->hw->mix_buf->size=%zu\n", live,
1005 sw->hw->mix_buf->size);
1006 return 0;
1009 dead = sw->hw->mix_buf->size - live;
1011 #ifdef DEBUG_OUT
1012 dolog ("%s: get_free live %d dead %d ret %" PRId64 "\n",
1013 SW_NAME (sw),
1014 live, dead, (((int64_t) dead << 32) / sw->ratio) << sw->info.shift);
1015 #endif
1017 return (((int64_t) dead << 32) / sw->ratio) << sw->info.shift;
1020 static void audio_capture_mix_and_clear(HWVoiceOut *hw, size_t rpos,
1021 size_t samples)
1023 size_t n;
1025 if (hw->enabled) {
1026 SWVoiceCap *sc;
1028 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1029 SWVoiceOut *sw = &sc->sw;
1030 int rpos2 = rpos;
1032 n = samples;
1033 while (n) {
1034 size_t till_end_of_hw = hw->mix_buf->size - rpos2;
1035 size_t to_write = MIN(till_end_of_hw, n);
1036 size_t bytes = to_write << hw->info.shift;
1037 size_t written;
1039 sw->buf = hw->mix_buf->samples + rpos2;
1040 written = audio_pcm_sw_write (sw, NULL, bytes);
1041 if (written - bytes) {
1042 dolog("Could not mix %zu bytes into a capture "
1043 "buffer, mixed %zu\n",
1044 bytes, written);
1045 break;
1047 n -= to_write;
1048 rpos2 = (rpos2 + to_write) % hw->mix_buf->size;
1053 n = MIN(samples, hw->mix_buf->size - rpos);
1054 mixeng_clear(hw->mix_buf->samples + rpos, n);
1055 mixeng_clear(hw->mix_buf->samples, samples - n);
1058 static size_t audio_pcm_hw_run_out(HWVoiceOut *hw, size_t live)
1060 size_t clipped = 0;
1062 while (live) {
1063 size_t size, decr, proc;
1064 void *buf = hw->pcm_ops->get_buffer_out(hw, &size);
1065 if (!buf) {
1066 /* retrying will likely won't help, drop everything. */
1067 hw->mix_buf->pos = (hw->mix_buf->pos + live) % hw->mix_buf->size;
1068 return clipped + live;
1071 decr = MIN(size >> hw->info.shift, live);
1072 audio_pcm_hw_clip_out(hw, buf, decr);
1073 proc = hw->pcm_ops->put_buffer_out(hw, buf, decr << hw->info.shift) >>
1074 hw->info.shift;
1076 live -= proc;
1077 clipped += proc;
1078 hw->mix_buf->pos = (hw->mix_buf->pos + proc) % hw->mix_buf->size;
1080 if (proc == 0 || proc < decr) {
1081 break;
1085 return clipped;
1088 static void audio_run_out (AudioState *s)
1090 HWVoiceOut *hw = NULL;
1091 SWVoiceOut *sw;
1093 while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1094 size_t played, live, prev_rpos, free;
1095 int nb_live, cleanup_required;
1097 live = audio_pcm_hw_get_live_out (hw, &nb_live);
1098 if (!nb_live) {
1099 live = 0;
1102 if (audio_bug(__func__, live > hw->mix_buf->size)) {
1103 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
1104 continue;
1107 if (hw->pending_disable && !nb_live) {
1108 SWVoiceCap *sc;
1109 #ifdef DEBUG_OUT
1110 dolog ("Disabling voice\n");
1111 #endif
1112 hw->enabled = 0;
1113 hw->pending_disable = 0;
1114 if (hw->pcm_ops->enable_out) {
1115 hw->pcm_ops->enable_out(hw, false);
1117 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1118 sc->sw.active = 0;
1119 audio_recalc_and_notify_capture (sc->cap);
1121 continue;
1124 if (!live) {
1125 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1126 if (sw->active) {
1127 free = audio_get_free (sw);
1128 if (free > 0) {
1129 sw->callback.fn (sw->callback.opaque, free);
1133 continue;
1136 prev_rpos = hw->mix_buf->pos;
1137 played = audio_pcm_hw_run_out(hw, live);
1138 replay_audio_out(&played);
1139 if (audio_bug(__func__, hw->mix_buf->pos >= hw->mix_buf->size)) {
1140 dolog("hw->mix_buf->pos=%zu hw->mix_buf->size=%zu played=%zu\n",
1141 hw->mix_buf->pos, hw->mix_buf->size, played);
1142 hw->mix_buf->pos = 0;
1145 #ifdef DEBUG_OUT
1146 dolog("played=%zu\n", played);
1147 #endif
1149 if (played) {
1150 hw->ts_helper += played;
1151 audio_capture_mix_and_clear (hw, prev_rpos, played);
1154 cleanup_required = 0;
1155 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1156 if (!sw->active && sw->empty) {
1157 continue;
1160 if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1161 dolog("played=%zu sw->total_hw_samples_mixed=%zu\n",
1162 played, sw->total_hw_samples_mixed);
1163 played = sw->total_hw_samples_mixed;
1166 sw->total_hw_samples_mixed -= played;
1168 if (!sw->total_hw_samples_mixed) {
1169 sw->empty = 1;
1170 cleanup_required |= !sw->active && !sw->callback.fn;
1173 if (sw->active) {
1174 free = audio_get_free (sw);
1175 if (free > 0) {
1176 sw->callback.fn (sw->callback.opaque, free);
1181 if (cleanup_required) {
1182 SWVoiceOut *sw1;
1184 sw = hw->sw_head.lh_first;
1185 while (sw) {
1186 sw1 = sw->entries.le_next;
1187 if (!sw->active && !sw->callback.fn) {
1188 audio_close_out (sw);
1190 sw = sw1;
1196 static size_t audio_pcm_hw_run_in(HWVoiceIn *hw, size_t samples)
1198 size_t conv = 0;
1199 STSampleBuffer *conv_buf = hw->conv_buf;
1201 while (samples) {
1202 size_t proc;
1203 size_t size = samples << hw->info.shift;
1204 void *buf = hw->pcm_ops->get_buffer_in(hw, &size);
1206 assert((size & hw->info.align) == 0);
1207 if (size == 0) {
1208 hw->pcm_ops->put_buffer_in(hw, buf, size);
1209 break;
1212 proc = MIN(size >> hw->info.shift,
1213 conv_buf->size - conv_buf->pos);
1215 hw->conv(conv_buf->samples + conv_buf->pos, buf, proc);
1216 conv_buf->pos = (conv_buf->pos + proc) % conv_buf->size;
1218 samples -= proc;
1219 conv += proc;
1220 hw->pcm_ops->put_buffer_in(hw, buf, proc << hw->info.shift);
1223 return conv;
1226 static void audio_run_in (AudioState *s)
1228 HWVoiceIn *hw = NULL;
1230 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1231 SWVoiceIn *sw;
1232 size_t captured = 0, min;
1234 if (replay_mode != REPLAY_MODE_PLAY) {
1235 captured = audio_pcm_hw_run_in(
1236 hw, hw->conv_buf->size - audio_pcm_hw_get_live_in(hw));
1238 replay_audio_in(&captured, hw->conv_buf->samples, &hw->conv_buf->pos,
1239 hw->conv_buf->size);
1241 min = audio_pcm_hw_find_min_in (hw);
1242 hw->total_samples_captured += captured - min;
1243 hw->ts_helper += captured;
1245 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1246 sw->total_hw_samples_acquired -= min;
1248 if (sw->active) {
1249 size_t avail;
1251 avail = audio_get_avail (sw);
1252 if (avail > 0) {
1253 sw->callback.fn (sw->callback.opaque, avail);
1260 static void audio_run_capture (AudioState *s)
1262 CaptureVoiceOut *cap;
1264 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1265 size_t live, rpos, captured;
1266 HWVoiceOut *hw = &cap->hw;
1267 SWVoiceOut *sw;
1269 captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1270 rpos = hw->mix_buf->pos;
1271 while (live) {
1272 size_t left = hw->mix_buf->size - rpos;
1273 size_t to_capture = MIN(live, left);
1274 struct st_sample *src;
1275 struct capture_callback *cb;
1277 src = hw->mix_buf->samples + rpos;
1278 hw->clip (cap->buf, src, to_capture);
1279 mixeng_clear (src, to_capture);
1281 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1282 cb->ops.capture (cb->opaque, cap->buf,
1283 to_capture << hw->info.shift);
1285 rpos = (rpos + to_capture) % hw->mix_buf->size;
1286 live -= to_capture;
1288 hw->mix_buf->pos = rpos;
1290 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1291 if (!sw->active && sw->empty) {
1292 continue;
1295 if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1296 dolog("captured=%zu sw->total_hw_samples_mixed=%zu\n",
1297 captured, sw->total_hw_samples_mixed);
1298 captured = sw->total_hw_samples_mixed;
1301 sw->total_hw_samples_mixed -= captured;
1302 sw->empty = sw->total_hw_samples_mixed == 0;
1307 void audio_run(AudioState *s, const char *msg)
1309 audio_run_out(s);
1310 audio_run_in(s);
1311 audio_run_capture(s);
1313 #ifdef DEBUG_POLL
1315 static double prevtime;
1316 double currtime;
1317 struct timeval tv;
1319 if (gettimeofday (&tv, NULL)) {
1320 perror ("audio_run: gettimeofday");
1321 return;
1324 currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1325 dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1326 prevtime = currtime;
1328 #endif
1331 void *audio_generic_get_buffer_in(HWVoiceIn *hw, size_t *size)
1333 ssize_t start;
1335 if (unlikely(!hw->buf_emul)) {
1336 size_t calc_size = hw->conv_buf->size << hw->info.shift;
1337 hw->buf_emul = g_malloc(calc_size);
1338 hw->size_emul = calc_size;
1339 hw->pos_emul = hw->pending_emul = 0;
1342 while (hw->pending_emul < hw->size_emul) {
1343 size_t read_len = MIN(hw->size_emul - hw->pos_emul,
1344 hw->size_emul - hw->pending_emul);
1345 size_t read = hw->pcm_ops->read(hw, hw->buf_emul + hw->pos_emul,
1346 read_len);
1347 hw->pending_emul += read;
1348 if (read < read_len) {
1349 break;
1353 start = ((ssize_t) hw->pos_emul) - hw->pending_emul;
1354 if (start < 0) {
1355 start += hw->size_emul;
1357 assert(start >= 0 && start < hw->size_emul);
1359 *size = MIN(hw->pending_emul, hw->size_emul - start);
1360 return hw->buf_emul + start;
1363 void audio_generic_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
1365 assert(size <= hw->pending_emul);
1366 hw->pending_emul -= size;
1369 void *audio_generic_get_buffer_out(HWVoiceOut *hw, size_t *size)
1371 if (unlikely(!hw->buf_emul)) {
1372 size_t calc_size = hw->mix_buf->size << hw->info.shift;
1374 hw->buf_emul = g_malloc(calc_size);
1375 hw->size_emul = calc_size;
1376 hw->pos_emul = hw->pending_emul = 0;
1379 *size = MIN(hw->size_emul - hw->pending_emul,
1380 hw->size_emul - hw->pos_emul);
1381 return hw->buf_emul + hw->pos_emul;
1384 size_t audio_generic_put_buffer_out_nowrite(HWVoiceOut *hw, void *buf,
1385 size_t size)
1387 assert(buf == hw->buf_emul + hw->pos_emul &&
1388 size + hw->pending_emul <= hw->size_emul);
1390 hw->pending_emul += size;
1391 hw->pos_emul = (hw->pos_emul + size) % hw->size_emul;
1393 return size;
1396 size_t audio_generic_put_buffer_out(HWVoiceOut *hw, void *buf, size_t size)
1398 audio_generic_put_buffer_out_nowrite(hw, buf, size);
1400 while (hw->pending_emul) {
1401 size_t write_len, written;
1402 ssize_t start = ((ssize_t) hw->pos_emul) - hw->pending_emul;
1403 if (start < 0) {
1404 start += hw->size_emul;
1406 assert(start >= 0 && start < hw->size_emul);
1408 write_len = MIN(hw->pending_emul, hw->size_emul - start);
1410 written = hw->pcm_ops->write(hw, hw->buf_emul + start, write_len);
1411 hw->pending_emul -= written;
1413 if (written < write_len) {
1414 break;
1419 * fake we have written everything. non-written data remain in pending_emul,
1420 * so we do not have to clip them multiple times
1422 return size;
1425 size_t audio_generic_write(HWVoiceOut *hw, void *buf, size_t size)
1427 size_t dst_size, copy_size;
1428 void *dst = hw->pcm_ops->get_buffer_out(hw, &dst_size);
1429 copy_size = MIN(size, dst_size);
1431 memcpy(dst, buf, copy_size);
1432 return hw->pcm_ops->put_buffer_out(hw, buf, copy_size);
1435 size_t audio_generic_read(HWVoiceIn *hw, void *buf, size_t size)
1437 size_t dst_size, copy_size;
1438 void *dst = hw->pcm_ops->get_buffer_in(hw, &dst_size);
1439 copy_size = MIN(size, dst_size);
1441 memcpy(dst, buf, copy_size);
1442 hw->pcm_ops->put_buffer_in(hw, buf, copy_size);
1443 return copy_size;
1447 static int audio_driver_init(AudioState *s, struct audio_driver *drv,
1448 bool msg, Audiodev *dev)
1450 s->drv_opaque = drv->init(dev);
1452 if (s->drv_opaque) {
1453 if (!drv->pcm_ops->get_buffer_in) {
1454 drv->pcm_ops->get_buffer_in = audio_generic_get_buffer_in;
1455 drv->pcm_ops->put_buffer_in = audio_generic_put_buffer_in;
1457 if (!drv->pcm_ops->get_buffer_out) {
1458 drv->pcm_ops->get_buffer_out = audio_generic_get_buffer_out;
1459 drv->pcm_ops->put_buffer_out = audio_generic_put_buffer_out;
1462 audio_init_nb_voices_out(s, drv);
1463 audio_init_nb_voices_in(s, drv);
1464 s->drv = drv;
1465 return 0;
1467 else {
1468 if (msg) {
1469 dolog("Could not init `%s' audio driver\n", drv->name);
1471 return -1;
1475 static void audio_vm_change_state_handler (void *opaque, int running,
1476 RunState state)
1478 AudioState *s = opaque;
1479 HWVoiceOut *hwo = NULL;
1480 HWVoiceIn *hwi = NULL;
1482 s->vm_running = running;
1483 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
1484 if (hwo->pcm_ops->enable_out) {
1485 hwo->pcm_ops->enable_out(hwo, running);
1489 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
1490 if (hwi->pcm_ops->enable_in) {
1491 hwi->pcm_ops->enable_in(hwi, running);
1494 audio_reset_timer (s);
1497 static bool is_cleaning_up;
1499 bool audio_is_cleaning_up(void)
1501 return is_cleaning_up;
1504 static void free_audio_state(AudioState *s)
1506 HWVoiceOut *hwo, *hwon;
1507 HWVoiceIn *hwi, *hwin;
1509 QLIST_FOREACH_SAFE(hwo, &s->hw_head_out, entries, hwon) {
1510 SWVoiceCap *sc;
1512 if (hwo->enabled && hwo->pcm_ops->enable_out) {
1513 hwo->pcm_ops->enable_out(hwo, false);
1515 hwo->pcm_ops->fini_out (hwo);
1517 for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1518 CaptureVoiceOut *cap = sc->cap;
1519 struct capture_callback *cb;
1521 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1522 cb->ops.destroy (cb->opaque);
1525 QLIST_REMOVE(hwo, entries);
1528 QLIST_FOREACH_SAFE(hwi, &s->hw_head_in, entries, hwin) {
1529 if (hwi->enabled && hwi->pcm_ops->enable_in) {
1530 hwi->pcm_ops->enable_in(hwi, false);
1532 hwi->pcm_ops->fini_in (hwi);
1533 QLIST_REMOVE(hwi, entries);
1536 if (s->drv) {
1537 s->drv->fini (s->drv_opaque);
1538 s->drv = NULL;
1541 if (s->dev) {
1542 qapi_free_Audiodev(s->dev);
1543 s->dev = NULL;
1546 if (s->ts) {
1547 timer_free(s->ts);
1548 s->ts = NULL;
1551 g_free(s);
1554 void audio_cleanup(void)
1556 is_cleaning_up = true;
1557 while (!QTAILQ_EMPTY(&audio_states)) {
1558 AudioState *s = QTAILQ_FIRST(&audio_states);
1559 QTAILQ_REMOVE(&audio_states, s, list);
1560 free_audio_state(s);
1564 static const VMStateDescription vmstate_audio = {
1565 .name = "audio",
1566 .version_id = 1,
1567 .minimum_version_id = 1,
1568 .fields = (VMStateField[]) {
1569 VMSTATE_END_OF_LIST()
1573 static void audio_validate_opts(Audiodev *dev, Error **errp);
1575 static AudiodevListEntry *audiodev_find(
1576 AudiodevListHead *head, const char *drvname)
1578 AudiodevListEntry *e;
1579 QSIMPLEQ_FOREACH(e, head, next) {
1580 if (strcmp(AudiodevDriver_str(e->dev->driver), drvname) == 0) {
1581 return e;
1585 return NULL;
1589 * if we have dev, this function was called because of an -audiodev argument =>
1590 * initialize a new state with it
1591 * if dev == NULL => legacy implicit initialization, return the already created
1592 * state or create a new one
1594 static AudioState *audio_init(Audiodev *dev, const char *name)
1596 static bool atexit_registered;
1597 size_t i;
1598 int done = 0;
1599 const char *drvname = NULL;
1600 VMChangeStateEntry *e;
1601 AudioState *s;
1602 struct audio_driver *driver;
1603 /* silence gcc warning about uninitialized variable */
1604 AudiodevListHead head = QSIMPLEQ_HEAD_INITIALIZER(head);
1606 if (dev) {
1607 /* -audiodev option */
1608 legacy_config = false;
1609 drvname = AudiodevDriver_str(dev->driver);
1610 } else if (!QTAILQ_EMPTY(&audio_states)) {
1611 if (!legacy_config) {
1612 dolog("Device %s: audiodev default parameter is deprecated, please "
1613 "specify audiodev=%s\n", name,
1614 QTAILQ_FIRST(&audio_states)->dev->id);
1616 return QTAILQ_FIRST(&audio_states);
1617 } else {
1618 /* legacy implicit initialization */
1619 head = audio_handle_legacy_opts();
1621 * In case of legacy initialization, all Audiodevs in the list will have
1622 * the same configuration (except the driver), so it does't matter which
1623 * one we chose. We need an Audiodev to set up AudioState before we can
1624 * init a driver. Also note that dev at this point is still in the
1625 * list.
1627 dev = QSIMPLEQ_FIRST(&head)->dev;
1628 audio_validate_opts(dev, &error_abort);
1631 s = g_malloc0(sizeof(AudioState));
1632 s->dev = dev;
1634 QLIST_INIT (&s->hw_head_out);
1635 QLIST_INIT (&s->hw_head_in);
1636 QLIST_INIT (&s->cap_head);
1637 if (!atexit_registered) {
1638 atexit(audio_cleanup);
1639 atexit_registered = true;
1641 QTAILQ_INSERT_TAIL(&audio_states, s, list);
1643 s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1645 s->nb_hw_voices_out = audio_get_pdo_out(dev)->voices;
1646 s->nb_hw_voices_in = audio_get_pdo_in(dev)->voices;
1648 if (s->nb_hw_voices_out <= 0) {
1649 dolog ("Bogus number of playback voices %d, setting to 1\n",
1650 s->nb_hw_voices_out);
1651 s->nb_hw_voices_out = 1;
1654 if (s->nb_hw_voices_in <= 0) {
1655 dolog ("Bogus number of capture voices %d, setting to 0\n",
1656 s->nb_hw_voices_in);
1657 s->nb_hw_voices_in = 0;
1660 if (drvname) {
1661 driver = audio_driver_lookup(drvname);
1662 if (driver) {
1663 done = !audio_driver_init(s, driver, true, dev);
1664 } else {
1665 dolog ("Unknown audio driver `%s'\n", drvname);
1667 } else {
1668 for (i = 0; audio_prio_list[i]; i++) {
1669 AudiodevListEntry *e = audiodev_find(&head, audio_prio_list[i]);
1670 driver = audio_driver_lookup(audio_prio_list[i]);
1672 if (e && driver) {
1673 s->dev = dev = e->dev;
1674 audio_validate_opts(dev, &error_abort);
1675 done = !audio_driver_init(s, driver, false, dev);
1676 if (done) {
1677 e->dev = NULL;
1678 break;
1683 audio_free_audiodev_list(&head);
1685 if (!done) {
1686 driver = audio_driver_lookup("none");
1687 done = !audio_driver_init(s, driver, false, dev);
1688 assert(done);
1689 dolog("warning: Using timer based audio emulation\n");
1692 if (dev->timer_period <= 0) {
1693 s->period_ticks = 1;
1694 } else {
1695 s->period_ticks = dev->timer_period * SCALE_US;
1698 e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1699 if (!e) {
1700 dolog ("warning: Could not register change state handler\n"
1701 "(Audio can continue looping even after stopping the VM)\n");
1704 QLIST_INIT (&s->card_head);
1705 vmstate_register (NULL, 0, &vmstate_audio, s);
1706 return s;
1709 void audio_free_audiodev_list(AudiodevListHead *head)
1711 AudiodevListEntry *e;
1712 while ((e = QSIMPLEQ_FIRST(head))) {
1713 QSIMPLEQ_REMOVE_HEAD(head, next);
1714 qapi_free_Audiodev(e->dev);
1715 g_free(e);
1719 void AUD_register_card (const char *name, QEMUSoundCard *card)
1721 if (!card->state) {
1722 card->state = audio_init(NULL, name);
1725 card->name = g_strdup (name);
1726 memset (&card->entries, 0, sizeof (card->entries));
1727 QLIST_INSERT_HEAD(&card->state->card_head, card, entries);
1730 void AUD_remove_card (QEMUSoundCard *card)
1732 QLIST_REMOVE (card, entries);
1733 g_free (card->name);
1737 CaptureVoiceOut *AUD_add_capture(
1738 AudioState *s,
1739 struct audsettings *as,
1740 struct audio_capture_ops *ops,
1741 void *cb_opaque
1744 CaptureVoiceOut *cap;
1745 struct capture_callback *cb;
1747 if (!s) {
1748 if (!legacy_config) {
1749 dolog("Capturing without setting an audiodev is deprecated\n");
1751 s = audio_init(NULL, NULL);
1754 if (audio_validate_settings (as)) {
1755 dolog ("Invalid settings were passed when trying to add capture\n");
1756 audio_print_settings (as);
1757 return NULL;
1760 cb = g_malloc0(sizeof(*cb));
1761 cb->ops = *ops;
1762 cb->opaque = cb_opaque;
1764 cap = audio_pcm_capture_find_specific(s, as);
1765 if (cap) {
1766 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1767 return cap;
1769 else {
1770 HWVoiceOut *hw;
1771 CaptureVoiceOut *cap;
1773 cap = g_malloc0(sizeof(*cap));
1775 hw = &cap->hw;
1776 hw->s = s;
1777 QLIST_INIT (&hw->sw_head);
1778 QLIST_INIT (&cap->cb_head);
1780 /* XXX find a more elegant way */
1781 hw->samples = 4096 * 4;
1782 audio_pcm_hw_alloc_resources_out(hw);
1784 audio_pcm_init_info (&hw->info, as);
1786 cap->buf = g_malloc0_n(hw->mix_buf->size, 1 << hw->info.shift);
1788 hw->clip = mixeng_clip
1789 [hw->info.nchannels == 2]
1790 [hw->info.sign]
1791 [hw->info.swap_endianness]
1792 [audio_bits_to_index (hw->info.bits)];
1794 QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1795 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1797 QLIST_FOREACH(hw, &s->hw_head_out, entries) {
1798 audio_attach_capture (hw);
1800 return cap;
1804 void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1806 struct capture_callback *cb;
1808 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1809 if (cb->opaque == cb_opaque) {
1810 cb->ops.destroy (cb_opaque);
1811 QLIST_REMOVE (cb, entries);
1812 g_free (cb);
1814 if (!cap->cb_head.lh_first) {
1815 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
1817 while (sw) {
1818 SWVoiceCap *sc = (SWVoiceCap *) sw;
1819 #ifdef DEBUG_CAPTURE
1820 dolog ("freeing %s\n", sw->name);
1821 #endif
1823 sw1 = sw->entries.le_next;
1824 if (sw->rate) {
1825 st_rate_stop (sw->rate);
1826 sw->rate = NULL;
1828 QLIST_REMOVE (sw, entries);
1829 QLIST_REMOVE (sc, entries);
1830 g_free (sc);
1831 sw = sw1;
1833 QLIST_REMOVE (cap, entries);
1834 g_free (cap->hw.mix_buf);
1835 g_free (cap->buf);
1836 g_free (cap);
1838 return;
1843 void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
1845 if (sw) {
1846 HWVoiceOut *hw = sw->hw;
1848 sw->vol.mute = mute;
1849 sw->vol.l = nominal_volume.l * lvol / 255;
1850 sw->vol.r = nominal_volume.r * rvol / 255;
1852 if (hw->pcm_ops->volume_out) {
1853 hw->pcm_ops->volume_out(hw, &sw->vol);
1858 void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
1860 if (sw) {
1861 HWVoiceIn *hw = sw->hw;
1863 sw->vol.mute = mute;
1864 sw->vol.l = nominal_volume.l * lvol / 255;
1865 sw->vol.r = nominal_volume.r * rvol / 255;
1867 if (hw->pcm_ops->volume_in) {
1868 hw->pcm_ops->volume_in(hw, &sw->vol);
1873 void audio_create_pdos(Audiodev *dev)
1875 switch (dev->driver) {
1876 #define CASE(DRIVER, driver, pdo_name) \
1877 case AUDIODEV_DRIVER_##DRIVER: \
1878 if (!dev->u.driver.has_in) { \
1879 dev->u.driver.in = g_malloc0( \
1880 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
1881 dev->u.driver.has_in = true; \
1883 if (!dev->u.driver.has_out) { \
1884 dev->u.driver.out = g_malloc0( \
1885 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
1886 dev->u.driver.has_out = true; \
1888 break
1890 CASE(NONE, none, );
1891 CASE(ALSA, alsa, Alsa);
1892 CASE(COREAUDIO, coreaudio, Coreaudio);
1893 CASE(DSOUND, dsound, );
1894 CASE(OSS, oss, Oss);
1895 CASE(PA, pa, Pa);
1896 CASE(SDL, sdl, );
1897 CASE(SPICE, spice, );
1898 CASE(WAV, wav, );
1900 case AUDIODEV_DRIVER__MAX:
1901 abort();
1905 static void audio_validate_per_direction_opts(
1906 AudiodevPerDirectionOptions *pdo, Error **errp)
1908 if (!pdo->has_fixed_settings) {
1909 pdo->has_fixed_settings = true;
1910 pdo->fixed_settings = true;
1912 if (!pdo->fixed_settings &&
1913 (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
1914 error_setg(errp,
1915 "You can't use frequency, channels or format with fixed-settings=off");
1916 return;
1919 if (!pdo->has_frequency) {
1920 pdo->has_frequency = true;
1921 pdo->frequency = 44100;
1923 if (!pdo->has_channels) {
1924 pdo->has_channels = true;
1925 pdo->channels = 2;
1927 if (!pdo->has_voices) {
1928 pdo->has_voices = true;
1929 pdo->voices = 1;
1931 if (!pdo->has_format) {
1932 pdo->has_format = true;
1933 pdo->format = AUDIO_FORMAT_S16;
1937 static void audio_validate_opts(Audiodev *dev, Error **errp)
1939 Error *err = NULL;
1941 audio_create_pdos(dev);
1943 audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
1944 if (err) {
1945 error_propagate(errp, err);
1946 return;
1949 audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
1950 if (err) {
1951 error_propagate(errp, err);
1952 return;
1955 if (!dev->has_timer_period) {
1956 dev->has_timer_period = true;
1957 dev->timer_period = 10000; /* 100Hz -> 10ms */
1961 void audio_parse_option(const char *opt)
1963 AudiodevListEntry *e;
1964 Audiodev *dev = NULL;
1966 Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
1967 visit_type_Audiodev(v, NULL, &dev, &error_fatal);
1968 visit_free(v);
1970 audio_validate_opts(dev, &error_fatal);
1972 e = g_malloc0(sizeof(AudiodevListEntry));
1973 e->dev = dev;
1974 QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
1977 void audio_init_audiodevs(void)
1979 AudiodevListEntry *e;
1981 QSIMPLEQ_FOREACH(e, &audiodevs, next) {
1982 audio_init(e->dev, NULL);
1986 audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
1988 return (audsettings) {
1989 .freq = pdo->frequency,
1990 .nchannels = pdo->channels,
1991 .fmt = pdo->format,
1992 .endianness = AUDIO_HOST_ENDIANNESS,
1996 int audioformat_bytes_per_sample(AudioFormat fmt)
1998 switch (fmt) {
1999 case AUDIO_FORMAT_U8:
2000 case AUDIO_FORMAT_S8:
2001 return 1;
2003 case AUDIO_FORMAT_U16:
2004 case AUDIO_FORMAT_S16:
2005 return 2;
2007 case AUDIO_FORMAT_U32:
2008 case AUDIO_FORMAT_S32:
2009 return 4;
2011 case AUDIO_FORMAT__MAX:
2014 abort();
2018 /* frames = freq * usec / 1e6 */
2019 int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
2020 audsettings *as, int def_usecs)
2022 uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
2023 return (as->freq * usecs + 500000) / 1000000;
2026 /* samples = channels * frames = channels * freq * usec / 1e6 */
2027 int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
2028 audsettings *as, int def_usecs)
2030 return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
2034 * bytes = bytes_per_sample * samples =
2035 * bytes_per_sample * channels * freq * usec / 1e6
2037 int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
2038 audsettings *as, int def_usecs)
2040 return audio_buffer_samples(pdo, as, def_usecs) *
2041 audioformat_bytes_per_sample(as->fmt);
2044 AudioState *audio_state_by_name(const char *name)
2046 AudioState *s;
2047 QTAILQ_FOREACH(s, &audio_states, list) {
2048 assert(s->dev);
2049 if (strcmp(name, s->dev->id) == 0) {
2050 return s;
2053 return NULL;
2056 const char *audio_get_id(QEMUSoundCard *card)
2058 if (card->state) {
2059 assert(card->state->dev);
2060 return card->state->dev->id;
2061 } else {
2062 return "";
2066 void audio_rate_start(RateCtl *rate)
2068 memset(rate, 0, sizeof(RateCtl));
2069 rate->start_ticks = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2072 size_t audio_rate_get_bytes(struct audio_pcm_info *info, RateCtl *rate,
2073 size_t bytes_avail)
2075 int64_t now;
2076 int64_t ticks;
2077 int64_t bytes;
2078 int64_t samples;
2079 size_t ret;
2081 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2082 ticks = now - rate->start_ticks;
2083 bytes = muldiv64(ticks, info->bytes_per_second, NANOSECONDS_PER_SECOND);
2084 samples = (bytes - rate->bytes_sent) >> info->shift;
2085 if (samples < 0 || samples > 65536) {
2086 AUD_log(NULL, "Resetting rate control (%" PRId64 " samples)\n", samples);
2087 audio_rate_start(rate);
2088 samples = 0;
2091 ret = MIN(samples << info->shift, bytes_avail);
2092 rate->bytes_sent += ret;
2093 return ret;