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