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
24 #include "qemu/osdep.h"
27 #include "monitor/monitor.h"
28 #include "qemu/timer.h"
29 #include "sysemu/sysemu.h"
30 #include "qemu/cutils.h"
31 #include "sysemu/replay.h"
34 #define AUDIO_CAP "audio"
35 #include "audio_int.h"
37 /* #define DEBUG_LIVE */
38 /* #define DEBUG_OUT */
39 /* #define DEBUG_CAPTURE */
40 /* #define DEBUG_POLL */
42 #define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
45 /* Order of CONFIG_AUDIO_DRIVERS is import.
46 The 1st one is the one used by default, that is the reason
47 that we generate the list.
49 static const char *audio_prio_list[] = {
56 static QLIST_HEAD(, audio_driver) audio_drivers;
58 void audio_driver_register(audio_driver *drv)
60 QLIST_INSERT_HEAD(&audio_drivers, drv, next);
63 audio_driver *audio_driver_lookup(const char *name)
65 struct audio_driver *d;
67 QLIST_FOREACH(d, &audio_drivers, next) {
68 if (strcmp(name, d->name) == 0) {
73 audio_module_load_one(name);
74 QLIST_FOREACH(d, &audio_drivers, next) {
75 if (strcmp(name, d->name) == 0) {
83 static void audio_module_load_all(void)
87 for (i = 0; i < ARRAY_SIZE(audio_prio_list); i++) {
88 audio_driver_lookup(audio_prio_list[i]);
92 struct fixed_settings {
96 struct audsettings settings;
100 struct fixed_settings fixed_out;
101 struct fixed_settings fixed_in;
109 .fixed_out = { /* DAC fixed settings */
117 .endianness = AUDIO_HOST_ENDIANNESS,
121 .fixed_in = { /* ADC fixed settings */
129 .endianness = AUDIO_HOST_ENDIANNESS,
133 .period = { .hertz = 100 },
138 static AudioState glob_audio_state;
140 const struct mixeng_volume nominal_volume = {
151 #ifdef AUDIO_IS_FLAWLESS_AND_NO_CHECKS_ARE_REQURIED
154 static void audio_print_options (const char *prefix,
155 struct audio_option *opt);
157 int audio_bug (const char *funcname, int cond)
162 AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
164 struct audio_driver *d;
167 AUD_log (NULL, "Save all your work and restart without audio\n");
169 AUD_log (NULL, "I am sorry\n");
170 d = glob_audio_state.drv;
172 audio_print_options (d->name, d->options);
175 AUD_log (NULL, "Context:\n");
177 #if defined AUDIO_BREAKPOINT_ON_BUG
178 # if defined HOST_I386
179 # if defined __GNUC__
181 # elif defined _MSC_VER
196 static inline int audio_bits_to_index (int bits)
209 audio_bug ("bits_to_index", 1);
210 AUD_log (NULL, "invalid bits %d\n", bits);
215 void *audio_calloc (const char *funcname, int nmemb, size_t size)
221 cond = !nmemb || !size;
225 if (audio_bug ("audio_calloc", cond)) {
226 AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
228 AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
232 return g_malloc0 (len);
235 static char *audio_alloc_prefix (const char *s)
237 const char qemu_prefix[] = "QEMU_";
246 r = g_malloc (len + sizeof (qemu_prefix));
248 u = r + sizeof (qemu_prefix) - 1;
250 pstrcpy (r, len + sizeof (qemu_prefix), qemu_prefix);
251 pstrcat (r, len + sizeof (qemu_prefix), s);
253 for (i = 0; i < len; ++i) {
254 u[i] = qemu_toupper(u[i]);
260 static const char *audio_audfmt_to_string (audfmt_e fmt)
282 dolog ("Bogus audfmt %d returning S16\n", fmt);
286 static audfmt_e audio_string_to_audfmt (const char *s, audfmt_e defval,
289 if (!strcasecmp (s, "u8")) {
293 else if (!strcasecmp (s, "u16")) {
297 else if (!strcasecmp (s, "u32")) {
301 else if (!strcasecmp (s, "s8")) {
305 else if (!strcasecmp (s, "s16")) {
309 else if (!strcasecmp (s, "s32")) {
314 dolog ("Bogus audio format `%s' using %s\n",
315 s, audio_audfmt_to_string (defval));
321 static audfmt_e audio_get_conf_fmt (const char *envname,
325 const char *var = getenv (envname);
330 return audio_string_to_audfmt (var, defval, defaultp);
333 static int audio_get_conf_int (const char *key, int defval, int *defaultp)
338 strval = getenv (key);
339 if (strval && !qemu_strtoi(strval, NULL, 10, &val)) {
349 static const char *audio_get_conf_str (const char *key,
353 const char *val = getenv (key);
364 void AUD_vlog (const char *cap, const char *fmt, va_list ap)
367 fprintf(stderr, "%s: ", cap);
370 vfprintf(stderr, fmt, ap);
373 void AUD_log (const char *cap, const char *fmt, ...)
378 AUD_vlog (cap, fmt, ap);
382 static void audio_print_options (const char *prefix,
383 struct audio_option *opt)
388 dolog ("No prefix specified\n");
393 dolog ("No options\n");
397 uprefix = audio_alloc_prefix (prefix);
399 for (; opt->name; opt++) {
400 const char *state = "default";
401 printf (" %s_%s: ", uprefix, opt->name);
403 if (opt->overriddenp && *opt->overriddenp) {
410 int *intp = opt->valp;
411 printf ("boolean, %s = %d\n", state, *intp ? 1 : 0);
417 int *intp = opt->valp;
418 printf ("integer, %s = %d\n", state, *intp);
424 audfmt_e *fmtp = opt->valp;
426 "format, %s = %s, (one of: U8 S8 U16 S16 U32 S32)\n",
428 audio_audfmt_to_string (*fmtp)
435 const char **strp = opt->valp;
436 printf ("string, %s = %s\n",
438 *strp ? *strp : "(not set)");
444 dolog ("Bad value tag for option %s_%s %d\n",
445 uprefix, opt->name, opt->tag);
448 printf (" %s\n", opt->descr);
454 static void audio_process_options (const char *prefix,
455 struct audio_option *opt)
459 if (audio_bug(__func__, !prefix)) {
460 dolog ("prefix = NULL\n");
464 if (audio_bug(__func__, !opt)) {
465 dolog ("opt = NULL\n");
469 prefix_upper = g_utf8_strup(prefix, -1);
471 for (; opt->name; opt++) {
476 dolog ("Option value pointer for `%s' is not set\n",
481 optname = g_strdup_printf("QEMU_%s_%s", prefix_upper, opt->name);
488 int *intp = opt->valp;
489 *intp = audio_get_conf_int (optname, *intp, &def);
495 audfmt_e *fmtp = opt->valp;
496 *fmtp = audio_get_conf_fmt (optname, *fmtp, &def);
502 const char **strp = opt->valp;
503 *strp = audio_get_conf_str (optname, *strp, &def);
508 dolog ("Bad value tag for option `%s' - %d\n",
513 if (!opt->overriddenp) {
514 opt->overriddenp = &opt->overridden;
516 *opt->overriddenp = !def;
519 g_free(prefix_upper);
522 static void audio_print_settings (struct audsettings *as)
524 dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
528 AUD_log (NULL, "S8");
531 AUD_log (NULL, "U8");
534 AUD_log (NULL, "S16");
537 AUD_log (NULL, "U16");
540 AUD_log (NULL, "S32");
543 AUD_log (NULL, "U32");
546 AUD_log (NULL, "invalid(%d)", as->fmt);
550 AUD_log (NULL, " endianness=");
551 switch (as->endianness) {
553 AUD_log (NULL, "little");
556 AUD_log (NULL, "big");
559 AUD_log (NULL, "invalid");
562 AUD_log (NULL, "\n");
565 static int audio_validate_settings (struct audsettings *as)
569 invalid = as->nchannels != 1 && as->nchannels != 2;
570 invalid |= as->endianness != 0 && as->endianness != 1;
585 invalid |= as->freq <= 0;
586 return invalid ? -1 : 0;
589 static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
591 int bits = 8, sign = 0;
614 return info->freq == as->freq
615 && info->nchannels == as->nchannels
616 && info->sign == sign
617 && info->bits == bits
618 && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
621 void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
623 int bits = 8, sign = 0, shift = 0;
646 info->freq = as->freq;
649 info->nchannels = as->nchannels;
650 info->shift = (as->nchannels == 2) + shift;
651 info->align = (1 << info->shift) - 1;
652 info->bytes_per_second = info->freq << info->shift;
653 info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
656 void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
663 memset (buf, 0x00, len << info->shift);
666 switch (info->bits) {
668 memset (buf, 0x80, len << info->shift);
675 int shift = info->nchannels - 1;
678 if (info->swap_endianness) {
682 for (i = 0; i < len << shift; i++) {
692 int shift = info->nchannels - 1;
693 int32_t s = INT32_MAX;
695 if (info->swap_endianness) {
699 for (i = 0; i < len << shift; i++) {
706 AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
716 static void noop_conv (struct st_sample *dst, const void *src, int samples)
723 static CaptureVoiceOut *audio_pcm_capture_find_specific (
724 struct audsettings *as
727 CaptureVoiceOut *cap;
728 AudioState *s = &glob_audio_state;
730 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
731 if (audio_pcm_info_eq (&cap->hw.info, as)) {
738 static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
740 struct capture_callback *cb;
743 dolog ("notification %d sent\n", cmd);
745 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
746 cb->ops.notify (cb->opaque, cmd);
750 static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
752 if (cap->hw.enabled != enabled) {
753 audcnotification_e cmd;
754 cap->hw.enabled = enabled;
755 cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
756 audio_notify_capture (cap, cmd);
760 static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
762 HWVoiceOut *hw = &cap->hw;
766 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
772 audio_capture_maybe_changed (cap, enabled);
775 static void audio_detach_capture (HWVoiceOut *hw)
777 SWVoiceCap *sc = hw->cap_head.lh_first;
780 SWVoiceCap *sc1 = sc->entries.le_next;
781 SWVoiceOut *sw = &sc->sw;
782 CaptureVoiceOut *cap = sc->cap;
783 int was_active = sw->active;
786 st_rate_stop (sw->rate);
790 QLIST_REMOVE (sw, entries);
791 QLIST_REMOVE (sc, entries);
794 /* We have removed soft voice from the capture:
795 this might have changed the overall status of the capture
796 since this might have been the only active voice */
797 audio_recalc_and_notify_capture (cap);
803 static int audio_attach_capture (HWVoiceOut *hw)
805 AudioState *s = &glob_audio_state;
806 CaptureVoiceOut *cap;
808 audio_detach_capture (hw);
809 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
812 HWVoiceOut *hw_cap = &cap->hw;
814 sc = g_malloc0(sizeof(*sc));
821 sw->active = hw->enabled;
822 sw->conv = noop_conv;
823 sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
824 sw->vol = nominal_volume;
825 sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
827 dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
831 QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
832 QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
834 sw->name = g_strdup_printf ("for %p %d,%d,%d",
835 hw, sw->info.freq, sw->info.bits,
837 dolog ("Added %s active = %d\n", sw->name, sw->active);
840 audio_capture_maybe_changed (cap, 1);
847 * Hard voice (capture)
849 static int audio_pcm_hw_find_min_in (HWVoiceIn *hw)
852 int m = hw->total_samples_captured;
854 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
856 m = audio_MIN (m, sw->total_hw_samples_acquired);
862 int audio_pcm_hw_get_live_in (HWVoiceIn *hw)
864 int live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
865 if (audio_bug(__func__, live < 0 || live > hw->samples)) {
866 dolog ("live=%d hw->samples=%d\n", live, hw->samples);
872 int audio_pcm_hw_clip_out (HWVoiceOut *hw, void *pcm_buf,
873 int live, int pending)
875 int left = hw->samples - pending;
876 int len = audio_MIN (left, live);
880 struct st_sample *src = hw->mix_buf + hw->rpos;
881 uint8_t *dst = advance (pcm_buf, hw->rpos << hw->info.shift);
882 int samples_till_end_of_buf = hw->samples - hw->rpos;
883 int samples_to_clip = audio_MIN (len, samples_till_end_of_buf);
885 hw->clip (dst, src, samples_to_clip);
887 hw->rpos = (hw->rpos + samples_to_clip) % hw->samples;
888 len -= samples_to_clip;
889 clipped += samples_to_clip;
895 * Soft voice (capture)
897 static int audio_pcm_sw_get_rpos_in (SWVoiceIn *sw)
899 HWVoiceIn *hw = sw->hw;
900 int live = hw->total_samples_captured - sw->total_hw_samples_acquired;
903 if (audio_bug(__func__, live < 0 || live > hw->samples)) {
904 dolog ("live=%d hw->samples=%d\n", live, hw->samples);
908 rpos = hw->wpos - live;
913 return hw->samples + rpos;
917 int audio_pcm_sw_read (SWVoiceIn *sw, void *buf, int size)
919 HWVoiceIn *hw = sw->hw;
920 int samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
921 struct st_sample *src, *dst = sw->buf;
923 rpos = audio_pcm_sw_get_rpos_in (sw) % hw->samples;
925 live = hw->total_samples_captured - sw->total_hw_samples_acquired;
926 if (audio_bug(__func__, live < 0 || live > hw->samples)) {
927 dolog ("live_in=%d hw->samples=%d\n", live, hw->samples);
931 samples = size >> sw->info.shift;
936 swlim = (live * sw->ratio) >> 32;
937 swlim = audio_MIN (swlim, samples);
940 src = hw->conv_buf + rpos;
941 isamp = hw->wpos - rpos;
944 isamp = hw->samples - rpos;
952 if (audio_bug(__func__, osamp < 0)) {
953 dolog ("osamp=%d\n", osamp);
957 st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
959 rpos = (rpos + isamp) % hw->samples;
965 if (!(hw->ctl_caps & VOICE_VOLUME_CAP)) {
966 mixeng_volume (sw->buf, ret, &sw->vol);
969 sw->clip (buf, sw->buf, ret);
970 sw->total_hw_samples_acquired += total;
971 return ret << sw->info.shift;
975 * Hard voice (playback)
977 static int audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
983 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
984 if (sw->active || !sw->empty) {
985 m = audio_MIN (m, sw->total_hw_samples_mixed);
994 static int audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
999 smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
1001 *nb_live = nb_live1;
1007 if (audio_bug(__func__, live < 0 || live > hw->samples)) {
1008 dolog ("live=%d hw->samples=%d\n", live, hw->samples);
1017 * Soft voice (playback)
1019 int audio_pcm_sw_write (SWVoiceOut *sw, void *buf, int size)
1021 int hwsamples, samples, isamp, osamp, wpos, live, dead, left, swlim, blck;
1022 int ret = 0, pos = 0, total = 0;
1028 hwsamples = sw->hw->samples;
1030 live = sw->total_hw_samples_mixed;
1031 if (audio_bug(__func__, live < 0 || live > hwsamples)) {
1032 dolog ("live=%d hw->samples=%d\n", live, hwsamples);
1036 if (live == hwsamples) {
1038 dolog ("%s is full %d\n", sw->name, live);
1043 wpos = (sw->hw->rpos + live) % hwsamples;
1044 samples = size >> sw->info.shift;
1046 dead = hwsamples - live;
1047 swlim = ((int64_t) dead << 32) / sw->ratio;
1048 swlim = audio_MIN (swlim, samples);
1050 sw->conv (sw->buf, buf, swlim);
1052 if (!(sw->hw->ctl_caps & VOICE_VOLUME_CAP)) {
1053 mixeng_volume (sw->buf, swlim, &sw->vol);
1058 dead = hwsamples - live;
1059 left = hwsamples - wpos;
1060 blck = audio_MIN (dead, left);
1069 sw->hw->mix_buf + wpos,
1077 wpos = (wpos + osamp) % hwsamples;
1081 sw->total_hw_samples_mixed += total;
1082 sw->empty = sw->total_hw_samples_mixed == 0;
1086 "%s: write size %d ret %d total sw %d\n",
1088 size >> sw->info.shift,
1090 sw->total_hw_samples_mixed
1094 return ret << sw->info.shift;
1098 static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
1100 dolog ("%s: bits %d, sign %d, freq %d, nchan %d\n",
1101 cap, info->bits, info->sign, info->freq, info->nchannels);
1106 #include "audio_template.h"
1108 #include "audio_template.h"
1114 static bool audio_timer_running;
1115 static uint64_t audio_timer_last;
1117 static int audio_is_timer_needed (void)
1119 HWVoiceIn *hwi = NULL;
1120 HWVoiceOut *hwo = NULL;
1122 while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
1123 if (!hwo->poll_mode) return 1;
1125 while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
1126 if (!hwi->poll_mode) return 1;
1131 static void audio_reset_timer (AudioState *s)
1133 if (audio_is_timer_needed ()) {
1134 timer_mod_anticipate_ns(s->ts,
1135 qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + conf.period.ticks);
1136 if (!audio_timer_running) {
1137 audio_timer_running = true;
1138 audio_timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1139 trace_audio_timer_start(conf.period.ticks / SCALE_MS);
1143 if (audio_timer_running) {
1144 audio_timer_running = false;
1145 trace_audio_timer_stop();
1150 static void audio_timer (void *opaque)
1154 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1155 diff = now - audio_timer_last;
1156 if (diff > conf.period.ticks * 3 / 2) {
1157 trace_audio_timer_delayed(diff / SCALE_MS);
1159 audio_timer_last = now;
1161 audio_run ("timer");
1162 audio_reset_timer (opaque);
1168 int AUD_write (SWVoiceOut *sw, void *buf, int size)
1171 /* XXX: Consider options */
1175 if (!sw->hw->enabled) {
1176 dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
1180 return sw->hw->pcm_ops->write(sw, buf, size);
1183 int AUD_read (SWVoiceIn *sw, void *buf, int size)
1186 /* XXX: Consider options */
1190 if (!sw->hw->enabled) {
1191 dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
1195 return sw->hw->pcm_ops->read(sw, buf, size);
1198 int AUD_get_buffer_size_out (SWVoiceOut *sw)
1200 return sw->hw->samples << sw->hw->info.shift;
1203 void AUD_set_active_out (SWVoiceOut *sw, int on)
1212 if (sw->active != on) {
1213 AudioState *s = &glob_audio_state;
1214 SWVoiceOut *temp_sw;
1218 hw->pending_disable = 0;
1221 if (s->vm_running) {
1222 hw->pcm_ops->ctl_out (hw, VOICE_ENABLE, conf.try_poll_out);
1223 audio_reset_timer (s);
1231 for (temp_sw = hw->sw_head.lh_first; temp_sw;
1232 temp_sw = temp_sw->entries.le_next) {
1233 nb_active += temp_sw->active != 0;
1236 hw->pending_disable = nb_active == 1;
1240 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1241 sc->sw.active = hw->enabled;
1243 audio_capture_maybe_changed (sc->cap, 1);
1250 void AUD_set_active_in (SWVoiceIn *sw, int on)
1259 if (sw->active != on) {
1260 AudioState *s = &glob_audio_state;
1266 if (s->vm_running) {
1267 hw->pcm_ops->ctl_in (hw, VOICE_ENABLE, conf.try_poll_in);
1268 audio_reset_timer (s);
1271 sw->total_hw_samples_acquired = hw->total_samples_captured;
1277 for (temp_sw = hw->sw_head.lh_first; temp_sw;
1278 temp_sw = temp_sw->entries.le_next) {
1279 nb_active += temp_sw->active != 0;
1282 if (nb_active == 1) {
1284 hw->pcm_ops->ctl_in (hw, VOICE_DISABLE);
1292 static int audio_get_avail (SWVoiceIn *sw)
1300 live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
1301 if (audio_bug(__func__, live < 0 || live > sw->hw->samples)) {
1302 dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples);
1307 "%s: get_avail live %d ret %" PRId64 "\n",
1309 live, (((int64_t) live << 32) / sw->ratio) << sw->info.shift
1312 return (((int64_t) live << 32) / sw->ratio) << sw->info.shift;
1315 static int audio_get_free (SWVoiceOut *sw)
1323 live = sw->total_hw_samples_mixed;
1325 if (audio_bug(__func__, live < 0 || live > sw->hw->samples)) {
1326 dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples);
1330 dead = sw->hw->samples - live;
1333 dolog ("%s: get_free live %d dead %d ret %" PRId64 "\n",
1335 live, dead, (((int64_t) dead << 32) / sw->ratio) << sw->info.shift);
1338 return (((int64_t) dead << 32) / sw->ratio) << sw->info.shift;
1341 static void audio_capture_mix_and_clear (HWVoiceOut *hw, int rpos, int samples)
1348 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1349 SWVoiceOut *sw = &sc->sw;
1354 int till_end_of_hw = hw->samples - rpos2;
1355 int to_write = audio_MIN (till_end_of_hw, n);
1356 int bytes = to_write << hw->info.shift;
1359 sw->buf = hw->mix_buf + rpos2;
1360 written = audio_pcm_sw_write (sw, NULL, bytes);
1361 if (written - bytes) {
1362 dolog ("Could not mix %d bytes into a capture "
1363 "buffer, mixed %d\n",
1368 rpos2 = (rpos2 + to_write) % hw->samples;
1373 n = audio_MIN (samples, hw->samples - rpos);
1374 mixeng_clear (hw->mix_buf + rpos, n);
1375 mixeng_clear (hw->mix_buf, samples - n);
1378 static void audio_run_out (AudioState *s)
1380 HWVoiceOut *hw = NULL;
1383 while ((hw = audio_pcm_hw_find_any_enabled_out (hw))) {
1385 int live, free, nb_live, cleanup_required, prev_rpos;
1387 live = audio_pcm_hw_get_live_out (hw, &nb_live);
1392 if (audio_bug(__func__, live < 0 || live > hw->samples)) {
1393 dolog ("live=%d hw->samples=%d\n", live, hw->samples);
1397 if (hw->pending_disable && !nb_live) {
1400 dolog ("Disabling voice\n");
1403 hw->pending_disable = 0;
1404 hw->pcm_ops->ctl_out (hw, VOICE_DISABLE);
1405 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1407 audio_recalc_and_notify_capture (sc->cap);
1413 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1415 free = audio_get_free (sw);
1417 sw->callback.fn (sw->callback.opaque, free);
1424 prev_rpos = hw->rpos;
1425 played = hw->pcm_ops->run_out (hw, live);
1426 replay_audio_out(&played);
1427 if (audio_bug(__func__, hw->rpos >= hw->samples)) {
1428 dolog ("hw->rpos=%d hw->samples=%d played=%d\n",
1429 hw->rpos, hw->samples, played);
1434 dolog ("played=%d\n", played);
1438 hw->ts_helper += played;
1439 audio_capture_mix_and_clear (hw, prev_rpos, played);
1442 cleanup_required = 0;
1443 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1444 if (!sw->active && sw->empty) {
1448 if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1449 dolog ("played=%d sw->total_hw_samples_mixed=%d\n",
1450 played, sw->total_hw_samples_mixed);
1451 played = sw->total_hw_samples_mixed;
1454 sw->total_hw_samples_mixed -= played;
1456 if (!sw->total_hw_samples_mixed) {
1458 cleanup_required |= !sw->active && !sw->callback.fn;
1462 free = audio_get_free (sw);
1464 sw->callback.fn (sw->callback.opaque, free);
1469 if (cleanup_required) {
1472 sw = hw->sw_head.lh_first;
1474 sw1 = sw->entries.le_next;
1475 if (!sw->active && !sw->callback.fn) {
1476 audio_close_out (sw);
1484 static void audio_run_in (AudioState *s)
1486 HWVoiceIn *hw = NULL;
1488 while ((hw = audio_pcm_hw_find_any_enabled_in (hw))) {
1490 int captured = 0, min;
1492 if (replay_mode != REPLAY_MODE_PLAY) {
1493 captured = hw->pcm_ops->run_in(hw);
1495 replay_audio_in(&captured, hw->conv_buf, &hw->wpos, hw->samples);
1497 min = audio_pcm_hw_find_min_in (hw);
1498 hw->total_samples_captured += captured - min;
1499 hw->ts_helper += captured;
1501 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1502 sw->total_hw_samples_acquired -= min;
1507 avail = audio_get_avail (sw);
1509 sw->callback.fn (sw->callback.opaque, avail);
1516 static void audio_run_capture (AudioState *s)
1518 CaptureVoiceOut *cap;
1520 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1521 int live, rpos, captured;
1522 HWVoiceOut *hw = &cap->hw;
1525 captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1528 int left = hw->samples - rpos;
1529 int to_capture = audio_MIN (live, left);
1530 struct st_sample *src;
1531 struct capture_callback *cb;
1533 src = hw->mix_buf + rpos;
1534 hw->clip (cap->buf, src, to_capture);
1535 mixeng_clear (src, to_capture);
1537 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1538 cb->ops.capture (cb->opaque, cap->buf,
1539 to_capture << hw->info.shift);
1541 rpos = (rpos + to_capture) % hw->samples;
1546 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1547 if (!sw->active && sw->empty) {
1551 if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1552 dolog ("captured=%d sw->total_hw_samples_mixed=%d\n",
1553 captured, sw->total_hw_samples_mixed);
1554 captured = sw->total_hw_samples_mixed;
1557 sw->total_hw_samples_mixed -= captured;
1558 sw->empty = sw->total_hw_samples_mixed == 0;
1563 void audio_run (const char *msg)
1565 AudioState *s = &glob_audio_state;
1569 audio_run_capture (s);
1572 static double prevtime;
1576 if (gettimeofday (&tv, NULL)) {
1577 perror ("audio_run: gettimeofday");
1581 currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1582 dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1583 prevtime = currtime;
1588 static struct audio_option audio_options[] = {
1591 .name = "DAC_FIXED_SETTINGS",
1592 .tag = AUD_OPT_BOOL,
1593 .valp = &conf.fixed_out.enabled,
1594 .descr = "Use fixed settings for host DAC"
1597 .name = "DAC_FIXED_FREQ",
1599 .valp = &conf.fixed_out.settings.freq,
1600 .descr = "Frequency for fixed host DAC"
1603 .name = "DAC_FIXED_FMT",
1605 .valp = &conf.fixed_out.settings.fmt,
1606 .descr = "Format for fixed host DAC"
1609 .name = "DAC_FIXED_CHANNELS",
1611 .valp = &conf.fixed_out.settings.nchannels,
1612 .descr = "Number of channels for fixed DAC (1 - mono, 2 - stereo)"
1615 .name = "DAC_VOICES",
1617 .valp = &conf.fixed_out.nb_voices,
1618 .descr = "Number of voices for DAC"
1621 .name = "DAC_TRY_POLL",
1622 .tag = AUD_OPT_BOOL,
1623 .valp = &conf.try_poll_out,
1624 .descr = "Attempt using poll mode for DAC"
1628 .name = "ADC_FIXED_SETTINGS",
1629 .tag = AUD_OPT_BOOL,
1630 .valp = &conf.fixed_in.enabled,
1631 .descr = "Use fixed settings for host ADC"
1634 .name = "ADC_FIXED_FREQ",
1636 .valp = &conf.fixed_in.settings.freq,
1637 .descr = "Frequency for fixed host ADC"
1640 .name = "ADC_FIXED_FMT",
1642 .valp = &conf.fixed_in.settings.fmt,
1643 .descr = "Format for fixed host ADC"
1646 .name = "ADC_FIXED_CHANNELS",
1648 .valp = &conf.fixed_in.settings.nchannels,
1649 .descr = "Number of channels for fixed ADC (1 - mono, 2 - stereo)"
1652 .name = "ADC_VOICES",
1654 .valp = &conf.fixed_in.nb_voices,
1655 .descr = "Number of voices for ADC"
1658 .name = "ADC_TRY_POLL",
1659 .tag = AUD_OPT_BOOL,
1660 .valp = &conf.try_poll_in,
1661 .descr = "Attempt using poll mode for ADC"
1665 .name = "TIMER_PERIOD",
1667 .valp = &conf.period.hertz,
1668 .descr = "Timer period in HZ (0 - use lowest possible)"
1670 { /* End of list */ }
1673 static void audio_pp_nb_voices (const char *typ, int nb)
1677 printf ("Does not support %s\n", typ);
1680 printf ("One %s voice\n", typ);
1683 printf ("Theoretically supports many %s voices\n", typ);
1686 printf ("Theoretically supports up to %d %s voices\n", nb, typ);
1692 void AUD_help (void)
1694 struct audio_driver *d;
1696 /* make sure we print the help text for modular drivers too */
1697 audio_module_load_all();
1699 audio_process_options ("AUDIO", audio_options);
1700 QLIST_FOREACH(d, &audio_drivers, next) {
1702 audio_process_options (d->name, d->options);
1706 printf ("Audio options:\n");
1707 audio_print_options ("AUDIO", audio_options);
1710 printf ("Available drivers:\n");
1712 QLIST_FOREACH(d, &audio_drivers, next) {
1714 printf ("Name: %s\n", d->name);
1715 printf ("Description: %s\n", d->descr);
1717 audio_pp_nb_voices ("playback", d->max_voices_out);
1718 audio_pp_nb_voices ("capture", d->max_voices_in);
1721 printf ("Options:\n");
1722 audio_print_options (d->name, d->options);
1725 printf ("No options\n");
1731 "Options are settable through environment variables.\n"
1734 " set QEMU_AUDIO_DRV=wav\n"
1735 " set QEMU_WAV_PATH=c:\\tune.wav\n"
1737 " export QEMU_AUDIO_DRV=wav\n"
1738 " export QEMU_WAV_PATH=$HOME/tune.wav\n"
1739 "(for csh replace export with setenv in the above)\n"
1745 static int audio_driver_init(AudioState *s, struct audio_driver *drv, bool msg)
1748 audio_process_options (drv->name, drv->options);
1750 s->drv_opaque = drv->init ();
1752 if (s->drv_opaque) {
1753 audio_init_nb_voices_out (drv);
1754 audio_init_nb_voices_in (drv);
1760 dolog("Could not init `%s' audio driver\n", drv->name);
1766 static void audio_vm_change_state_handler (void *opaque, int running,
1769 AudioState *s = opaque;
1770 HWVoiceOut *hwo = NULL;
1771 HWVoiceIn *hwi = NULL;
1772 int op = running ? VOICE_ENABLE : VOICE_DISABLE;
1774 s->vm_running = running;
1775 while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
1776 hwo->pcm_ops->ctl_out (hwo, op, conf.try_poll_out);
1779 while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
1780 hwi->pcm_ops->ctl_in (hwi, op, conf.try_poll_in);
1782 audio_reset_timer (s);
1785 static bool is_cleaning_up;
1787 bool audio_is_cleaning_up(void)
1789 return is_cleaning_up;
1792 void audio_cleanup(void)
1794 AudioState *s = &glob_audio_state;
1795 HWVoiceOut *hwo, *hwon;
1796 HWVoiceIn *hwi, *hwin;
1798 is_cleaning_up = true;
1799 QLIST_FOREACH_SAFE(hwo, &glob_audio_state.hw_head_out, entries, hwon) {
1803 hwo->pcm_ops->ctl_out (hwo, VOICE_DISABLE);
1805 hwo->pcm_ops->fini_out (hwo);
1807 for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1808 CaptureVoiceOut *cap = sc->cap;
1809 struct capture_callback *cb;
1811 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1812 cb->ops.destroy (cb->opaque);
1815 QLIST_REMOVE(hwo, entries);
1818 QLIST_FOREACH_SAFE(hwi, &glob_audio_state.hw_head_in, entries, hwin) {
1820 hwi->pcm_ops->ctl_in (hwi, VOICE_DISABLE);
1822 hwi->pcm_ops->fini_in (hwi);
1823 QLIST_REMOVE(hwi, entries);
1827 s->drv->fini (s->drv_opaque);
1832 static const VMStateDescription vmstate_audio = {
1835 .minimum_version_id = 1,
1836 .fields = (VMStateField[]) {
1837 VMSTATE_END_OF_LIST()
1841 static void audio_init (void)
1845 const char *drvname;
1846 VMChangeStateEntry *e;
1847 AudioState *s = &glob_audio_state;
1848 struct audio_driver *driver;
1854 QLIST_INIT (&s->hw_head_out);
1855 QLIST_INIT (&s->hw_head_in);
1856 QLIST_INIT (&s->cap_head);
1857 atexit(audio_cleanup);
1859 s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1861 audio_process_options ("AUDIO", audio_options);
1863 s->nb_hw_voices_out = conf.fixed_out.nb_voices;
1864 s->nb_hw_voices_in = conf.fixed_in.nb_voices;
1866 if (s->nb_hw_voices_out <= 0) {
1867 dolog ("Bogus number of playback voices %d, setting to 1\n",
1868 s->nb_hw_voices_out);
1869 s->nb_hw_voices_out = 1;
1872 if (s->nb_hw_voices_in <= 0) {
1873 dolog ("Bogus number of capture voices %d, setting to 0\n",
1874 s->nb_hw_voices_in);
1875 s->nb_hw_voices_in = 0;
1880 drvname = audio_get_conf_str ("QEMU_AUDIO_DRV", NULL, &def);
1884 driver = audio_driver_lookup(drvname);
1886 done = !audio_driver_init(s, driver, true);
1888 dolog ("Unknown audio driver `%s'\n", drvname);
1889 dolog ("Run with -audio-help to list available drivers\n");
1894 for (i = 0; !done && i < ARRAY_SIZE(audio_prio_list); i++) {
1895 driver = audio_driver_lookup(audio_prio_list[i]);
1896 if (driver && driver->can_be_default) {
1897 done = !audio_driver_init(s, driver, false);
1903 driver = audio_driver_lookup("none");
1904 done = !audio_driver_init(s, driver, false);
1906 dolog("warning: Using timer based audio emulation\n");
1909 if (conf.period.hertz <= 0) {
1910 if (conf.period.hertz < 0) {
1911 dolog ("warning: Timer period is negative - %d "
1912 "treating as zero\n",
1915 conf.period.ticks = 1;
1917 conf.period.ticks = NANOSECONDS_PER_SECOND / conf.period.hertz;
1920 e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1922 dolog ("warning: Could not register change state handler\n"
1923 "(Audio can continue looping even after stopping the VM)\n");
1926 QLIST_INIT (&s->card_head);
1927 vmstate_register (NULL, 0, &vmstate_audio, s);
1930 void AUD_register_card (const char *name, QEMUSoundCard *card)
1933 card->name = g_strdup (name);
1934 memset (&card->entries, 0, sizeof (card->entries));
1935 QLIST_INSERT_HEAD (&glob_audio_state.card_head, card, entries);
1938 void AUD_remove_card (QEMUSoundCard *card)
1940 QLIST_REMOVE (card, entries);
1941 g_free (card->name);
1945 CaptureVoiceOut *AUD_add_capture (
1946 struct audsettings *as,
1947 struct audio_capture_ops *ops,
1951 AudioState *s = &glob_audio_state;
1952 CaptureVoiceOut *cap;
1953 struct capture_callback *cb;
1955 if (audio_validate_settings (as)) {
1956 dolog ("Invalid settings were passed when trying to add capture\n");
1957 audio_print_settings (as);
1961 cb = g_malloc0(sizeof(*cb));
1963 cb->opaque = cb_opaque;
1965 cap = audio_pcm_capture_find_specific (as);
1967 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1972 CaptureVoiceOut *cap;
1974 cap = g_malloc0(sizeof(*cap));
1977 QLIST_INIT (&hw->sw_head);
1978 QLIST_INIT (&cap->cb_head);
1980 /* XXX find a more elegant way */
1981 hw->samples = 4096 * 4;
1982 hw->mix_buf = g_new0(struct st_sample, hw->samples);
1984 audio_pcm_init_info (&hw->info, as);
1986 cap->buf = g_malloc0_n(hw->samples, 1 << hw->info.shift);
1988 hw->clip = mixeng_clip
1989 [hw->info.nchannels == 2]
1991 [hw->info.swap_endianness]
1992 [audio_bits_to_index (hw->info.bits)];
1994 QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1995 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1997 QLIST_FOREACH(hw, &glob_audio_state.hw_head_out, entries) {
1998 audio_attach_capture (hw);
2004 void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
2006 struct capture_callback *cb;
2008 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
2009 if (cb->opaque == cb_opaque) {
2010 cb->ops.destroy (cb_opaque);
2011 QLIST_REMOVE (cb, entries);
2014 if (!cap->cb_head.lh_first) {
2015 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
2018 SWVoiceCap *sc = (SWVoiceCap *) sw;
2019 #ifdef DEBUG_CAPTURE
2020 dolog ("freeing %s\n", sw->name);
2023 sw1 = sw->entries.le_next;
2025 st_rate_stop (sw->rate);
2028 QLIST_REMOVE (sw, entries);
2029 QLIST_REMOVE (sc, entries);
2033 QLIST_REMOVE (cap, entries);
2034 g_free (cap->hw.mix_buf);
2043 void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
2046 HWVoiceOut *hw = sw->hw;
2048 sw->vol.mute = mute;
2049 sw->vol.l = nominal_volume.l * lvol / 255;
2050 sw->vol.r = nominal_volume.r * rvol / 255;
2052 if (hw->pcm_ops->ctl_out) {
2053 hw->pcm_ops->ctl_out (hw, VOICE_VOLUME, sw);
2058 void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
2061 HWVoiceIn *hw = sw->hw;
2063 sw->vol.mute = mute;
2064 sw->vol.l = nominal_volume.l * lvol / 255;
2065 sw->vol.r = nominal_volume.r * rvol / 255;
2067 if (hw->pcm_ops->ctl_in) {
2068 hw->pcm_ops->ctl_in (hw, VOICE_VOLUME, sw);