xref: /openbmc/qemu/audio/audio.c (revision 69a80279)
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                              bool msg, Audiodev *dev)
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 (!msg) {
1581             error_free(local_err);
1582         } else if (local_err) {
1583             error_report_err(local_err);
1584         } else {
1585             error_report("Could not init `%s' audio driver", drv->name);
1586         }
1587         return -1;
1588     }
1589 }
1590 
1591 static void audio_vm_change_state_handler (void *opaque, bool running,
1592                                            RunState state)
1593 {
1594     AudioState *s = opaque;
1595     HWVoiceOut *hwo = NULL;
1596     HWVoiceIn *hwi = NULL;
1597 
1598     s->vm_running = running;
1599     while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
1600         if (hwo->pcm_ops->enable_out) {
1601             hwo->pcm_ops->enable_out(hwo, running);
1602         }
1603     }
1604 
1605     while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
1606         if (hwi->pcm_ops->enable_in) {
1607             hwi->pcm_ops->enable_in(hwi, running);
1608         }
1609     }
1610     audio_reset_timer (s);
1611 }
1612 
1613 static void free_audio_state(AudioState *s)
1614 {
1615     HWVoiceOut *hwo, *hwon;
1616     HWVoiceIn *hwi, *hwin;
1617 
1618     QLIST_FOREACH_SAFE(hwo, &s->hw_head_out, entries, hwon) {
1619         SWVoiceCap *sc;
1620 
1621         if (hwo->enabled && hwo->pcm_ops->enable_out) {
1622             hwo->pcm_ops->enable_out(hwo, false);
1623         }
1624         hwo->pcm_ops->fini_out (hwo);
1625 
1626         for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1627             CaptureVoiceOut *cap = sc->cap;
1628             struct capture_callback *cb;
1629 
1630             for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1631                 cb->ops.destroy (cb->opaque);
1632             }
1633         }
1634         QLIST_REMOVE(hwo, entries);
1635     }
1636 
1637     QLIST_FOREACH_SAFE(hwi, &s->hw_head_in, entries, hwin) {
1638         if (hwi->enabled && hwi->pcm_ops->enable_in) {
1639             hwi->pcm_ops->enable_in(hwi, false);
1640         }
1641         hwi->pcm_ops->fini_in (hwi);
1642         QLIST_REMOVE(hwi, entries);
1643     }
1644 
1645     if (s->drv) {
1646         s->drv->fini (s->drv_opaque);
1647         s->drv = NULL;
1648     }
1649 
1650     if (s->dev) {
1651         qapi_free_Audiodev(s->dev);
1652         s->dev = NULL;
1653     }
1654 
1655     if (s->ts) {
1656         timer_free(s->ts);
1657         s->ts = NULL;
1658     }
1659 
1660     g_free(s);
1661 }
1662 
1663 void audio_cleanup(void)
1664 {
1665     while (!QTAILQ_EMPTY(&audio_states)) {
1666         AudioState *s = QTAILQ_FIRST(&audio_states);
1667         QTAILQ_REMOVE(&audio_states, s, list);
1668         free_audio_state(s);
1669     }
1670 }
1671 
1672 static bool vmstate_audio_needed(void *opaque)
1673 {
1674     /*
1675      * Never needed, this vmstate only exists in case
1676      * an old qemu sends it to us.
1677      */
1678     return false;
1679 }
1680 
1681 static const VMStateDescription vmstate_audio = {
1682     .name = "audio",
1683     .version_id = 1,
1684     .minimum_version_id = 1,
1685     .needed = vmstate_audio_needed,
1686     .fields = (VMStateField[]) {
1687         VMSTATE_END_OF_LIST()
1688     }
1689 };
1690 
1691 static void audio_validate_opts(Audiodev *dev, Error **errp);
1692 
1693 static void audio_create_default_audiodevs(void)
1694 {
1695     const char *drvname = getenv("QEMU_AUDIO_DRV");
1696 
1697     /* QEMU_AUDIO_DRV=none is used by libqtest.  */
1698     if (drvname && !g_str_equal(drvname, "none")) {
1699         error_report("Please use -audiodev instead of QEMU_AUDIO_*");
1700         exit(1);
1701     }
1702 
1703     for (int i = 0; audio_prio_list[i]; i++) {
1704         if (drvname && !g_str_equal(drvname, audio_prio_list[i])) {
1705             continue;
1706         }
1707 
1708         if (audio_driver_lookup(audio_prio_list[i])) {
1709             QDict *dict = qdict_new();
1710             Audiodev *dev = NULL;
1711             AudiodevListEntry *e;
1712             Visitor *v;
1713 
1714             qdict_put_str(dict, "driver", audio_prio_list[i]);
1715             qdict_put_str(dict, "id", "#default");
1716 
1717             v = qobject_input_visitor_new_keyval(QOBJECT(dict));
1718             qobject_unref(dict);
1719             visit_type_Audiodev(v, NULL, &dev, &error_fatal);
1720             visit_free(v);
1721 
1722             audio_validate_opts(dev, &error_abort);
1723             e = g_new0(AudiodevListEntry, 1);
1724             e->dev = dev;
1725             QSIMPLEQ_INSERT_TAIL(&default_audiodevs, e, next);
1726         }
1727     }
1728 }
1729 
1730 /*
1731  * if we have dev, this function was called because of an -audiodev argument =>
1732  *   initialize a new state with it
1733  * if dev == NULL => legacy implicit initialization, return the already created
1734  *   state or create a new one
1735  */
1736 static AudioState *audio_init(Audiodev *dev)
1737 {
1738     static bool atexit_registered;
1739     int done = 0;
1740     const char *drvname;
1741     VMChangeStateEntry *vmse;
1742     AudioState *s;
1743     struct audio_driver *driver;
1744 
1745     s = g_new0(AudioState, 1);
1746 
1747     QLIST_INIT (&s->hw_head_out);
1748     QLIST_INIT (&s->hw_head_in);
1749     QLIST_INIT (&s->cap_head);
1750     if (!atexit_registered) {
1751         atexit(audio_cleanup);
1752         atexit_registered = true;
1753     }
1754 
1755     s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1756 
1757     if (dev) {
1758         /* -audiodev option */
1759         s->dev = dev;
1760         drvname = AudiodevDriver_str(dev->driver);
1761         driver = audio_driver_lookup(drvname);
1762         if (driver) {
1763             done = !audio_driver_init(s, driver, true, dev);
1764         } else {
1765             dolog ("Unknown audio driver `%s'\n", drvname);
1766         }
1767         if (!done) {
1768             goto out;
1769         }
1770     } else {
1771         for (;;) {
1772             AudiodevListEntry *e = QSIMPLEQ_FIRST(&default_audiodevs);
1773             if (!e) {
1774                 dolog("no default audio driver available\n");
1775                 goto out;
1776             }
1777             s->dev = dev = e->dev;
1778             drvname = AudiodevDriver_str(dev->driver);
1779             driver = audio_driver_lookup(drvname);
1780             if (!audio_driver_init(s, driver, false, dev)) {
1781                 break;
1782             }
1783             QSIMPLEQ_REMOVE_HEAD(&default_audiodevs, next);
1784         }
1785     }
1786 
1787     if (dev->timer_period <= 0) {
1788         s->period_ticks = 1;
1789     } else {
1790         s->period_ticks = dev->timer_period * (int64_t)SCALE_US;
1791     }
1792 
1793     vmse = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1794     if (!vmse) {
1795         dolog ("warning: Could not register change state handler\n"
1796                "(Audio can continue looping even after stopping the VM)\n");
1797     }
1798 
1799     QTAILQ_INSERT_TAIL(&audio_states, s, list);
1800     QLIST_INIT (&s->card_head);
1801     vmstate_register (NULL, 0, &vmstate_audio, s);
1802     return s;
1803 
1804 out:
1805     free_audio_state(s);
1806     return NULL;
1807 }
1808 
1809 void AUD_register_card (const char *name, QEMUSoundCard *card)
1810 {
1811     if (!card->state) {
1812         if (!QTAILQ_EMPTY(&audio_states)) {
1813             if (QSIMPLEQ_EMPTY(&default_audiodevs)) {
1814                 dolog("Device %s: audiodev default parameter is deprecated, please "
1815                       "specify audiodev=%s\n", name,
1816                       QTAILQ_FIRST(&audio_states)->dev->id);
1817             }
1818             card->state = QTAILQ_FIRST(&audio_states);
1819         } else {
1820             if (QSIMPLEQ_EMPTY(&default_audiodevs)) {
1821                 audio_create_default_audiodevs();
1822             }
1823             card->state = audio_init(NULL);
1824         }
1825     }
1826 
1827     card->name = g_strdup (name);
1828     memset (&card->entries, 0, sizeof (card->entries));
1829     QLIST_INSERT_HEAD(&card->state->card_head, card, entries);
1830 }
1831 
1832 void AUD_remove_card (QEMUSoundCard *card)
1833 {
1834     QLIST_REMOVE (card, entries);
1835     g_free (card->name);
1836 }
1837 
1838 static struct audio_pcm_ops capture_pcm_ops;
1839 
1840 CaptureVoiceOut *AUD_add_capture(
1841     AudioState *s,
1842     struct audsettings *as,
1843     struct audio_capture_ops *ops,
1844     void *cb_opaque
1845     )
1846 {
1847     CaptureVoiceOut *cap;
1848     struct capture_callback *cb;
1849 
1850     if (!s) {
1851         error_report("Capturing without setting an audiodev is not supported");
1852         abort();
1853     }
1854 
1855     if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1856         dolog("Can't capture with mixeng disabled\n");
1857         return NULL;
1858     }
1859 
1860     if (audio_validate_settings (as)) {
1861         dolog ("Invalid settings were passed when trying to add capture\n");
1862         audio_print_settings (as);
1863         return NULL;
1864     }
1865 
1866     cb = g_malloc0(sizeof(*cb));
1867     cb->ops = *ops;
1868     cb->opaque = cb_opaque;
1869 
1870     cap = audio_pcm_capture_find_specific(s, as);
1871     if (cap) {
1872         QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1873     } else {
1874         HWVoiceOut *hw;
1875 
1876         cap = g_malloc0(sizeof(*cap));
1877 
1878         hw = &cap->hw;
1879         hw->s = s;
1880         hw->pcm_ops = &capture_pcm_ops;
1881         QLIST_INIT (&hw->sw_head);
1882         QLIST_INIT (&cap->cb_head);
1883 
1884         /* XXX find a more elegant way */
1885         hw->samples = 4096 * 4;
1886         audio_pcm_hw_alloc_resources_out(hw);
1887 
1888         audio_pcm_init_info (&hw->info, as);
1889 
1890         cap->buf = g_malloc0_n(hw->mix_buf.size, hw->info.bytes_per_frame);
1891 
1892         if (hw->info.is_float) {
1893             hw->clip = mixeng_clip_float[hw->info.nchannels == 2];
1894         } else {
1895             hw->clip = mixeng_clip
1896                 [hw->info.nchannels == 2]
1897                 [hw->info.is_signed]
1898                 [hw->info.swap_endianness]
1899                 [audio_bits_to_index(hw->info.bits)];
1900         }
1901 
1902         QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1903         QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1904 
1905         QLIST_FOREACH(hw, &s->hw_head_out, entries) {
1906             audio_attach_capture (hw);
1907         }
1908     }
1909 
1910     return cap;
1911 }
1912 
1913 void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1914 {
1915     struct capture_callback *cb;
1916 
1917     for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1918         if (cb->opaque == cb_opaque) {
1919             cb->ops.destroy (cb_opaque);
1920             QLIST_REMOVE (cb, entries);
1921             g_free (cb);
1922 
1923             if (!cap->cb_head.lh_first) {
1924                 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
1925 
1926                 while (sw) {
1927                     SWVoiceCap *sc = (SWVoiceCap *) sw;
1928 #ifdef DEBUG_CAPTURE
1929                     dolog ("freeing %s\n", sw->name);
1930 #endif
1931 
1932                     sw1 = sw->entries.le_next;
1933                     if (sw->rate) {
1934                         st_rate_stop (sw->rate);
1935                         sw->rate = NULL;
1936                     }
1937                     QLIST_REMOVE (sw, entries);
1938                     QLIST_REMOVE (sc, entries);
1939                     g_free (sc);
1940                     sw = sw1;
1941                 }
1942                 QLIST_REMOVE (cap, entries);
1943                 g_free(cap->hw.mix_buf.buffer);
1944                 g_free (cap->buf);
1945                 g_free (cap);
1946             }
1947             return;
1948         }
1949     }
1950 }
1951 
1952 void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
1953 {
1954     Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1955     audio_set_volume_out(sw, &vol);
1956 }
1957 
1958 void audio_set_volume_out(SWVoiceOut *sw, Volume *vol)
1959 {
1960     if (sw) {
1961         HWVoiceOut *hw = sw->hw;
1962 
1963         sw->vol.mute = vol->mute;
1964         sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
1965         sw->vol.r = nominal_volume.l * vol->vol[vol->channels > 1 ? 1 : 0] /
1966             255;
1967 
1968         if (hw->pcm_ops->volume_out) {
1969             hw->pcm_ops->volume_out(hw, vol);
1970         }
1971     }
1972 }
1973 
1974 void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
1975 {
1976     Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1977     audio_set_volume_in(sw, &vol);
1978 }
1979 
1980 void audio_set_volume_in(SWVoiceIn *sw, Volume *vol)
1981 {
1982     if (sw) {
1983         HWVoiceIn *hw = sw->hw;
1984 
1985         sw->vol.mute = vol->mute;
1986         sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
1987         sw->vol.r = nominal_volume.r * vol->vol[vol->channels > 1 ? 1 : 0] /
1988             255;
1989 
1990         if (hw->pcm_ops->volume_in) {
1991             hw->pcm_ops->volume_in(hw, vol);
1992         }
1993     }
1994 }
1995 
1996 void audio_create_pdos(Audiodev *dev)
1997 {
1998     switch (dev->driver) {
1999 #define CASE(DRIVER, driver, pdo_name)                              \
2000     case AUDIODEV_DRIVER_##DRIVER:                                  \
2001         if (!dev->u.driver.in) {                                    \
2002             dev->u.driver.in = g_malloc0(                           \
2003                 sizeof(Audiodev##pdo_name##PerDirectionOptions));   \
2004         }                                                           \
2005         if (!dev->u.driver.out) {                                   \
2006             dev->u.driver.out = g_malloc0(                          \
2007                 sizeof(Audiodev##pdo_name##PerDirectionOptions));   \
2008         }                                                           \
2009         break
2010 
2011         CASE(NONE, none, );
2012 #ifdef CONFIG_AUDIO_ALSA
2013         CASE(ALSA, alsa, Alsa);
2014 #endif
2015 #ifdef CONFIG_AUDIO_COREAUDIO
2016         CASE(COREAUDIO, coreaudio, Coreaudio);
2017 #endif
2018 #ifdef CONFIG_DBUS_DISPLAY
2019         CASE(DBUS, dbus, );
2020 #endif
2021 #ifdef CONFIG_AUDIO_DSOUND
2022         CASE(DSOUND, dsound, );
2023 #endif
2024 #ifdef CONFIG_AUDIO_JACK
2025         CASE(JACK, jack, Jack);
2026 #endif
2027 #ifdef CONFIG_AUDIO_OSS
2028         CASE(OSS, oss, Oss);
2029 #endif
2030 #ifdef CONFIG_AUDIO_PA
2031         CASE(PA, pa, Pa);
2032 #endif
2033 #ifdef CONFIG_AUDIO_PIPEWIRE
2034         CASE(PIPEWIRE, pipewire, Pipewire);
2035 #endif
2036 #ifdef CONFIG_AUDIO_SDL
2037         CASE(SDL, sdl, Sdl);
2038 #endif
2039 #ifdef CONFIG_AUDIO_SNDIO
2040         CASE(SNDIO, sndio, );
2041 #endif
2042 #ifdef CONFIG_SPICE
2043         CASE(SPICE, spice, );
2044 #endif
2045         CASE(WAV, wav, );
2046 
2047     case AUDIODEV_DRIVER__MAX:
2048         abort();
2049     };
2050 }
2051 
2052 static void audio_validate_per_direction_opts(
2053     AudiodevPerDirectionOptions *pdo, Error **errp)
2054 {
2055     if (!pdo->has_mixing_engine) {
2056         pdo->has_mixing_engine = true;
2057         pdo->mixing_engine = true;
2058     }
2059     if (!pdo->has_fixed_settings) {
2060         pdo->has_fixed_settings = true;
2061         pdo->fixed_settings = pdo->mixing_engine;
2062     }
2063     if (!pdo->fixed_settings &&
2064         (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
2065         error_setg(errp,
2066                    "You can't use frequency, channels or format with fixed-settings=off");
2067         return;
2068     }
2069     if (!pdo->mixing_engine && pdo->fixed_settings) {
2070         error_setg(errp, "You can't use fixed-settings without mixeng");
2071         return;
2072     }
2073 
2074     if (!pdo->has_frequency) {
2075         pdo->has_frequency = true;
2076         pdo->frequency = 44100;
2077     }
2078     if (!pdo->has_channels) {
2079         pdo->has_channels = true;
2080         pdo->channels = 2;
2081     }
2082     if (!pdo->has_voices) {
2083         pdo->has_voices = true;
2084         pdo->voices = pdo->mixing_engine ? 1 : INT_MAX;
2085     }
2086     if (!pdo->has_format) {
2087         pdo->has_format = true;
2088         pdo->format = AUDIO_FORMAT_S16;
2089     }
2090 }
2091 
2092 static void audio_validate_opts(Audiodev *dev, Error **errp)
2093 {
2094     Error *err = NULL;
2095 
2096     audio_create_pdos(dev);
2097 
2098     audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
2099     if (err) {
2100         error_propagate(errp, err);
2101         return;
2102     }
2103 
2104     audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
2105     if (err) {
2106         error_propagate(errp, err);
2107         return;
2108     }
2109 
2110     if (!dev->has_timer_period) {
2111         dev->has_timer_period = true;
2112         dev->timer_period = 10000; /* 100Hz -> 10ms */
2113     }
2114 }
2115 
2116 void audio_help(void)
2117 {
2118     int i;
2119 
2120     printf("Available audio drivers:\n");
2121 
2122     for (i = 0; i < AUDIODEV_DRIVER__MAX; i++) {
2123         audio_driver *driver = audio_driver_lookup(AudiodevDriver_str(i));
2124         if (driver) {
2125             printf("%s\n", driver->name);
2126         }
2127     }
2128 }
2129 
2130 void audio_parse_option(const char *opt)
2131 {
2132     Audiodev *dev = NULL;
2133 
2134     if (is_help_option(opt)) {
2135         audio_help();
2136         exit(EXIT_SUCCESS);
2137     }
2138     Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
2139     visit_type_Audiodev(v, NULL, &dev, &error_fatal);
2140     visit_free(v);
2141 
2142     audio_define(dev);
2143 }
2144 
2145 void audio_define(Audiodev *dev)
2146 {
2147     AudiodevListEntry *e;
2148 
2149     audio_validate_opts(dev, &error_fatal);
2150 
2151     e = g_new0(AudiodevListEntry, 1);
2152     e->dev = dev;
2153     QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
2154 }
2155 
2156 bool audio_init_audiodevs(void)
2157 {
2158     AudiodevListEntry *e;
2159 
2160     QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2161         if (!audio_init(e->dev)) {
2162             return false;
2163         }
2164     }
2165 
2166     return true;
2167 }
2168 
2169 audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
2170 {
2171     return (audsettings) {
2172         .freq = pdo->frequency,
2173         .nchannels = pdo->channels,
2174         .fmt = pdo->format,
2175         .endianness = AUDIO_HOST_ENDIANNESS,
2176     };
2177 }
2178 
2179 int audioformat_bytes_per_sample(AudioFormat fmt)
2180 {
2181     switch (fmt) {
2182     case AUDIO_FORMAT_U8:
2183     case AUDIO_FORMAT_S8:
2184         return 1;
2185 
2186     case AUDIO_FORMAT_U16:
2187     case AUDIO_FORMAT_S16:
2188         return 2;
2189 
2190     case AUDIO_FORMAT_U32:
2191     case AUDIO_FORMAT_S32:
2192     case AUDIO_FORMAT_F32:
2193         return 4;
2194 
2195     case AUDIO_FORMAT__MAX:
2196         ;
2197     }
2198     abort();
2199 }
2200 
2201 
2202 /* frames = freq * usec / 1e6 */
2203 int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
2204                         audsettings *as, int def_usecs)
2205 {
2206     uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
2207     return (as->freq * usecs + 500000) / 1000000;
2208 }
2209 
2210 /* samples = channels * frames = channels * freq * usec / 1e6 */
2211 int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
2212                          audsettings *as, int def_usecs)
2213 {
2214     return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
2215 }
2216 
2217 /*
2218  * bytes = bytes_per_sample * samples =
2219  *     bytes_per_sample * channels * freq * usec / 1e6
2220  */
2221 int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
2222                        audsettings *as, int def_usecs)
2223 {
2224     return audio_buffer_samples(pdo, as, def_usecs) *
2225         audioformat_bytes_per_sample(as->fmt);
2226 }
2227 
2228 AudioState *audio_state_by_name(const char *name, Error **errp)
2229 {
2230     AudioState *s;
2231     QTAILQ_FOREACH(s, &audio_states, list) {
2232         assert(s->dev);
2233         if (strcmp(name, s->dev->id) == 0) {
2234             return s;
2235         }
2236     }
2237     error_setg(errp, "audiodev '%s' not found", name);
2238     return NULL;
2239 }
2240 
2241 const char *audio_get_id(QEMUSoundCard *card)
2242 {
2243     if (card->state) {
2244         assert(card->state->dev);
2245         return card->state->dev->id;
2246     } else {
2247         return "";
2248     }
2249 }
2250 
2251 const char *audio_application_name(void)
2252 {
2253     const char *vm_name;
2254 
2255     vm_name = qemu_get_vm_name();
2256     return vm_name ? vm_name : "qemu";
2257 }
2258 
2259 void audio_rate_start(RateCtl *rate)
2260 {
2261     memset(rate, 0, sizeof(RateCtl));
2262     rate->start_ticks = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2263 }
2264 
2265 size_t audio_rate_peek_bytes(RateCtl *rate, struct audio_pcm_info *info)
2266 {
2267     int64_t now;
2268     int64_t ticks;
2269     int64_t bytes;
2270     int64_t frames;
2271 
2272     now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2273     ticks = now - rate->start_ticks;
2274     bytes = muldiv64(ticks, info->bytes_per_second, NANOSECONDS_PER_SECOND);
2275     frames = (bytes - rate->bytes_sent) / info->bytes_per_frame;
2276     if (frames < 0 || frames > 65536) {
2277         AUD_log(NULL, "Resetting rate control (%" PRId64 " frames)\n", frames);
2278         audio_rate_start(rate);
2279         frames = 0;
2280     }
2281 
2282     return frames * info->bytes_per_frame;
2283 }
2284 
2285 void audio_rate_add_bytes(RateCtl *rate, size_t bytes_used)
2286 {
2287     rate->bytes_sent += bytes_used;
2288 }
2289 
2290 size_t audio_rate_get_bytes(RateCtl *rate, struct audio_pcm_info *info,
2291                             size_t bytes_avail)
2292 {
2293     size_t bytes;
2294 
2295     bytes = audio_rate_peek_bytes(rate, info);
2296     bytes = MIN(bytes, bytes_avail);
2297     audio_rate_add_bytes(rate, bytes);
2298 
2299     return bytes;
2300 }
2301 
2302 AudiodevList *qmp_query_audiodevs(Error **errp)
2303 {
2304     AudiodevList *ret = NULL;
2305     AudiodevListEntry *e;
2306     QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2307         QAPI_LIST_PREPEND(ret, QAPI_CLONE(Audiodev, e->dev));
2308     }
2309     return ret;
2310 }
2311