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