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