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