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