xref: /openbmc/qemu/audio/audio.c (revision 5c63d141)
1 /*
2  * QEMU Audio subsystem
3  *
4  * Copyright (c) 2003-2005 Vassili Karpov (malc)
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "audio.h"
27 #include "migration/vmstate.h"
28 #include "monitor/monitor.h"
29 #include "qemu/timer.h"
30 #include "qapi/error.h"
31 #include "qapi/clone-visitor.h"
32 #include "qapi/qobject-input-visitor.h"
33 #include "qapi/qapi-visit-audio.h"
34 #include "qapi/qapi-commands-audio.h"
35 #include "qemu/cutils.h"
36 #include "qemu/error-report.h"
37 #include "qemu/log.h"
38 #include "qemu/module.h"
39 #include "qemu/help_option.h"
40 #include "sysemu/sysemu.h"
41 #include "sysemu/replay.h"
42 #include "sysemu/runstate.h"
43 #include "ui/qemu-spice.h"
44 #include "trace.h"
45 
46 #define AUDIO_CAP "audio"
47 #include "audio_int.h"
48 
49 /* #define DEBUG_LIVE */
50 /* #define DEBUG_OUT */
51 /* #define DEBUG_CAPTURE */
52 /* #define DEBUG_POLL */
53 
54 #define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
55 
56 
57 /* Order of CONFIG_AUDIO_DRIVERS is import.
58    The 1st one is the one used by default, that is the reason
59     that we generate the list.
60 */
61 const char *audio_prio_list[] = {
62     "spice",
63     CONFIG_AUDIO_DRIVERS
64     "none",
65     "wav",
66     NULL
67 };
68 
69 static QLIST_HEAD(, audio_driver) audio_drivers;
70 static AudiodevListHead audiodevs = QSIMPLEQ_HEAD_INITIALIZER(audiodevs);
71 
72 void audio_driver_register(audio_driver *drv)
73 {
74     QLIST_INSERT_HEAD(&audio_drivers, drv, next);
75 }
76 
77 audio_driver *audio_driver_lookup(const char *name)
78 {
79     struct audio_driver *d;
80     Error *local_err = NULL;
81     int rv;
82 
83     QLIST_FOREACH(d, &audio_drivers, next) {
84         if (strcmp(name, d->name) == 0) {
85             return d;
86         }
87     }
88     rv = audio_module_load(name, &local_err);
89     if (rv > 0) {
90         QLIST_FOREACH(d, &audio_drivers, next) {
91             if (strcmp(name, d->name) == 0) {
92                 return d;
93             }
94         }
95     } else if (rv < 0) {
96         error_report_err(local_err);
97     }
98     return NULL;
99 }
100 
101 static QTAILQ_HEAD(AudioStateHead, AudioState) audio_states =
102     QTAILQ_HEAD_INITIALIZER(audio_states);
103 
104 const struct mixeng_volume nominal_volume = {
105     .mute = 0,
106 #ifdef FLOAT_MIXENG
107     .r = 1.0,
108     .l = 1.0,
109 #else
110     .r = 1ULL << 32,
111     .l = 1ULL << 32,
112 #endif
113 };
114 
115 static bool legacy_config = true;
116 
117 int audio_bug (const char *funcname, int cond)
118 {
119     if (cond) {
120         static int shown;
121 
122         AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
123         if (!shown) {
124             shown = 1;
125             AUD_log (NULL, "Save all your work and restart without audio\n");
126             AUD_log (NULL, "I am sorry\n");
127         }
128         AUD_log (NULL, "Context:\n");
129     }
130 
131     return cond;
132 }
133 
134 static inline int audio_bits_to_index (int bits)
135 {
136     switch (bits) {
137     case 8:
138         return 0;
139 
140     case 16:
141         return 1;
142 
143     case 32:
144         return 2;
145 
146     default:
147         audio_bug ("bits_to_index", 1);
148         AUD_log (NULL, "invalid bits %d\n", bits);
149         return 0;
150     }
151 }
152 
153 void AUD_vlog (const char *cap, const char *fmt, va_list ap)
154 {
155     if (cap) {
156         fprintf(stderr, "%s: ", cap);
157     }
158 
159     vfprintf(stderr, fmt, ap);
160 }
161 
162 void AUD_log (const char *cap, const char *fmt, ...)
163 {
164     va_list ap;
165 
166     va_start (ap, fmt);
167     AUD_vlog (cap, fmt, ap);
168     va_end (ap);
169 }
170 
171 static void audio_print_settings (struct audsettings *as)
172 {
173     dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
174 
175     switch (as->fmt) {
176     case AUDIO_FORMAT_S8:
177         AUD_log (NULL, "S8");
178         break;
179     case AUDIO_FORMAT_U8:
180         AUD_log (NULL, "U8");
181         break;
182     case AUDIO_FORMAT_S16:
183         AUD_log (NULL, "S16");
184         break;
185     case AUDIO_FORMAT_U16:
186         AUD_log (NULL, "U16");
187         break;
188     case AUDIO_FORMAT_S32:
189         AUD_log (NULL, "S32");
190         break;
191     case AUDIO_FORMAT_U32:
192         AUD_log (NULL, "U32");
193         break;
194     case AUDIO_FORMAT_F32:
195         AUD_log (NULL, "F32");
196         break;
197     default:
198         AUD_log (NULL, "invalid(%d)", as->fmt);
199         break;
200     }
201 
202     AUD_log (NULL, " endianness=");
203     switch (as->endianness) {
204     case 0:
205         AUD_log (NULL, "little");
206         break;
207     case 1:
208         AUD_log (NULL, "big");
209         break;
210     default:
211         AUD_log (NULL, "invalid");
212         break;
213     }
214     AUD_log (NULL, "\n");
215 }
216 
217 static int audio_validate_settings (struct audsettings *as)
218 {
219     int invalid;
220 
221     invalid = as->nchannels < 1;
222     invalid |= as->endianness != 0 && as->endianness != 1;
223 
224     switch (as->fmt) {
225     case AUDIO_FORMAT_S8:
226     case AUDIO_FORMAT_U8:
227     case AUDIO_FORMAT_S16:
228     case AUDIO_FORMAT_U16:
229     case AUDIO_FORMAT_S32:
230     case AUDIO_FORMAT_U32:
231     case AUDIO_FORMAT_F32:
232         break;
233     default:
234         invalid = 1;
235         break;
236     }
237 
238     invalid |= as->freq <= 0;
239     return invalid ? -1 : 0;
240 }
241 
242 static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
243 {
244     int bits = 8;
245     bool is_signed = false, is_float = false;
246 
247     switch (as->fmt) {
248     case AUDIO_FORMAT_S8:
249         is_signed = true;
250         /* fall through */
251     case AUDIO_FORMAT_U8:
252         break;
253 
254     case AUDIO_FORMAT_S16:
255         is_signed = true;
256         /* fall through */
257     case AUDIO_FORMAT_U16:
258         bits = 16;
259         break;
260 
261     case AUDIO_FORMAT_F32:
262         is_float = true;
263         /* fall through */
264     case AUDIO_FORMAT_S32:
265         is_signed = true;
266         /* fall through */
267     case AUDIO_FORMAT_U32:
268         bits = 32;
269         break;
270 
271     default:
272         abort();
273     }
274     return info->freq == as->freq
275         && info->nchannels == as->nchannels
276         && info->is_signed == is_signed
277         && info->is_float == is_float
278         && info->bits == bits
279         && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
280 }
281 
282 void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
283 {
284     int bits = 8, mul;
285     bool is_signed = false, is_float = false;
286 
287     switch (as->fmt) {
288     case AUDIO_FORMAT_S8:
289         is_signed = true;
290         /* fall through */
291     case AUDIO_FORMAT_U8:
292         mul = 1;
293         break;
294 
295     case AUDIO_FORMAT_S16:
296         is_signed = true;
297         /* fall through */
298     case AUDIO_FORMAT_U16:
299         bits = 16;
300         mul = 2;
301         break;
302 
303     case AUDIO_FORMAT_F32:
304         is_float = true;
305         /* fall through */
306     case AUDIO_FORMAT_S32:
307         is_signed = true;
308         /* fall through */
309     case AUDIO_FORMAT_U32:
310         bits = 32;
311         mul = 4;
312         break;
313 
314     default:
315         abort();
316     }
317 
318     info->freq = as->freq;
319     info->bits = bits;
320     info->is_signed = is_signed;
321     info->is_float = is_float;
322     info->nchannels = as->nchannels;
323     info->bytes_per_frame = as->nchannels * mul;
324     info->bytes_per_second = info->freq * info->bytes_per_frame;
325     info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
326 }
327 
328 void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
329 {
330     if (!len) {
331         return;
332     }
333 
334     if (info->is_signed || info->is_float) {
335         memset(buf, 0x00, len * info->bytes_per_frame);
336     } else {
337         switch (info->bits) {
338         case 8:
339             memset(buf, 0x80, len * info->bytes_per_frame);
340             break;
341 
342         case 16:
343             {
344                 int i;
345                 uint16_t *p = buf;
346                 short s = INT16_MAX;
347 
348                 if (info->swap_endianness) {
349                     s = bswap16 (s);
350                 }
351 
352                 for (i = 0; i < len * info->nchannels; i++) {
353                     p[i] = s;
354                 }
355             }
356             break;
357 
358         case 32:
359             {
360                 int i;
361                 uint32_t *p = buf;
362                 int32_t s = INT32_MAX;
363 
364                 if (info->swap_endianness) {
365                     s = bswap32 (s);
366                 }
367 
368                 for (i = 0; i < len * info->nchannels; i++) {
369                     p[i] = s;
370                 }
371             }
372             break;
373 
374         default:
375             AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
376                      info->bits);
377             break;
378         }
379     }
380 }
381 
382 /*
383  * Capture
384  */
385 static CaptureVoiceOut *audio_pcm_capture_find_specific(AudioState *s,
386                                                         struct audsettings *as)
387 {
388     CaptureVoiceOut *cap;
389 
390     for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
391         if (audio_pcm_info_eq (&cap->hw.info, as)) {
392             return cap;
393         }
394     }
395     return NULL;
396 }
397 
398 static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
399 {
400     struct capture_callback *cb;
401 
402 #ifdef DEBUG_CAPTURE
403     dolog ("notification %d sent\n", cmd);
404 #endif
405     for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
406         cb->ops.notify (cb->opaque, cmd);
407     }
408 }
409 
410 static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
411 {
412     if (cap->hw.enabled != enabled) {
413         audcnotification_e cmd;
414         cap->hw.enabled = enabled;
415         cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
416         audio_notify_capture (cap, cmd);
417     }
418 }
419 
420 static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
421 {
422     HWVoiceOut *hw = &cap->hw;
423     SWVoiceOut *sw;
424     int enabled = 0;
425 
426     for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
427         if (sw->active) {
428             enabled = 1;
429             break;
430         }
431     }
432     audio_capture_maybe_changed (cap, enabled);
433 }
434 
435 static void audio_detach_capture (HWVoiceOut *hw)
436 {
437     SWVoiceCap *sc = hw->cap_head.lh_first;
438 
439     while (sc) {
440         SWVoiceCap *sc1 = sc->entries.le_next;
441         SWVoiceOut *sw = &sc->sw;
442         CaptureVoiceOut *cap = sc->cap;
443         int was_active = sw->active;
444 
445         if (sw->rate) {
446             st_rate_stop (sw->rate);
447             sw->rate = NULL;
448         }
449 
450         QLIST_REMOVE (sw, entries);
451         QLIST_REMOVE (sc, entries);
452         g_free (sc);
453         if (was_active) {
454             /* We have removed soft voice from the capture:
455                this might have changed the overall status of the capture
456                since this might have been the only active voice */
457             audio_recalc_and_notify_capture (cap);
458         }
459         sc = sc1;
460     }
461 }
462 
463 static int audio_attach_capture (HWVoiceOut *hw)
464 {
465     AudioState *s = hw->s;
466     CaptureVoiceOut *cap;
467 
468     audio_detach_capture (hw);
469     for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
470         SWVoiceCap *sc;
471         SWVoiceOut *sw;
472         HWVoiceOut *hw_cap = &cap->hw;
473 
474         sc = g_malloc0(sizeof(*sc));
475 
476         sc->cap = cap;
477         sw = &sc->sw;
478         sw->hw = hw_cap;
479         sw->info = hw->info;
480         sw->empty = 1;
481         sw->active = hw->enabled;
482         sw->vol = nominal_volume;
483         sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
484         QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
485         QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
486 #ifdef DEBUG_CAPTURE
487         sw->name = g_strdup_printf ("for %p %d,%d,%d",
488                                     hw, sw->info.freq, sw->info.bits,
489                                     sw->info.nchannels);
490         dolog ("Added %s active = %d\n", sw->name, sw->active);
491 #endif
492         if (sw->active) {
493             audio_capture_maybe_changed (cap, 1);
494         }
495     }
496     return 0;
497 }
498 
499 /*
500  * Hard voice (capture)
501  */
502 static size_t audio_pcm_hw_find_min_in (HWVoiceIn *hw)
503 {
504     SWVoiceIn *sw;
505     size_t m = hw->total_samples_captured;
506 
507     for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
508         if (sw->active) {
509             m = MIN (m, sw->total_hw_samples_acquired);
510         }
511     }
512     return m;
513 }
514 
515 static size_t audio_pcm_hw_get_live_in(HWVoiceIn *hw)
516 {
517     size_t live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
518     if (audio_bug(__func__, live > hw->conv_buf.size)) {
519         dolog("live=%zu hw->conv_buf.size=%zu\n", live, hw->conv_buf.size);
520         return 0;
521     }
522     return live;
523 }
524 
525 static size_t audio_pcm_hw_conv_in(HWVoiceIn *hw, void *pcm_buf, size_t samples)
526 {
527     size_t conv = 0;
528     STSampleBuffer *conv_buf = &hw->conv_buf;
529 
530     while (samples) {
531         uint8_t *src = advance(pcm_buf, conv * hw->info.bytes_per_frame);
532         size_t proc = MIN(samples, conv_buf->size - conv_buf->pos);
533 
534         hw->conv(conv_buf->buffer + conv_buf->pos, src, proc);
535         conv_buf->pos = (conv_buf->pos + proc) % conv_buf->size;
536         samples -= proc;
537         conv += proc;
538     }
539 
540     return conv;
541 }
542 
543 /*
544  * Soft voice (capture)
545  */
546 static void audio_pcm_sw_resample_in(SWVoiceIn *sw,
547     size_t frames_in_max, size_t frames_out_max,
548     size_t *total_in, size_t *total_out)
549 {
550     HWVoiceIn *hw = sw->hw;
551     struct st_sample *src, *dst;
552     size_t live, rpos, frames_in, frames_out;
553 
554     live = hw->total_samples_captured - sw->total_hw_samples_acquired;
555     rpos = audio_ring_posb(hw->conv_buf.pos, live, hw->conv_buf.size);
556 
557     /* resample conv_buf from rpos to end of buffer */
558     src = hw->conv_buf.buffer + rpos;
559     frames_in = MIN(frames_in_max, hw->conv_buf.size - rpos);
560     dst = sw->resample_buf.buffer;
561     frames_out = frames_out_max;
562     st_rate_flow(sw->rate, src, dst, &frames_in, &frames_out);
563     rpos += frames_in;
564     *total_in = frames_in;
565     *total_out = frames_out;
566 
567     /* resample conv_buf from start of buffer if there are input frames left */
568     if (frames_in_max - frames_in && rpos == hw->conv_buf.size) {
569         src = hw->conv_buf.buffer;
570         frames_in = frames_in_max - frames_in;
571         dst += frames_out;
572         frames_out = frames_out_max - frames_out;
573         st_rate_flow(sw->rate, src, dst, &frames_in, &frames_out);
574         *total_in += frames_in;
575         *total_out += frames_out;
576     }
577 }
578 
579 static size_t audio_pcm_sw_read(SWVoiceIn *sw, void *buf, size_t buf_len)
580 {
581     HWVoiceIn *hw = sw->hw;
582     size_t live, frames_out_max, total_in, total_out;
583 
584     live = hw->total_samples_captured - sw->total_hw_samples_acquired;
585     if (!live) {
586         return 0;
587     }
588     if (audio_bug(__func__, live > hw->conv_buf.size)) {
589         dolog("live_in=%zu hw->conv_buf.size=%zu\n", live, hw->conv_buf.size);
590         return 0;
591     }
592 
593     frames_out_max = MIN(buf_len / sw->info.bytes_per_frame,
594                          sw->resample_buf.size);
595 
596     audio_pcm_sw_resample_in(sw, live, frames_out_max, &total_in, &total_out);
597 
598     if (!hw->pcm_ops->volume_in) {
599         mixeng_volume(sw->resample_buf.buffer, total_out, &sw->vol);
600     }
601     sw->clip(buf, sw->resample_buf.buffer, total_out);
602 
603     sw->total_hw_samples_acquired += total_in;
604     return total_out * sw->info.bytes_per_frame;
605 }
606 
607 /*
608  * Hard voice (playback)
609  */
610 static size_t audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
611 {
612     SWVoiceOut *sw;
613     size_t m = SIZE_MAX;
614     int nb_live = 0;
615 
616     for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
617         if (sw->active || !sw->empty) {
618             m = MIN (m, sw->total_hw_samples_mixed);
619             nb_live += 1;
620         }
621     }
622 
623     *nb_livep = nb_live;
624     return m;
625 }
626 
627 static size_t audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
628 {
629     size_t smin;
630     int nb_live1;
631 
632     smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
633     if (nb_live) {
634         *nb_live = nb_live1;
635     }
636 
637     if (nb_live1) {
638         size_t live = smin;
639 
640         if (audio_bug(__func__, live > hw->mix_buf.size)) {
641             dolog("live=%zu hw->mix_buf.size=%zu\n", live, hw->mix_buf.size);
642             return 0;
643         }
644         return live;
645     }
646     return 0;
647 }
648 
649 static size_t audio_pcm_hw_get_free(HWVoiceOut *hw)
650 {
651     return (hw->pcm_ops->buffer_get_free ? hw->pcm_ops->buffer_get_free(hw) :
652             INT_MAX) / hw->info.bytes_per_frame;
653 }
654 
655 static void audio_pcm_hw_clip_out(HWVoiceOut *hw, void *pcm_buf, size_t len)
656 {
657     size_t clipped = 0;
658     size_t pos = hw->mix_buf.pos;
659 
660     while (len) {
661         st_sample *src = hw->mix_buf.buffer + pos;
662         uint8_t *dst = advance(pcm_buf, clipped * hw->info.bytes_per_frame);
663         size_t samples_till_end_of_buf = hw->mix_buf.size - pos;
664         size_t samples_to_clip = MIN(len, samples_till_end_of_buf);
665 
666         hw->clip(dst, src, samples_to_clip);
667 
668         pos = (pos + samples_to_clip) % hw->mix_buf.size;
669         len -= samples_to_clip;
670         clipped += samples_to_clip;
671     }
672 }
673 
674 /*
675  * Soft voice (playback)
676  */
677 static void audio_pcm_sw_resample_out(SWVoiceOut *sw,
678     size_t frames_in_max, size_t frames_out_max,
679     size_t *total_in, size_t *total_out)
680 {
681     HWVoiceOut *hw = sw->hw;
682     struct st_sample *src, *dst;
683     size_t live, wpos, frames_in, frames_out;
684 
685     live = sw->total_hw_samples_mixed;
686     wpos = (hw->mix_buf.pos + live) % hw->mix_buf.size;
687 
688     /* write to mix_buf from wpos to end of buffer */
689     src = sw->resample_buf.buffer;
690     frames_in = frames_in_max;
691     dst = hw->mix_buf.buffer + wpos;
692     frames_out = MIN(frames_out_max, hw->mix_buf.size - wpos);
693     st_rate_flow_mix(sw->rate, src, dst, &frames_in, &frames_out);
694     wpos += frames_out;
695     *total_in = frames_in;
696     *total_out = frames_out;
697 
698     /* write to mix_buf from start of buffer if there are input frames left */
699     if (frames_in_max - frames_in > 0 && wpos == hw->mix_buf.size) {
700         src += frames_in;
701         frames_in = frames_in_max - frames_in;
702         dst = hw->mix_buf.buffer;
703         frames_out = frames_out_max - frames_out;
704         st_rate_flow_mix(sw->rate, src, dst, &frames_in, &frames_out);
705         *total_in += frames_in;
706         *total_out += frames_out;
707     }
708 }
709 
710 static size_t audio_pcm_sw_write(SWVoiceOut *sw, void *buf, size_t buf_len)
711 {
712     HWVoiceOut *hw = sw->hw;
713     size_t live, dead, hw_free, sw_max, fe_max;
714     size_t frames_in_max, frames_out_max, total_in, total_out;
715 
716     live = sw->total_hw_samples_mixed;
717     if (audio_bug(__func__, live > hw->mix_buf.size)) {
718         dolog("live=%zu hw->mix_buf.size=%zu\n", live, hw->mix_buf.size);
719         return 0;
720     }
721 
722     if (live == hw->mix_buf.size) {
723 #ifdef DEBUG_OUT
724         dolog ("%s is full %zu\n", sw->name, live);
725 #endif
726         return 0;
727     }
728 
729     dead = hw->mix_buf.size - live;
730     hw_free = audio_pcm_hw_get_free(hw);
731     hw_free = hw_free > live ? hw_free - live : 0;
732     frames_out_max = MIN(dead, hw_free);
733     sw_max = st_rate_frames_in(sw->rate, frames_out_max);
734     fe_max = MIN(buf_len / sw->info.bytes_per_frame + sw->resample_buf.pos,
735                  sw->resample_buf.size);
736     frames_in_max = MIN(sw_max, fe_max);
737 
738     if (!frames_in_max) {
739         return 0;
740     }
741 
742     if (frames_in_max > sw->resample_buf.pos) {
743         sw->conv(sw->resample_buf.buffer + sw->resample_buf.pos,
744                  buf, frames_in_max - sw->resample_buf.pos);
745         if (!sw->hw->pcm_ops->volume_out) {
746             mixeng_volume(sw->resample_buf.buffer + sw->resample_buf.pos,
747                           frames_in_max - sw->resample_buf.pos, &sw->vol);
748         }
749     }
750 
751     audio_pcm_sw_resample_out(sw, frames_in_max, frames_out_max,
752                               &total_in, &total_out);
753 
754     sw->total_hw_samples_mixed += total_out;
755     sw->empty = sw->total_hw_samples_mixed == 0;
756 
757     /*
758      * Upsampling may leave one audio frame in the resample buffer. Decrement
759      * total_in by one if there was a leftover frame from the previous resample
760      * pass in the resample buffer. Increment total_in by one if the current
761      * resample pass left one frame in the resample buffer.
762      */
763     if (frames_in_max - total_in == 1) {
764         /* copy one leftover audio frame to the beginning of the buffer */
765         *sw->resample_buf.buffer = *(sw->resample_buf.buffer + total_in);
766         total_in += 1 - sw->resample_buf.pos;
767         sw->resample_buf.pos = 1;
768     } else if (total_in >= sw->resample_buf.pos) {
769         total_in -= sw->resample_buf.pos;
770         sw->resample_buf.pos = 0;
771     }
772 
773 #ifdef DEBUG_OUT
774     dolog (
775         "%s: write size %zu written %zu total mixed %zu\n",
776         SW_NAME(sw),
777         buf_len / sw->info.bytes_per_frame,
778         total_in,
779         sw->total_hw_samples_mixed
780         );
781 #endif
782 
783     return total_in * sw->info.bytes_per_frame;
784 }
785 
786 #ifdef DEBUG_AUDIO
787 static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
788 {
789     dolog("%s: bits %d, sign %d, float %d, freq %d, nchan %d\n",
790           cap, info->bits, info->is_signed, info->is_float, info->freq,
791           info->nchannels);
792 }
793 #endif
794 
795 #define DAC
796 #include "audio_template.h"
797 #undef DAC
798 #include "audio_template.h"
799 
800 /*
801  * Timer
802  */
803 static int audio_is_timer_needed(AudioState *s)
804 {
805     HWVoiceIn *hwi = NULL;
806     HWVoiceOut *hwo = NULL;
807 
808     while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
809         if (!hwo->poll_mode) {
810             return 1;
811         }
812     }
813     while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
814         if (!hwi->poll_mode) {
815             return 1;
816         }
817     }
818     return 0;
819 }
820 
821 static void audio_reset_timer (AudioState *s)
822 {
823     if (audio_is_timer_needed(s)) {
824         timer_mod_anticipate_ns(s->ts,
825             qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
826         if (!s->timer_running) {
827             s->timer_running = true;
828             s->timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
829             trace_audio_timer_start(s->period_ticks / SCALE_MS);
830         }
831     } else {
832         timer_del(s->ts);
833         if (s->timer_running) {
834             s->timer_running = false;
835             trace_audio_timer_stop();
836         }
837     }
838 }
839 
840 static void audio_timer (void *opaque)
841 {
842     int64_t now, diff;
843     AudioState *s = opaque;
844 
845     now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
846     diff = now - s->timer_last;
847     if (diff > s->period_ticks * 3 / 2) {
848         trace_audio_timer_delayed(diff / SCALE_MS);
849     }
850     s->timer_last = now;
851 
852     audio_run(s, "timer");
853     audio_reset_timer(s);
854 }
855 
856 /*
857  * Public API
858  */
859 size_t AUD_write(SWVoiceOut *sw, void *buf, size_t size)
860 {
861     HWVoiceOut *hw;
862 
863     if (!sw) {
864         /* XXX: Consider options */
865         return size;
866     }
867     hw = sw->hw;
868 
869     if (!hw->enabled) {
870         dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
871         return 0;
872     }
873 
874     if (audio_get_pdo_out(hw->s->dev)->mixing_engine) {
875         return audio_pcm_sw_write(sw, buf, size);
876     } else {
877         return hw->pcm_ops->write(hw, buf, size);
878     }
879 }
880 
881 size_t AUD_read(SWVoiceIn *sw, void *buf, size_t size)
882 {
883     HWVoiceIn *hw;
884 
885     if (!sw) {
886         /* XXX: Consider options */
887         return size;
888     }
889     hw = sw->hw;
890 
891     if (!hw->enabled) {
892         dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
893         return 0;
894     }
895 
896     if (audio_get_pdo_in(hw->s->dev)->mixing_engine) {
897         return audio_pcm_sw_read(sw, buf, size);
898     } else {
899         return hw->pcm_ops->read(hw, buf, size);
900     }
901 }
902 
903 int AUD_get_buffer_size_out(SWVoiceOut *sw)
904 {
905     return sw->hw->samples * sw->hw->info.bytes_per_frame;
906 }
907 
908 void AUD_set_active_out (SWVoiceOut *sw, int on)
909 {
910     HWVoiceOut *hw;
911 
912     if (!sw) {
913         return;
914     }
915 
916     hw = sw->hw;
917     if (sw->active != on) {
918         AudioState *s = sw->s;
919         SWVoiceOut *temp_sw;
920         SWVoiceCap *sc;
921 
922         if (on) {
923             hw->pending_disable = 0;
924             if (!hw->enabled) {
925                 hw->enabled = 1;
926                 if (s->vm_running) {
927                     if (hw->pcm_ops->enable_out) {
928                         hw->pcm_ops->enable_out(hw, true);
929                     }
930                     audio_reset_timer (s);
931                 }
932             }
933         } else {
934             if (hw->enabled) {
935                 int nb_active = 0;
936 
937                 for (temp_sw = hw->sw_head.lh_first; temp_sw;
938                      temp_sw = temp_sw->entries.le_next) {
939                     nb_active += temp_sw->active != 0;
940                 }
941 
942                 hw->pending_disable = nb_active == 1;
943             }
944         }
945 
946         for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
947             sc->sw.active = hw->enabled;
948             if (hw->enabled) {
949                 audio_capture_maybe_changed (sc->cap, 1);
950             }
951         }
952         sw->active = on;
953     }
954 }
955 
956 void AUD_set_active_in (SWVoiceIn *sw, int on)
957 {
958     HWVoiceIn *hw;
959 
960     if (!sw) {
961         return;
962     }
963 
964     hw = sw->hw;
965     if (sw->active != on) {
966         AudioState *s = sw->s;
967         SWVoiceIn *temp_sw;
968 
969         if (on) {
970             if (!hw->enabled) {
971                 hw->enabled = 1;
972                 if (s->vm_running) {
973                     if (hw->pcm_ops->enable_in) {
974                         hw->pcm_ops->enable_in(hw, true);
975                     }
976                     audio_reset_timer (s);
977                 }
978             }
979             sw->total_hw_samples_acquired = hw->total_samples_captured;
980         } else {
981             if (hw->enabled) {
982                 int nb_active = 0;
983 
984                 for (temp_sw = hw->sw_head.lh_first; temp_sw;
985                      temp_sw = temp_sw->entries.le_next) {
986                     nb_active += temp_sw->active != 0;
987                 }
988 
989                 if (nb_active == 1) {
990                     hw->enabled = 0;
991                     if (hw->pcm_ops->enable_in) {
992                         hw->pcm_ops->enable_in(hw, false);
993                     }
994                 }
995             }
996         }
997         sw->active = on;
998     }
999 }
1000 
1001 static size_t audio_get_avail (SWVoiceIn *sw)
1002 {
1003     size_t live;
1004 
1005     if (!sw) {
1006         return 0;
1007     }
1008 
1009     live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
1010     if (audio_bug(__func__, live > sw->hw->conv_buf.size)) {
1011         dolog("live=%zu sw->hw->conv_buf.size=%zu\n", live,
1012               sw->hw->conv_buf.size);
1013         return 0;
1014     }
1015 
1016     ldebug (
1017         "%s: get_avail live %zu frontend frames %u\n",
1018         SW_NAME (sw),
1019         live, st_rate_frames_out(sw->rate, live)
1020         );
1021 
1022     return live;
1023 }
1024 
1025 static size_t audio_get_free(SWVoiceOut *sw)
1026 {
1027     size_t live, dead;
1028 
1029     if (!sw) {
1030         return 0;
1031     }
1032 
1033     live = sw->total_hw_samples_mixed;
1034 
1035     if (audio_bug(__func__, live > sw->hw->mix_buf.size)) {
1036         dolog("live=%zu sw->hw->mix_buf.size=%zu\n", live,
1037               sw->hw->mix_buf.size);
1038         return 0;
1039     }
1040 
1041     dead = sw->hw->mix_buf.size - live;
1042 
1043 #ifdef DEBUG_OUT
1044     dolog("%s: get_free live %zu dead %zu frontend frames %u\n",
1045           SW_NAME(sw), live, dead, st_rate_frames_in(sw->rate, dead));
1046 #endif
1047 
1048     return dead;
1049 }
1050 
1051 static void audio_capture_mix_and_clear(HWVoiceOut *hw, size_t rpos,
1052                                         size_t samples)
1053 {
1054     size_t n;
1055 
1056     if (hw->enabled) {
1057         SWVoiceCap *sc;
1058 
1059         for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1060             SWVoiceOut *sw = &sc->sw;
1061             size_t rpos2 = rpos;
1062 
1063             n = samples;
1064             while (n) {
1065                 size_t till_end_of_hw = hw->mix_buf.size - rpos2;
1066                 size_t to_read = MIN(till_end_of_hw, n);
1067                 size_t live, frames_in, frames_out;
1068 
1069                 sw->resample_buf.buffer = hw->mix_buf.buffer + rpos2;
1070                 sw->resample_buf.size = to_read;
1071                 live = sw->total_hw_samples_mixed;
1072 
1073                 audio_pcm_sw_resample_out(sw,
1074                                           to_read, sw->hw->mix_buf.size - live,
1075                                           &frames_in, &frames_out);
1076 
1077                 sw->total_hw_samples_mixed += frames_out;
1078                 sw->empty = sw->total_hw_samples_mixed == 0;
1079 
1080                 if (to_read - frames_in) {
1081                     dolog("Could not mix %zu frames into a capture "
1082                           "buffer, mixed %zu\n",
1083                           to_read, frames_in);
1084                     break;
1085                 }
1086                 n -= to_read;
1087                 rpos2 = (rpos2 + to_read) % hw->mix_buf.size;
1088             }
1089         }
1090     }
1091 
1092     n = MIN(samples, hw->mix_buf.size - rpos);
1093     mixeng_clear(hw->mix_buf.buffer + rpos, n);
1094     mixeng_clear(hw->mix_buf.buffer, samples - n);
1095 }
1096 
1097 static size_t audio_pcm_hw_run_out(HWVoiceOut *hw, size_t live)
1098 {
1099     size_t clipped = 0;
1100 
1101     while (live) {
1102         size_t size = live * hw->info.bytes_per_frame;
1103         size_t decr, proc;
1104         void *buf = hw->pcm_ops->get_buffer_out(hw, &size);
1105 
1106         if (size == 0) {
1107             break;
1108         }
1109 
1110         decr = MIN(size / hw->info.bytes_per_frame, live);
1111         if (buf) {
1112             audio_pcm_hw_clip_out(hw, buf, decr);
1113         }
1114         proc = hw->pcm_ops->put_buffer_out(hw, buf,
1115                                            decr * hw->info.bytes_per_frame) /
1116             hw->info.bytes_per_frame;
1117 
1118         live -= proc;
1119         clipped += proc;
1120         hw->mix_buf.pos = (hw->mix_buf.pos + proc) % hw->mix_buf.size;
1121 
1122         if (proc == 0 || proc < decr) {
1123             break;
1124         }
1125     }
1126 
1127     if (hw->pcm_ops->run_buffer_out) {
1128         hw->pcm_ops->run_buffer_out(hw);
1129     }
1130 
1131     return clipped;
1132 }
1133 
1134 static void audio_run_out (AudioState *s)
1135 {
1136     HWVoiceOut *hw = NULL;
1137     SWVoiceOut *sw;
1138 
1139     while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1140         size_t played, live, prev_rpos;
1141         size_t hw_free = audio_pcm_hw_get_free(hw);
1142         int nb_live;
1143 
1144         if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1145             /* there is exactly 1 sw for each hw with no mixeng */
1146             sw = hw->sw_head.lh_first;
1147 
1148             if (hw->pending_disable) {
1149                 hw->enabled = 0;
1150                 hw->pending_disable = 0;
1151                 if (hw->pcm_ops->enable_out) {
1152                     hw->pcm_ops->enable_out(hw, false);
1153                 }
1154             }
1155 
1156             if (sw->active) {
1157                 sw->callback.fn(sw->callback.opaque,
1158                                 hw_free * sw->info.bytes_per_frame);
1159             }
1160 
1161             if (hw->pcm_ops->run_buffer_out) {
1162                 hw->pcm_ops->run_buffer_out(hw);
1163             }
1164 
1165             continue;
1166         }
1167 
1168         for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1169             if (sw->active) {
1170                 size_t sw_free = audio_get_free(sw);
1171                 size_t free;
1172 
1173                 if (hw_free > sw->total_hw_samples_mixed) {
1174                     free = st_rate_frames_in(sw->rate,
1175                         MIN(sw_free, hw_free - sw->total_hw_samples_mixed));
1176                 } else {
1177                     free = 0;
1178                 }
1179                 if (free > sw->resample_buf.pos) {
1180                     free = MIN(free, sw->resample_buf.size)
1181                            - sw->resample_buf.pos;
1182                     sw->callback.fn(sw->callback.opaque,
1183                                     free * sw->info.bytes_per_frame);
1184                 }
1185             }
1186         }
1187 
1188         live = audio_pcm_hw_get_live_out (hw, &nb_live);
1189         if (!nb_live) {
1190             live = 0;
1191         }
1192 
1193         if (audio_bug(__func__, live > hw->mix_buf.size)) {
1194             dolog("live=%zu hw->mix_buf.size=%zu\n", live, hw->mix_buf.size);
1195             continue;
1196         }
1197 
1198         if (hw->pending_disable && !nb_live) {
1199             SWVoiceCap *sc;
1200 #ifdef DEBUG_OUT
1201             dolog ("Disabling voice\n");
1202 #endif
1203             hw->enabled = 0;
1204             hw->pending_disable = 0;
1205             if (hw->pcm_ops->enable_out) {
1206                 hw->pcm_ops->enable_out(hw, false);
1207             }
1208             for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1209                 sc->sw.active = 0;
1210                 audio_recalc_and_notify_capture (sc->cap);
1211             }
1212             continue;
1213         }
1214 
1215         if (!live) {
1216             if (hw->pcm_ops->run_buffer_out) {
1217                 hw->pcm_ops->run_buffer_out(hw);
1218             }
1219             continue;
1220         }
1221 
1222         prev_rpos = hw->mix_buf.pos;
1223         played = audio_pcm_hw_run_out(hw, live);
1224         replay_audio_out(&played);
1225         if (audio_bug(__func__, hw->mix_buf.pos >= hw->mix_buf.size)) {
1226             dolog("hw->mix_buf.pos=%zu hw->mix_buf.size=%zu played=%zu\n",
1227                   hw->mix_buf.pos, hw->mix_buf.size, played);
1228             hw->mix_buf.pos = 0;
1229         }
1230 
1231 #ifdef DEBUG_OUT
1232         dolog("played=%zu\n", played);
1233 #endif
1234 
1235         if (played) {
1236             hw->ts_helper += played;
1237             audio_capture_mix_and_clear (hw, prev_rpos, played);
1238         }
1239 
1240         for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1241             if (!sw->active && sw->empty) {
1242                 continue;
1243             }
1244 
1245             if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1246                 dolog("played=%zu sw->total_hw_samples_mixed=%zu\n",
1247                       played, sw->total_hw_samples_mixed);
1248                 played = sw->total_hw_samples_mixed;
1249             }
1250 
1251             sw->total_hw_samples_mixed -= played;
1252 
1253             if (!sw->total_hw_samples_mixed) {
1254                 sw->empty = 1;
1255             }
1256         }
1257     }
1258 }
1259 
1260 static size_t audio_pcm_hw_run_in(HWVoiceIn *hw, size_t samples)
1261 {
1262     size_t conv = 0;
1263 
1264     if (hw->pcm_ops->run_buffer_in) {
1265         hw->pcm_ops->run_buffer_in(hw);
1266     }
1267 
1268     while (samples) {
1269         size_t proc;
1270         size_t size = samples * hw->info.bytes_per_frame;
1271         void *buf = hw->pcm_ops->get_buffer_in(hw, &size);
1272 
1273         assert(size % hw->info.bytes_per_frame == 0);
1274         if (size == 0) {
1275             break;
1276         }
1277 
1278         proc = audio_pcm_hw_conv_in(hw, buf, size / hw->info.bytes_per_frame);
1279 
1280         samples -= proc;
1281         conv += proc;
1282         hw->pcm_ops->put_buffer_in(hw, buf, proc * hw->info.bytes_per_frame);
1283     }
1284 
1285     return conv;
1286 }
1287 
1288 static void audio_run_in (AudioState *s)
1289 {
1290     HWVoiceIn *hw = NULL;
1291 
1292     if (!audio_get_pdo_in(s->dev)->mixing_engine) {
1293         while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1294             /* there is exactly 1 sw for each hw with no mixeng */
1295             SWVoiceIn *sw = hw->sw_head.lh_first;
1296             if (sw->active) {
1297                 sw->callback.fn(sw->callback.opaque, INT_MAX);
1298             }
1299         }
1300         return;
1301     }
1302 
1303     while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1304         SWVoiceIn *sw;
1305         size_t captured = 0, min;
1306 
1307         if (replay_mode != REPLAY_MODE_PLAY) {
1308             captured = audio_pcm_hw_run_in(
1309                 hw, hw->conv_buf.size - audio_pcm_hw_get_live_in(hw));
1310         }
1311         replay_audio_in(&captured, hw->conv_buf.buffer, &hw->conv_buf.pos,
1312                         hw->conv_buf.size);
1313 
1314         min = audio_pcm_hw_find_min_in (hw);
1315         hw->total_samples_captured += captured - min;
1316         hw->ts_helper += captured;
1317 
1318         for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1319             sw->total_hw_samples_acquired -= min;
1320 
1321             if (sw->active) {
1322                 size_t sw_avail = audio_get_avail(sw);
1323                 size_t avail;
1324 
1325                 avail = st_rate_frames_out(sw->rate, sw_avail);
1326                 if (avail > 0) {
1327                     avail = MIN(avail, sw->resample_buf.size);
1328                     sw->callback.fn(sw->callback.opaque,
1329                                     avail * sw->info.bytes_per_frame);
1330                 }
1331             }
1332         }
1333     }
1334 }
1335 
1336 static void audio_run_capture (AudioState *s)
1337 {
1338     CaptureVoiceOut *cap;
1339 
1340     for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1341         size_t live, rpos, captured;
1342         HWVoiceOut *hw = &cap->hw;
1343         SWVoiceOut *sw;
1344 
1345         captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1346         rpos = hw->mix_buf.pos;
1347         while (live) {
1348             size_t left = hw->mix_buf.size - rpos;
1349             size_t to_capture = MIN(live, left);
1350             struct st_sample *src;
1351             struct capture_callback *cb;
1352 
1353             src = hw->mix_buf.buffer + rpos;
1354             hw->clip (cap->buf, src, to_capture);
1355             mixeng_clear (src, to_capture);
1356 
1357             for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1358                 cb->ops.capture (cb->opaque, cap->buf,
1359                                  to_capture * hw->info.bytes_per_frame);
1360             }
1361             rpos = (rpos + to_capture) % hw->mix_buf.size;
1362             live -= to_capture;
1363         }
1364         hw->mix_buf.pos = rpos;
1365 
1366         for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1367             if (!sw->active && sw->empty) {
1368                 continue;
1369             }
1370 
1371             if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1372                 dolog("captured=%zu sw->total_hw_samples_mixed=%zu\n",
1373                       captured, sw->total_hw_samples_mixed);
1374                 captured = sw->total_hw_samples_mixed;
1375             }
1376 
1377             sw->total_hw_samples_mixed -= captured;
1378             sw->empty = sw->total_hw_samples_mixed == 0;
1379         }
1380     }
1381 }
1382 
1383 void audio_run(AudioState *s, const char *msg)
1384 {
1385     audio_run_out(s);
1386     audio_run_in(s);
1387     audio_run_capture(s);
1388 
1389 #ifdef DEBUG_POLL
1390     {
1391         static double prevtime;
1392         double currtime;
1393         struct timeval tv;
1394 
1395         if (gettimeofday (&tv, NULL)) {
1396             perror ("audio_run: gettimeofday");
1397             return;
1398         }
1399 
1400         currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1401         dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1402         prevtime = currtime;
1403     }
1404 #endif
1405 }
1406 
1407 void audio_generic_run_buffer_in(HWVoiceIn *hw)
1408 {
1409     if (unlikely(!hw->buf_emul)) {
1410         hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1411         hw->buf_emul = g_malloc(hw->size_emul);
1412         hw->pos_emul = hw->pending_emul = 0;
1413     }
1414 
1415     while (hw->pending_emul < hw->size_emul) {
1416         size_t read_len = MIN(hw->size_emul - hw->pos_emul,
1417                               hw->size_emul - hw->pending_emul);
1418         size_t read = hw->pcm_ops->read(hw, hw->buf_emul + hw->pos_emul,
1419                                         read_len);
1420         hw->pending_emul += read;
1421         hw->pos_emul = (hw->pos_emul + read) % hw->size_emul;
1422         if (read < read_len) {
1423             break;
1424         }
1425     }
1426 }
1427 
1428 void *audio_generic_get_buffer_in(HWVoiceIn *hw, size_t *size)
1429 {
1430     size_t start;
1431 
1432     start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1433     assert(start < hw->size_emul);
1434 
1435     *size = MIN(*size, hw->pending_emul);
1436     *size = MIN(*size, hw->size_emul - start);
1437     return hw->buf_emul + start;
1438 }
1439 
1440 void audio_generic_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
1441 {
1442     assert(size <= hw->pending_emul);
1443     hw->pending_emul -= size;
1444 }
1445 
1446 size_t audio_generic_buffer_get_free(HWVoiceOut *hw)
1447 {
1448     if (hw->buf_emul) {
1449         return hw->size_emul - hw->pending_emul;
1450     } else {
1451         return hw->samples * hw->info.bytes_per_frame;
1452     }
1453 }
1454 
1455 void audio_generic_run_buffer_out(HWVoiceOut *hw)
1456 {
1457     while (hw->pending_emul) {
1458         size_t write_len, written, start;
1459 
1460         start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1461         assert(start < hw->size_emul);
1462 
1463         write_len = MIN(hw->pending_emul, hw->size_emul - start);
1464 
1465         written = hw->pcm_ops->write(hw, hw->buf_emul + start, write_len);
1466         hw->pending_emul -= written;
1467 
1468         if (written < write_len) {
1469             break;
1470         }
1471     }
1472 }
1473 
1474 void *audio_generic_get_buffer_out(HWVoiceOut *hw, size_t *size)
1475 {
1476     if (unlikely(!hw->buf_emul)) {
1477         hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1478         hw->buf_emul = g_malloc(hw->size_emul);
1479         hw->pos_emul = hw->pending_emul = 0;
1480     }
1481 
1482     *size = MIN(hw->size_emul - hw->pending_emul,
1483                 hw->size_emul - hw->pos_emul);
1484     return hw->buf_emul + hw->pos_emul;
1485 }
1486 
1487 size_t audio_generic_put_buffer_out(HWVoiceOut *hw, void *buf, size_t size)
1488 {
1489     assert(buf == hw->buf_emul + hw->pos_emul &&
1490            size + hw->pending_emul <= hw->size_emul);
1491 
1492     hw->pending_emul += size;
1493     hw->pos_emul = (hw->pos_emul + size) % hw->size_emul;
1494 
1495     return size;
1496 }
1497 
1498 size_t audio_generic_write(HWVoiceOut *hw, void *buf, size_t size)
1499 {
1500     size_t total = 0;
1501 
1502     if (hw->pcm_ops->buffer_get_free) {
1503         size_t free = hw->pcm_ops->buffer_get_free(hw);
1504 
1505         size = MIN(size, free);
1506     }
1507 
1508     while (total < size) {
1509         size_t dst_size = size - total;
1510         size_t copy_size, proc;
1511         void *dst = hw->pcm_ops->get_buffer_out(hw, &dst_size);
1512 
1513         if (dst_size == 0) {
1514             break;
1515         }
1516 
1517         copy_size = MIN(size - total, dst_size);
1518         if (dst) {
1519             memcpy(dst, (char *)buf + total, copy_size);
1520         }
1521         proc = hw->pcm_ops->put_buffer_out(hw, dst, copy_size);
1522         total += proc;
1523 
1524         if (proc == 0 || proc < copy_size) {
1525             break;
1526         }
1527     }
1528 
1529     return total;
1530 }
1531 
1532 size_t audio_generic_read(HWVoiceIn *hw, void *buf, size_t size)
1533 {
1534     size_t total = 0;
1535 
1536     if (hw->pcm_ops->run_buffer_in) {
1537         hw->pcm_ops->run_buffer_in(hw);
1538     }
1539 
1540     while (total < size) {
1541         size_t src_size = size - total;
1542         void *src = hw->pcm_ops->get_buffer_in(hw, &src_size);
1543 
1544         if (src_size == 0) {
1545             break;
1546         }
1547 
1548         memcpy((char *)buf + total, src, src_size);
1549         hw->pcm_ops->put_buffer_in(hw, src, src_size);
1550         total += src_size;
1551     }
1552 
1553     return total;
1554 }
1555 
1556 static int audio_driver_init(AudioState *s, struct audio_driver *drv,
1557                              bool msg, Audiodev *dev)
1558 {
1559     Error *local_err = NULL;
1560 
1561     s->drv_opaque = drv->init(dev, &local_err);
1562 
1563     if (s->drv_opaque) {
1564         if (!drv->pcm_ops->get_buffer_in) {
1565             drv->pcm_ops->get_buffer_in = audio_generic_get_buffer_in;
1566             drv->pcm_ops->put_buffer_in = audio_generic_put_buffer_in;
1567         }
1568         if (!drv->pcm_ops->get_buffer_out) {
1569             drv->pcm_ops->get_buffer_out = audio_generic_get_buffer_out;
1570             drv->pcm_ops->put_buffer_out = audio_generic_put_buffer_out;
1571         }
1572 
1573         audio_init_nb_voices_out(s, drv, 1);
1574         audio_init_nb_voices_in(s, drv, 0);
1575         s->drv = drv;
1576         return 0;
1577     } else {
1578         if (!msg) {
1579             error_free(local_err);
1580         } else if (local_err) {
1581             error_report_err(local_err);
1582         } else {
1583             error_report("Could not init `%s' audio driver", drv->name);
1584         }
1585         return -1;
1586     }
1587 }
1588 
1589 static void audio_vm_change_state_handler (void *opaque, bool running,
1590                                            RunState state)
1591 {
1592     AudioState *s = opaque;
1593     HWVoiceOut *hwo = NULL;
1594     HWVoiceIn *hwi = NULL;
1595 
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);
1600         }
1601     }
1602 
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);
1606         }
1607     }
1608     audio_reset_timer (s);
1609 }
1610 
1611 static void free_audio_state(AudioState *s)
1612 {
1613     HWVoiceOut *hwo, *hwon;
1614     HWVoiceIn *hwi, *hwin;
1615 
1616     QLIST_FOREACH_SAFE(hwo, &s->hw_head_out, entries, hwon) {
1617         SWVoiceCap *sc;
1618 
1619         if (hwo->enabled && hwo->pcm_ops->enable_out) {
1620             hwo->pcm_ops->enable_out(hwo, false);
1621         }
1622         hwo->pcm_ops->fini_out (hwo);
1623 
1624         for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1625             CaptureVoiceOut *cap = sc->cap;
1626             struct capture_callback *cb;
1627 
1628             for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1629                 cb->ops.destroy (cb->opaque);
1630             }
1631         }
1632         QLIST_REMOVE(hwo, entries);
1633     }
1634 
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);
1638         }
1639         hwi->pcm_ops->fini_in (hwi);
1640         QLIST_REMOVE(hwi, entries);
1641     }
1642 
1643     if (s->drv) {
1644         s->drv->fini (s->drv_opaque);
1645         s->drv = NULL;
1646     }
1647 
1648     if (s->dev) {
1649         qapi_free_Audiodev(s->dev);
1650         s->dev = NULL;
1651     }
1652 
1653     if (s->ts) {
1654         timer_free(s->ts);
1655         s->ts = NULL;
1656     }
1657 
1658     g_free(s);
1659 }
1660 
1661 void audio_cleanup(void)
1662 {
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);
1667     }
1668 }
1669 
1670 static bool vmstate_audio_needed(void *opaque)
1671 {
1672     /*
1673      * Never needed, this vmstate only exists in case
1674      * an old qemu sends it to us.
1675      */
1676     return false;
1677 }
1678 
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()
1686     }
1687 };
1688 
1689 static void audio_validate_opts(Audiodev *dev, Error **errp);
1690 
1691 static AudiodevListEntry *audiodev_find(
1692     AudiodevListHead *head, const char *drvname)
1693 {
1694     AudiodevListEntry *e;
1695     QSIMPLEQ_FOREACH(e, head, next) {
1696         if (strcmp(AudiodevDriver_str(e->dev->driver), drvname) == 0) {
1697             return e;
1698         }
1699     }
1700 
1701     return NULL;
1702 }
1703 
1704 /*
1705  * if we have dev, this function was called because of an -audiodev argument =>
1706  *   initialize a new state with it
1707  * if dev == NULL => legacy implicit initialization, return the already created
1708  *   state or create a new one
1709  */
1710 static AudioState *audio_init(Audiodev *dev, const char *name)
1711 {
1712     static bool atexit_registered;
1713     size_t i;
1714     int done = 0;
1715     const char *drvname = NULL;
1716     VMChangeStateEntry *vmse;
1717     AudioState *s;
1718     struct audio_driver *driver;
1719     /* silence gcc warning about uninitialized variable */
1720     AudiodevListHead head = QSIMPLEQ_HEAD_INITIALIZER(head);
1721 
1722     if (using_spice) {
1723         /*
1724          * When using spice allow the spice audio driver being picked
1725          * as default.
1726          *
1727          * Temporary hack.  Using audio devices without explicit
1728          * audiodev= property is already deprecated.  Same goes for
1729          * the -soundhw switch.  Once this support gets finally
1730          * removed we can also drop the concept of a default audio
1731          * backend and this can go away.
1732          */
1733         driver = audio_driver_lookup("spice");
1734         if (driver) {
1735             driver->can_be_default = 1;
1736         }
1737     }
1738 
1739     if (dev) {
1740         /* -audiodev option */
1741         legacy_config = false;
1742         drvname = AudiodevDriver_str(dev->driver);
1743     } else if (!QTAILQ_EMPTY(&audio_states)) {
1744         if (!legacy_config) {
1745             dolog("Device %s: audiodev default parameter is deprecated, please "
1746                   "specify audiodev=%s\n", name,
1747                   QTAILQ_FIRST(&audio_states)->dev->id);
1748         }
1749         return QTAILQ_FIRST(&audio_states);
1750     } else {
1751         /* legacy implicit initialization */
1752         head = audio_handle_legacy_opts();
1753         /*
1754          * In case of legacy initialization, all Audiodevs in the list will have
1755          * the same configuration (except the driver), so it doesn't matter which
1756          * one we chose.  We need an Audiodev to set up AudioState before we can
1757          * init a driver.  Also note that dev at this point is still in the
1758          * list.
1759          */
1760         dev = QSIMPLEQ_FIRST(&head)->dev;
1761         audio_validate_opts(dev, &error_abort);
1762     }
1763 
1764     s = g_new0(AudioState, 1);
1765     s->dev = dev;
1766 
1767     QLIST_INIT (&s->hw_head_out);
1768     QLIST_INIT (&s->hw_head_in);
1769     QLIST_INIT (&s->cap_head);
1770     if (!atexit_registered) {
1771         atexit(audio_cleanup);
1772         atexit_registered = true;
1773     }
1774 
1775     s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1776 
1777     if (drvname) {
1778         driver = audio_driver_lookup(drvname);
1779         if (driver) {
1780             done = !audio_driver_init(s, driver, true, dev);
1781         } else {
1782             dolog ("Unknown audio driver `%s'\n", drvname);
1783         }
1784         if (!done) {
1785             free_audio_state(s);
1786             return NULL;
1787         }
1788     } else {
1789         for (i = 0; audio_prio_list[i]; i++) {
1790             AudiodevListEntry *e = audiodev_find(&head, audio_prio_list[i]);
1791             driver = audio_driver_lookup(audio_prio_list[i]);
1792 
1793             if (e && driver) {
1794                 s->dev = dev = e->dev;
1795                 audio_validate_opts(dev, &error_abort);
1796                 done = !audio_driver_init(s, driver, false, dev);
1797                 if (done) {
1798                     e->dev = NULL;
1799                     break;
1800                 }
1801             }
1802         }
1803     }
1804     audio_free_audiodev_list(&head);
1805 
1806     if (!done) {
1807         driver = audio_driver_lookup("none");
1808         done = !audio_driver_init(s, driver, false, dev);
1809         assert(done);
1810         dolog("warning: Using timer based audio emulation\n");
1811     }
1812 
1813     if (dev->timer_period <= 0) {
1814         s->period_ticks = 1;
1815     } else {
1816         s->period_ticks = dev->timer_period * (int64_t)SCALE_US;
1817     }
1818 
1819     vmse = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1820     if (!vmse) {
1821         dolog ("warning: Could not register change state handler\n"
1822                "(Audio can continue looping even after stopping the VM)\n");
1823     }
1824 
1825     QTAILQ_INSERT_TAIL(&audio_states, s, list);
1826     QLIST_INIT (&s->card_head);
1827     vmstate_register (NULL, 0, &vmstate_audio, s);
1828     return s;
1829 }
1830 
1831 void audio_free_audiodev_list(AudiodevListHead *head)
1832 {
1833     AudiodevListEntry *e;
1834     while ((e = QSIMPLEQ_FIRST(head))) {
1835         QSIMPLEQ_REMOVE_HEAD(head, next);
1836         qapi_free_Audiodev(e->dev);
1837         g_free(e);
1838     }
1839 }
1840 
1841 void AUD_register_card (const char *name, QEMUSoundCard *card)
1842 {
1843     if (!card->state) {
1844         card->state = audio_init(NULL, name);
1845     }
1846 
1847     card->name = g_strdup (name);
1848     memset (&card->entries, 0, sizeof (card->entries));
1849     QLIST_INSERT_HEAD(&card->state->card_head, card, entries);
1850 }
1851 
1852 void AUD_remove_card (QEMUSoundCard *card)
1853 {
1854     QLIST_REMOVE (card, entries);
1855     g_free (card->name);
1856 }
1857 
1858 static struct audio_pcm_ops capture_pcm_ops;
1859 
1860 CaptureVoiceOut *AUD_add_capture(
1861     AudioState *s,
1862     struct audsettings *as,
1863     struct audio_capture_ops *ops,
1864     void *cb_opaque
1865     )
1866 {
1867     CaptureVoiceOut *cap;
1868     struct capture_callback *cb;
1869 
1870     if (!s) {
1871         error_report("Capturing without setting an audiodev is not supported");
1872         abort();
1873     }
1874 
1875     if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1876         dolog("Can't capture with mixeng disabled\n");
1877         return NULL;
1878     }
1879 
1880     if (audio_validate_settings (as)) {
1881         dolog ("Invalid settings were passed when trying to add capture\n");
1882         audio_print_settings (as);
1883         return NULL;
1884     }
1885 
1886     cb = g_malloc0(sizeof(*cb));
1887     cb->ops = *ops;
1888     cb->opaque = cb_opaque;
1889 
1890     cap = audio_pcm_capture_find_specific(s, as);
1891     if (cap) {
1892         QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1893     } else {
1894         HWVoiceOut *hw;
1895 
1896         cap = g_malloc0(sizeof(*cap));
1897 
1898         hw = &cap->hw;
1899         hw->s = s;
1900         hw->pcm_ops = &capture_pcm_ops;
1901         QLIST_INIT (&hw->sw_head);
1902         QLIST_INIT (&cap->cb_head);
1903 
1904         /* XXX find a more elegant way */
1905         hw->samples = 4096 * 4;
1906         audio_pcm_hw_alloc_resources_out(hw);
1907 
1908         audio_pcm_init_info (&hw->info, as);
1909 
1910         cap->buf = g_malloc0_n(hw->mix_buf.size, hw->info.bytes_per_frame);
1911 
1912         if (hw->info.is_float) {
1913             hw->clip = mixeng_clip_float[hw->info.nchannels == 2];
1914         } else {
1915             hw->clip = mixeng_clip
1916                 [hw->info.nchannels == 2]
1917                 [hw->info.is_signed]
1918                 [hw->info.swap_endianness]
1919                 [audio_bits_to_index(hw->info.bits)];
1920         }
1921 
1922         QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1923         QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1924 
1925         QLIST_FOREACH(hw, &s->hw_head_out, entries) {
1926             audio_attach_capture (hw);
1927         }
1928     }
1929 
1930     return cap;
1931 }
1932 
1933 void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1934 {
1935     struct capture_callback *cb;
1936 
1937     for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1938         if (cb->opaque == cb_opaque) {
1939             cb->ops.destroy (cb_opaque);
1940             QLIST_REMOVE (cb, entries);
1941             g_free (cb);
1942 
1943             if (!cap->cb_head.lh_first) {
1944                 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
1945 
1946                 while (sw) {
1947                     SWVoiceCap *sc = (SWVoiceCap *) sw;
1948 #ifdef DEBUG_CAPTURE
1949                     dolog ("freeing %s\n", sw->name);
1950 #endif
1951 
1952                     sw1 = sw->entries.le_next;
1953                     if (sw->rate) {
1954                         st_rate_stop (sw->rate);
1955                         sw->rate = NULL;
1956                     }
1957                     QLIST_REMOVE (sw, entries);
1958                     QLIST_REMOVE (sc, entries);
1959                     g_free (sc);
1960                     sw = sw1;
1961                 }
1962                 QLIST_REMOVE (cap, entries);
1963                 g_free(cap->hw.mix_buf.buffer);
1964                 g_free (cap->buf);
1965                 g_free (cap);
1966             }
1967             return;
1968         }
1969     }
1970 }
1971 
1972 void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
1973 {
1974     Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1975     audio_set_volume_out(sw, &vol);
1976 }
1977 
1978 void audio_set_volume_out(SWVoiceOut *sw, Volume *vol)
1979 {
1980     if (sw) {
1981         HWVoiceOut *hw = sw->hw;
1982 
1983         sw->vol.mute = vol->mute;
1984         sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
1985         sw->vol.r = nominal_volume.l * vol->vol[vol->channels > 1 ? 1 : 0] /
1986             255;
1987 
1988         if (hw->pcm_ops->volume_out) {
1989             hw->pcm_ops->volume_out(hw, vol);
1990         }
1991     }
1992 }
1993 
1994 void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
1995 {
1996     Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1997     audio_set_volume_in(sw, &vol);
1998 }
1999 
2000 void audio_set_volume_in(SWVoiceIn *sw, Volume *vol)
2001 {
2002     if (sw) {
2003         HWVoiceIn *hw = sw->hw;
2004 
2005         sw->vol.mute = vol->mute;
2006         sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
2007         sw->vol.r = nominal_volume.r * vol->vol[vol->channels > 1 ? 1 : 0] /
2008             255;
2009 
2010         if (hw->pcm_ops->volume_in) {
2011             hw->pcm_ops->volume_in(hw, vol);
2012         }
2013     }
2014 }
2015 
2016 void audio_create_pdos(Audiodev *dev)
2017 {
2018     switch (dev->driver) {
2019 #define CASE(DRIVER, driver, pdo_name)                              \
2020     case AUDIODEV_DRIVER_##DRIVER:                                  \
2021         if (!dev->u.driver.in) {                                    \
2022             dev->u.driver.in = g_malloc0(                           \
2023                 sizeof(Audiodev##pdo_name##PerDirectionOptions));   \
2024         }                                                           \
2025         if (!dev->u.driver.out) {                                   \
2026             dev->u.driver.out = g_malloc0(                          \
2027                 sizeof(Audiodev##pdo_name##PerDirectionOptions));   \
2028         }                                                           \
2029         break
2030 
2031         CASE(NONE, none, );
2032 #ifdef CONFIG_AUDIO_ALSA
2033         CASE(ALSA, alsa, Alsa);
2034 #endif
2035 #ifdef CONFIG_AUDIO_COREAUDIO
2036         CASE(COREAUDIO, coreaudio, Coreaudio);
2037 #endif
2038 #ifdef CONFIG_DBUS_DISPLAY
2039         CASE(DBUS, dbus, );
2040 #endif
2041 #ifdef CONFIG_AUDIO_DSOUND
2042         CASE(DSOUND, dsound, );
2043 #endif
2044 #ifdef CONFIG_AUDIO_JACK
2045         CASE(JACK, jack, Jack);
2046 #endif
2047 #ifdef CONFIG_AUDIO_OSS
2048         CASE(OSS, oss, Oss);
2049 #endif
2050 #ifdef CONFIG_AUDIO_PA
2051         CASE(PA, pa, Pa);
2052 #endif
2053 #ifdef CONFIG_AUDIO_PIPEWIRE
2054         CASE(PIPEWIRE, pipewire, Pipewire);
2055 #endif
2056 #ifdef CONFIG_AUDIO_SDL
2057         CASE(SDL, sdl, Sdl);
2058 #endif
2059 #ifdef CONFIG_AUDIO_SNDIO
2060         CASE(SNDIO, sndio, );
2061 #endif
2062 #ifdef CONFIG_SPICE
2063         CASE(SPICE, spice, );
2064 #endif
2065         CASE(WAV, wav, );
2066 
2067     case AUDIODEV_DRIVER__MAX:
2068         abort();
2069     };
2070 }
2071 
2072 static void audio_validate_per_direction_opts(
2073     AudiodevPerDirectionOptions *pdo, Error **errp)
2074 {
2075     if (!pdo->has_mixing_engine) {
2076         pdo->has_mixing_engine = true;
2077         pdo->mixing_engine = true;
2078     }
2079     if (!pdo->has_fixed_settings) {
2080         pdo->has_fixed_settings = true;
2081         pdo->fixed_settings = pdo->mixing_engine;
2082     }
2083     if (!pdo->fixed_settings &&
2084         (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
2085         error_setg(errp,
2086                    "You can't use frequency, channels or format with fixed-settings=off");
2087         return;
2088     }
2089     if (!pdo->mixing_engine && pdo->fixed_settings) {
2090         error_setg(errp, "You can't use fixed-settings without mixeng");
2091         return;
2092     }
2093 
2094     if (!pdo->has_frequency) {
2095         pdo->has_frequency = true;
2096         pdo->frequency = 44100;
2097     }
2098     if (!pdo->has_channels) {
2099         pdo->has_channels = true;
2100         pdo->channels = 2;
2101     }
2102     if (!pdo->has_voices) {
2103         pdo->has_voices = true;
2104         pdo->voices = pdo->mixing_engine ? 1 : INT_MAX;
2105     }
2106     if (!pdo->has_format) {
2107         pdo->has_format = true;
2108         pdo->format = AUDIO_FORMAT_S16;
2109     }
2110 }
2111 
2112 static void audio_validate_opts(Audiodev *dev, Error **errp)
2113 {
2114     Error *err = NULL;
2115 
2116     audio_create_pdos(dev);
2117 
2118     audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
2119     if (err) {
2120         error_propagate(errp, err);
2121         return;
2122     }
2123 
2124     audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
2125     if (err) {
2126         error_propagate(errp, err);
2127         return;
2128     }
2129 
2130     if (!dev->has_timer_period) {
2131         dev->has_timer_period = true;
2132         dev->timer_period = 10000; /* 100Hz -> 10ms */
2133     }
2134 }
2135 
2136 void audio_help(void)
2137 {
2138     int i;
2139 
2140     printf("Available audio drivers:\n");
2141 
2142     for (i = 0; i < AUDIODEV_DRIVER__MAX; i++) {
2143         audio_driver *driver = audio_driver_lookup(AudiodevDriver_str(i));
2144         if (driver) {
2145             printf("%s\n", driver->name);
2146         }
2147     }
2148 }
2149 
2150 void audio_parse_option(const char *opt)
2151 {
2152     Audiodev *dev = NULL;
2153 
2154     if (is_help_option(opt)) {
2155         audio_help();
2156         exit(EXIT_SUCCESS);
2157     }
2158     Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
2159     visit_type_Audiodev(v, NULL, &dev, &error_fatal);
2160     visit_free(v);
2161 
2162     audio_define(dev);
2163 }
2164 
2165 void audio_define(Audiodev *dev)
2166 {
2167     AudiodevListEntry *e;
2168 
2169     audio_validate_opts(dev, &error_fatal);
2170 
2171     e = g_new0(AudiodevListEntry, 1);
2172     e->dev = dev;
2173     QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
2174 }
2175 
2176 bool audio_init_audiodevs(void)
2177 {
2178     AudiodevListEntry *e;
2179 
2180     QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2181         if (!audio_init(e->dev, NULL)) {
2182             return false;
2183         }
2184     }
2185 
2186     return true;
2187 }
2188 
2189 audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
2190 {
2191     return (audsettings) {
2192         .freq = pdo->frequency,
2193         .nchannels = pdo->channels,
2194         .fmt = pdo->format,
2195         .endianness = AUDIO_HOST_ENDIANNESS,
2196     };
2197 }
2198 
2199 int audioformat_bytes_per_sample(AudioFormat fmt)
2200 {
2201     switch (fmt) {
2202     case AUDIO_FORMAT_U8:
2203     case AUDIO_FORMAT_S8:
2204         return 1;
2205 
2206     case AUDIO_FORMAT_U16:
2207     case AUDIO_FORMAT_S16:
2208         return 2;
2209 
2210     case AUDIO_FORMAT_U32:
2211     case AUDIO_FORMAT_S32:
2212     case AUDIO_FORMAT_F32:
2213         return 4;
2214 
2215     case AUDIO_FORMAT__MAX:
2216         ;
2217     }
2218     abort();
2219 }
2220 
2221 
2222 /* frames = freq * usec / 1e6 */
2223 int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
2224                         audsettings *as, int def_usecs)
2225 {
2226     uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
2227     return (as->freq * usecs + 500000) / 1000000;
2228 }
2229 
2230 /* samples = channels * frames = channels * freq * usec / 1e6 */
2231 int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
2232                          audsettings *as, int def_usecs)
2233 {
2234     return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
2235 }
2236 
2237 /*
2238  * bytes = bytes_per_sample * samples =
2239  *     bytes_per_sample * channels * freq * usec / 1e6
2240  */
2241 int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
2242                        audsettings *as, int def_usecs)
2243 {
2244     return audio_buffer_samples(pdo, as, def_usecs) *
2245         audioformat_bytes_per_sample(as->fmt);
2246 }
2247 
2248 AudioState *audio_state_by_name(const char *name, Error **errp)
2249 {
2250     AudioState *s;
2251     QTAILQ_FOREACH(s, &audio_states, list) {
2252         assert(s->dev);
2253         if (strcmp(name, s->dev->id) == 0) {
2254             return s;
2255         }
2256     }
2257     error_setg(errp, "audiodev '%s' not found", name);
2258     return NULL;
2259 }
2260 
2261 const char *audio_get_id(QEMUSoundCard *card)
2262 {
2263     if (card->state) {
2264         assert(card->state->dev);
2265         return card->state->dev->id;
2266     } else {
2267         return "";
2268     }
2269 }
2270 
2271 const char *audio_application_name(void)
2272 {
2273     const char *vm_name;
2274 
2275     vm_name = qemu_get_vm_name();
2276     return vm_name ? vm_name : "qemu";
2277 }
2278 
2279 void audio_rate_start(RateCtl *rate)
2280 {
2281     memset(rate, 0, sizeof(RateCtl));
2282     rate->start_ticks = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2283 }
2284 
2285 size_t audio_rate_peek_bytes(RateCtl *rate, struct audio_pcm_info *info)
2286 {
2287     int64_t now;
2288     int64_t ticks;
2289     int64_t bytes;
2290     int64_t frames;
2291 
2292     now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2293     ticks = now - rate->start_ticks;
2294     bytes = muldiv64(ticks, info->bytes_per_second, NANOSECONDS_PER_SECOND);
2295     frames = (bytes - rate->bytes_sent) / info->bytes_per_frame;
2296     if (frames < 0 || frames > 65536) {
2297         AUD_log(NULL, "Resetting rate control (%" PRId64 " frames)\n", frames);
2298         audio_rate_start(rate);
2299         frames = 0;
2300     }
2301 
2302     return frames * info->bytes_per_frame;
2303 }
2304 
2305 void audio_rate_add_bytes(RateCtl *rate, size_t bytes_used)
2306 {
2307     rate->bytes_sent += bytes_used;
2308 }
2309 
2310 size_t audio_rate_get_bytes(RateCtl *rate, struct audio_pcm_info *info,
2311                             size_t bytes_avail)
2312 {
2313     size_t bytes;
2314 
2315     bytes = audio_rate_peek_bytes(rate, info);
2316     bytes = MIN(bytes, bytes_avail);
2317     audio_rate_add_bytes(rate, bytes);
2318 
2319     return bytes;
2320 }
2321 
2322 AudiodevList *qmp_query_audiodevs(Error **errp)
2323 {
2324     AudiodevList *ret = NULL;
2325     AudiodevListEntry *e;
2326     QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2327         QAPI_LIST_PREPEND(ret, QAPI_CLONE(Audiodev, e->dev));
2328     }
2329     return ret;
2330 }
2331