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