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