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