xref: /openbmc/qemu/audio/audio.c (revision 3d9569b8)
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 "hw/hw.h"
27 #include "audio.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 "sysemu/sysemu.h"
34 #include "qemu/cutils.h"
35 #include "qemu/module.h"
36 #include "sysemu/replay.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 AudioState glob_audio_state;
91 
92 const struct mixeng_volume nominal_volume = {
93     .mute = 0,
94 #ifdef FLOAT_MIXENG
95     .r = 1.0,
96     .l = 1.0,
97 #else
98     .r = 1ULL << 32,
99     .l = 1ULL << 32,
100 #endif
101 };
102 
103 #ifdef AUDIO_IS_FLAWLESS_AND_NO_CHECKS_ARE_REQURIED
104 #error No its not
105 #else
106 int audio_bug (const char *funcname, int cond)
107 {
108     if (cond) {
109         static int shown;
110 
111         AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
112         if (!shown) {
113             shown = 1;
114             AUD_log (NULL, "Save all your work and restart without audio\n");
115             AUD_log (NULL, "I am sorry\n");
116         }
117         AUD_log (NULL, "Context:\n");
118 
119 #if defined AUDIO_BREAKPOINT_ON_BUG
120 #  if defined HOST_I386
121 #    if defined __GNUC__
122         __asm__ ("int3");
123 #    elif defined _MSC_VER
124         _asm _emit 0xcc;
125 #    else
126         abort ();
127 #    endif
128 #  else
129         abort ();
130 #  endif
131 #endif
132     }
133 
134     return cond;
135 }
136 #endif
137 
138 static inline int audio_bits_to_index (int bits)
139 {
140     switch (bits) {
141     case 8:
142         return 0;
143 
144     case 16:
145         return 1;
146 
147     case 32:
148         return 2;
149 
150     default:
151         audio_bug ("bits_to_index", 1);
152         AUD_log (NULL, "invalid bits %d\n", bits);
153         return 0;
154     }
155 }
156 
157 void *audio_calloc (const char *funcname, int nmemb, size_t size)
158 {
159     int cond;
160     size_t len;
161 
162     len = nmemb * size;
163     cond = !nmemb || !size;
164     cond |= nmemb < 0;
165     cond |= len < size;
166 
167     if (audio_bug ("audio_calloc", cond)) {
168         AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
169                  funcname);
170         AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
171         return NULL;
172     }
173 
174     return g_malloc0 (len);
175 }
176 
177 void AUD_vlog (const char *cap, const char *fmt, va_list ap)
178 {
179     if (cap) {
180         fprintf(stderr, "%s: ", cap);
181     }
182 
183     vfprintf(stderr, fmt, ap);
184 }
185 
186 void AUD_log (const char *cap, const char *fmt, ...)
187 {
188     va_list ap;
189 
190     va_start (ap, fmt);
191     AUD_vlog (cap, fmt, ap);
192     va_end (ap);
193 }
194 
195 static void audio_print_settings (struct audsettings *as)
196 {
197     dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
198 
199     switch (as->fmt) {
200     case AUDIO_FORMAT_S8:
201         AUD_log (NULL, "S8");
202         break;
203     case AUDIO_FORMAT_U8:
204         AUD_log (NULL, "U8");
205         break;
206     case AUDIO_FORMAT_S16:
207         AUD_log (NULL, "S16");
208         break;
209     case AUDIO_FORMAT_U16:
210         AUD_log (NULL, "U16");
211         break;
212     case AUDIO_FORMAT_S32:
213         AUD_log (NULL, "S32");
214         break;
215     case AUDIO_FORMAT_U32:
216         AUD_log (NULL, "U32");
217         break;
218     default:
219         AUD_log (NULL, "invalid(%d)", as->fmt);
220         break;
221     }
222 
223     AUD_log (NULL, " endianness=");
224     switch (as->endianness) {
225     case 0:
226         AUD_log (NULL, "little");
227         break;
228     case 1:
229         AUD_log (NULL, "big");
230         break;
231     default:
232         AUD_log (NULL, "invalid");
233         break;
234     }
235     AUD_log (NULL, "\n");
236 }
237 
238 static int audio_validate_settings (struct audsettings *as)
239 {
240     int invalid;
241 
242     invalid = as->nchannels != 1 && as->nchannels != 2;
243     invalid |= as->endianness != 0 && as->endianness != 1;
244 
245     switch (as->fmt) {
246     case AUDIO_FORMAT_S8:
247     case AUDIO_FORMAT_U8:
248     case AUDIO_FORMAT_S16:
249     case AUDIO_FORMAT_U16:
250     case AUDIO_FORMAT_S32:
251     case AUDIO_FORMAT_U32:
252         break;
253     default:
254         invalid = 1;
255         break;
256     }
257 
258     invalid |= as->freq <= 0;
259     return invalid ? -1 : 0;
260 }
261 
262 static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
263 {
264     int bits = 8, sign = 0;
265 
266     switch (as->fmt) {
267     case AUDIO_FORMAT_S8:
268         sign = 1;
269         /* fall through */
270     case AUDIO_FORMAT_U8:
271         break;
272 
273     case AUDIO_FORMAT_S16:
274         sign = 1;
275         /* fall through */
276     case AUDIO_FORMAT_U16:
277         bits = 16;
278         break;
279 
280     case AUDIO_FORMAT_S32:
281         sign = 1;
282         /* fall through */
283     case AUDIO_FORMAT_U32:
284         bits = 32;
285         break;
286 
287     default:
288         abort();
289     }
290     return info->freq == as->freq
291         && info->nchannels == as->nchannels
292         && info->sign == sign
293         && info->bits == bits
294         && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
295 }
296 
297 void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
298 {
299     int bits = 8, sign = 0, shift = 0;
300 
301     switch (as->fmt) {
302     case AUDIO_FORMAT_S8:
303         sign = 1;
304     case AUDIO_FORMAT_U8:
305         break;
306 
307     case AUDIO_FORMAT_S16:
308         sign = 1;
309     case AUDIO_FORMAT_U16:
310         bits = 16;
311         shift = 1;
312         break;
313 
314     case AUDIO_FORMAT_S32:
315         sign = 1;
316     case AUDIO_FORMAT_U32:
317         bits = 32;
318         shift = 2;
319         break;
320 
321     default:
322         abort();
323     }
324 
325     info->freq = as->freq;
326     info->bits = bits;
327     info->sign = sign;
328     info->nchannels = as->nchannels;
329     info->shift = (as->nchannels == 2) + shift;
330     info->align = (1 << info->shift) - 1;
331     info->bytes_per_second = info->freq << info->shift;
332     info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
333 }
334 
335 void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
336 {
337     if (!len) {
338         return;
339     }
340 
341     if (info->sign) {
342         memset (buf, 0x00, len << info->shift);
343     }
344     else {
345         switch (info->bits) {
346         case 8:
347             memset (buf, 0x80, len << info->shift);
348             break;
349 
350         case 16:
351             {
352                 int i;
353                 uint16_t *p = buf;
354                 int shift = info->nchannels - 1;
355                 short s = INT16_MAX;
356 
357                 if (info->swap_endianness) {
358                     s = bswap16 (s);
359                 }
360 
361                 for (i = 0; i < len << shift; i++) {
362                     p[i] = s;
363                 }
364             }
365             break;
366 
367         case 32:
368             {
369                 int i;
370                 uint32_t *p = buf;
371                 int shift = info->nchannels - 1;
372                 int32_t s = INT32_MAX;
373 
374                 if (info->swap_endianness) {
375                     s = bswap32 (s);
376                 }
377 
378                 for (i = 0; i < len << shift; i++) {
379                     p[i] = s;
380                 }
381             }
382             break;
383 
384         default:
385             AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
386                      info->bits);
387             break;
388         }
389     }
390 }
391 
392 /*
393  * Capture
394  */
395 static void noop_conv (struct st_sample *dst, const void *src, int samples)
396 {
397     (void) src;
398     (void) dst;
399     (void) samples;
400 }
401 
402 static CaptureVoiceOut *audio_pcm_capture_find_specific (
403     struct audsettings *as
404     )
405 {
406     CaptureVoiceOut *cap;
407     AudioState *s = &glob_audio_state;
408 
409     for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
410         if (audio_pcm_info_eq (&cap->hw.info, as)) {
411             return cap;
412         }
413     }
414     return NULL;
415 }
416 
417 static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
418 {
419     struct capture_callback *cb;
420 
421 #ifdef DEBUG_CAPTURE
422     dolog ("notification %d sent\n", cmd);
423 #endif
424     for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
425         cb->ops.notify (cb->opaque, cmd);
426     }
427 }
428 
429 static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
430 {
431     if (cap->hw.enabled != enabled) {
432         audcnotification_e cmd;
433         cap->hw.enabled = enabled;
434         cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
435         audio_notify_capture (cap, cmd);
436     }
437 }
438 
439 static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
440 {
441     HWVoiceOut *hw = &cap->hw;
442     SWVoiceOut *sw;
443     int enabled = 0;
444 
445     for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
446         if (sw->active) {
447             enabled = 1;
448             break;
449         }
450     }
451     audio_capture_maybe_changed (cap, enabled);
452 }
453 
454 static void audio_detach_capture (HWVoiceOut *hw)
455 {
456     SWVoiceCap *sc = hw->cap_head.lh_first;
457 
458     while (sc) {
459         SWVoiceCap *sc1 = sc->entries.le_next;
460         SWVoiceOut *sw = &sc->sw;
461         CaptureVoiceOut *cap = sc->cap;
462         int was_active = sw->active;
463 
464         if (sw->rate) {
465             st_rate_stop (sw->rate);
466             sw->rate = NULL;
467         }
468 
469         QLIST_REMOVE (sw, entries);
470         QLIST_REMOVE (sc, entries);
471         g_free (sc);
472         if (was_active) {
473             /* We have removed soft voice from the capture:
474                this might have changed the overall status of the capture
475                since this might have been the only active voice */
476             audio_recalc_and_notify_capture (cap);
477         }
478         sc = sc1;
479     }
480 }
481 
482 static int audio_attach_capture (HWVoiceOut *hw)
483 {
484     AudioState *s = &glob_audio_state;
485     CaptureVoiceOut *cap;
486 
487     audio_detach_capture (hw);
488     for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
489         SWVoiceCap *sc;
490         SWVoiceOut *sw;
491         HWVoiceOut *hw_cap = &cap->hw;
492 
493         sc = g_malloc0(sizeof(*sc));
494 
495         sc->cap = cap;
496         sw = &sc->sw;
497         sw->hw = hw_cap;
498         sw->info = hw->info;
499         sw->empty = 1;
500         sw->active = hw->enabled;
501         sw->conv = noop_conv;
502         sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
503         sw->vol = nominal_volume;
504         sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
505         if (!sw->rate) {
506             dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
507             g_free (sw);
508             return -1;
509         }
510         QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
511         QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
512 #ifdef DEBUG_CAPTURE
513         sw->name = g_strdup_printf ("for %p %d,%d,%d",
514                                     hw, sw->info.freq, sw->info.bits,
515                                     sw->info.nchannels);
516         dolog ("Added %s active = %d\n", sw->name, sw->active);
517 #endif
518         if (sw->active) {
519             audio_capture_maybe_changed (cap, 1);
520         }
521     }
522     return 0;
523 }
524 
525 /*
526  * Hard voice (capture)
527  */
528 static int audio_pcm_hw_find_min_in (HWVoiceIn *hw)
529 {
530     SWVoiceIn *sw;
531     int m = hw->total_samples_captured;
532 
533     for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
534         if (sw->active) {
535             m = audio_MIN (m, sw->total_hw_samples_acquired);
536         }
537     }
538     return m;
539 }
540 
541 int audio_pcm_hw_get_live_in (HWVoiceIn *hw)
542 {
543     int live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
544     if (audio_bug(__func__, live < 0 || live > hw->samples)) {
545         dolog ("live=%d hw->samples=%d\n", live, hw->samples);
546         return 0;
547     }
548     return live;
549 }
550 
551 int audio_pcm_hw_clip_out (HWVoiceOut *hw, void *pcm_buf,
552                            int live, int pending)
553 {
554     int left = hw->samples - pending;
555     int len = audio_MIN (left, live);
556     int clipped = 0;
557 
558     while (len) {
559         struct st_sample *src = hw->mix_buf + hw->rpos;
560         uint8_t *dst = advance (pcm_buf, hw->rpos << hw->info.shift);
561         int samples_till_end_of_buf = hw->samples - hw->rpos;
562         int samples_to_clip = audio_MIN (len, samples_till_end_of_buf);
563 
564         hw->clip (dst, src, samples_to_clip);
565 
566         hw->rpos = (hw->rpos + samples_to_clip) % hw->samples;
567         len -= samples_to_clip;
568         clipped += samples_to_clip;
569     }
570     return clipped;
571 }
572 
573 /*
574  * Soft voice (capture)
575  */
576 static int audio_pcm_sw_get_rpos_in (SWVoiceIn *sw)
577 {
578     HWVoiceIn *hw = sw->hw;
579     int live = hw->total_samples_captured - sw->total_hw_samples_acquired;
580     int rpos;
581 
582     if (audio_bug(__func__, live < 0 || live > hw->samples)) {
583         dolog ("live=%d hw->samples=%d\n", live, hw->samples);
584         return 0;
585     }
586 
587     rpos = hw->wpos - live;
588     if (rpos >= 0) {
589         return rpos;
590     }
591     else {
592         return hw->samples + rpos;
593     }
594 }
595 
596 int audio_pcm_sw_read (SWVoiceIn *sw, void *buf, int size)
597 {
598     HWVoiceIn *hw = sw->hw;
599     int 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->samples;
603 
604     live = hw->total_samples_captured - sw->total_hw_samples_acquired;
605     if (audio_bug(__func__, live < 0 || live > hw->samples)) {
606         dolog ("live_in=%d hw->samples=%d\n", live, hw->samples);
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 = audio_MIN (swlim, samples);
617 
618     while (swlim) {
619         src = hw->conv_buf + rpos;
620         isamp = hw->wpos - rpos;
621         /* XXX: <= ? */
622         if (isamp <= 0) {
623             isamp = hw->samples - rpos;
624         }
625 
626         if (!isamp) {
627             break;
628         }
629         osamp = swlim;
630 
631         if (audio_bug(__func__, osamp < 0)) {
632             dolog ("osamp=%d\n", osamp);
633             return 0;
634         }
635 
636         st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
637         swlim -= osamp;
638         rpos = (rpos + isamp) % hw->samples;
639         dst += osamp;
640         ret += osamp;
641         total += isamp;
642     }
643 
644     if (!(hw->ctl_caps & VOICE_VOLUME_CAP)) {
645         mixeng_volume (sw->buf, ret, &sw->vol);
646     }
647 
648     sw->clip (buf, sw->buf, ret);
649     sw->total_hw_samples_acquired += total;
650     return ret << sw->info.shift;
651 }
652 
653 /*
654  * Hard voice (playback)
655  */
656 static int audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
657 {
658     SWVoiceOut *sw;
659     int m = INT_MAX;
660     int nb_live = 0;
661 
662     for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
663         if (sw->active || !sw->empty) {
664             m = audio_MIN (m, sw->total_hw_samples_mixed);
665             nb_live += 1;
666         }
667     }
668 
669     *nb_livep = nb_live;
670     return m;
671 }
672 
673 static int audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
674 {
675     int smin;
676     int nb_live1;
677 
678     smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
679     if (nb_live) {
680         *nb_live = nb_live1;
681     }
682 
683     if (nb_live1) {
684         int live = smin;
685 
686         if (audio_bug(__func__, live < 0 || live > hw->samples)) {
687             dolog ("live=%d hw->samples=%d\n", live, hw->samples);
688             return 0;
689         }
690         return live;
691     }
692     return 0;
693 }
694 
695 /*
696  * Soft voice (playback)
697  */
698 int audio_pcm_sw_write (SWVoiceOut *sw, void *buf, int size)
699 {
700     int hwsamples, samples, isamp, osamp, wpos, live, dead, left, swlim, blck;
701     int ret = 0, pos = 0, total = 0;
702 
703     if (!sw) {
704         return size;
705     }
706 
707     hwsamples = sw->hw->samples;
708 
709     live = sw->total_hw_samples_mixed;
710     if (audio_bug(__func__, live < 0 || live > hwsamples)) {
711         dolog ("live=%d hw->samples=%d\n", live, hwsamples);
712         return 0;
713     }
714 
715     if (live == hwsamples) {
716 #ifdef DEBUG_OUT
717         dolog ("%s is full %d\n", sw->name, live);
718 #endif
719         return 0;
720     }
721 
722     wpos = (sw->hw->rpos + live) % hwsamples;
723     samples = size >> sw->info.shift;
724 
725     dead = hwsamples - live;
726     swlim = ((int64_t) dead << 32) / sw->ratio;
727     swlim = audio_MIN (swlim, samples);
728     if (swlim) {
729         sw->conv (sw->buf, buf, swlim);
730 
731         if (!(sw->hw->ctl_caps & VOICE_VOLUME_CAP)) {
732             mixeng_volume (sw->buf, swlim, &sw->vol);
733         }
734     }
735 
736     while (swlim) {
737         dead = hwsamples - live;
738         left = hwsamples - wpos;
739         blck = audio_MIN (dead, left);
740         if (!blck) {
741             break;
742         }
743         isamp = swlim;
744         osamp = blck;
745         st_rate_flow_mix (
746             sw->rate,
747             sw->buf + pos,
748             sw->hw->mix_buf + wpos,
749             &isamp,
750             &osamp
751             );
752         ret += isamp;
753         swlim -= isamp;
754         pos += isamp;
755         live += osamp;
756         wpos = (wpos + osamp) % hwsamples;
757         total += osamp;
758     }
759 
760     sw->total_hw_samples_mixed += total;
761     sw->empty = sw->total_hw_samples_mixed == 0;
762 
763 #ifdef DEBUG_OUT
764     dolog (
765         "%s: write size %d ret %d total sw %d\n",
766         SW_NAME (sw),
767         size >> sw->info.shift,
768         ret,
769         sw->total_hw_samples_mixed
770         );
771 #endif
772 
773     return ret << sw->info.shift;
774 }
775 
776 #ifdef DEBUG_AUDIO
777 static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
778 {
779     dolog ("%s: bits %d, sign %d, freq %d, nchan %d\n",
780            cap, info->bits, info->sign, info->freq, info->nchannels);
781 }
782 #endif
783 
784 #define DAC
785 #include "audio_template.h"
786 #undef DAC
787 #include "audio_template.h"
788 
789 /*
790  * Timer
791  */
792 
793 static bool audio_timer_running;
794 static uint64_t audio_timer_last;
795 
796 static int audio_is_timer_needed (void)
797 {
798     HWVoiceIn *hwi = NULL;
799     HWVoiceOut *hwo = NULL;
800 
801     while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
802         if (!hwo->poll_mode) return 1;
803     }
804     while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
805         if (!hwi->poll_mode) return 1;
806     }
807     return 0;
808 }
809 
810 static void audio_reset_timer (AudioState *s)
811 {
812     if (audio_is_timer_needed ()) {
813         timer_mod_anticipate_ns(s->ts,
814             qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
815         if (!audio_timer_running) {
816             audio_timer_running = true;
817             audio_timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
818             trace_audio_timer_start(s->period_ticks / SCALE_MS);
819         }
820     } else {
821         timer_del(s->ts);
822         if (audio_timer_running) {
823             audio_timer_running = false;
824             trace_audio_timer_stop();
825         }
826     }
827 }
828 
829 static void audio_timer (void *opaque)
830 {
831     int64_t now, diff;
832     AudioState *s = opaque;
833 
834     now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
835     diff = now - audio_timer_last;
836     if (diff > s->period_ticks * 3 / 2) {
837         trace_audio_timer_delayed(diff / SCALE_MS);
838     }
839     audio_timer_last = now;
840 
841     audio_run("timer");
842     audio_reset_timer(s);
843 }
844 
845 /*
846  * Public API
847  */
848 int AUD_write (SWVoiceOut *sw, void *buf, int size)
849 {
850     if (!sw) {
851         /* XXX: Consider options */
852         return size;
853     }
854 
855     if (!sw->hw->enabled) {
856         dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
857         return 0;
858     }
859 
860     return sw->hw->pcm_ops->write(sw, buf, size);
861 }
862 
863 int AUD_read (SWVoiceIn *sw, void *buf, int size)
864 {
865     if (!sw) {
866         /* XXX: Consider options */
867         return size;
868     }
869 
870     if (!sw->hw->enabled) {
871         dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
872         return 0;
873     }
874 
875     return sw->hw->pcm_ops->read(sw, buf, size);
876 }
877 
878 int AUD_get_buffer_size_out (SWVoiceOut *sw)
879 {
880     return sw->hw->samples << sw->hw->info.shift;
881 }
882 
883 void AUD_set_active_out (SWVoiceOut *sw, int on)
884 {
885     HWVoiceOut *hw;
886 
887     if (!sw) {
888         return;
889     }
890 
891     hw = sw->hw;
892     if (sw->active != on) {
893         AudioState *s = &glob_audio_state;
894         SWVoiceOut *temp_sw;
895         SWVoiceCap *sc;
896 
897         if (on) {
898             hw->pending_disable = 0;
899             if (!hw->enabled) {
900                 hw->enabled = 1;
901                 if (s->vm_running) {
902                     hw->pcm_ops->ctl_out(hw, VOICE_ENABLE);
903                     audio_reset_timer (s);
904                 }
905             }
906         }
907         else {
908             if (hw->enabled) {
909                 int nb_active = 0;
910 
911                 for (temp_sw = hw->sw_head.lh_first; temp_sw;
912                      temp_sw = temp_sw->entries.le_next) {
913                     nb_active += temp_sw->active != 0;
914                 }
915 
916                 hw->pending_disable = nb_active == 1;
917             }
918         }
919 
920         for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
921             sc->sw.active = hw->enabled;
922             if (hw->enabled) {
923                 audio_capture_maybe_changed (sc->cap, 1);
924             }
925         }
926         sw->active = on;
927     }
928 }
929 
930 void AUD_set_active_in (SWVoiceIn *sw, int on)
931 {
932     HWVoiceIn *hw;
933 
934     if (!sw) {
935         return;
936     }
937 
938     hw = sw->hw;
939     if (sw->active != on) {
940         AudioState *s = &glob_audio_state;
941         SWVoiceIn *temp_sw;
942 
943         if (on) {
944             if (!hw->enabled) {
945                 hw->enabled = 1;
946                 if (s->vm_running) {
947                     hw->pcm_ops->ctl_in(hw, VOICE_ENABLE);
948                     audio_reset_timer (s);
949                 }
950             }
951             sw->total_hw_samples_acquired = hw->total_samples_captured;
952         }
953         else {
954             if (hw->enabled) {
955                 int nb_active = 0;
956 
957                 for (temp_sw = hw->sw_head.lh_first; temp_sw;
958                      temp_sw = temp_sw->entries.le_next) {
959                     nb_active += temp_sw->active != 0;
960                 }
961 
962                 if (nb_active == 1) {
963                     hw->enabled = 0;
964                     hw->pcm_ops->ctl_in (hw, VOICE_DISABLE);
965                 }
966             }
967         }
968         sw->active = on;
969     }
970 }
971 
972 static int audio_get_avail (SWVoiceIn *sw)
973 {
974     int live;
975 
976     if (!sw) {
977         return 0;
978     }
979 
980     live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
981     if (audio_bug(__func__, live < 0 || live > sw->hw->samples)) {
982         dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples);
983         return 0;
984     }
985 
986     ldebug (
987         "%s: get_avail live %d ret %" PRId64 "\n",
988         SW_NAME (sw),
989         live, (((int64_t) live << 32) / sw->ratio) << sw->info.shift
990         );
991 
992     return (((int64_t) live << 32) / sw->ratio) << sw->info.shift;
993 }
994 
995 static int audio_get_free (SWVoiceOut *sw)
996 {
997     int live, dead;
998 
999     if (!sw) {
1000         return 0;
1001     }
1002 
1003     live = sw->total_hw_samples_mixed;
1004 
1005     if (audio_bug(__func__, live < 0 || live > sw->hw->samples)) {
1006         dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples);
1007         return 0;
1008     }
1009 
1010     dead = sw->hw->samples - live;
1011 
1012 #ifdef DEBUG_OUT
1013     dolog ("%s: get_free live %d dead %d ret %" PRId64 "\n",
1014            SW_NAME (sw),
1015            live, dead, (((int64_t) dead << 32) / sw->ratio) << sw->info.shift);
1016 #endif
1017 
1018     return (((int64_t) dead << 32) / sw->ratio) << sw->info.shift;
1019 }
1020 
1021 static void audio_capture_mix_and_clear (HWVoiceOut *hw, int rpos, int samples)
1022 {
1023     int 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                 int till_end_of_hw = hw->samples - rpos2;
1035                 int to_write = audio_MIN (till_end_of_hw, n);
1036                 int bytes = to_write << hw->info.shift;
1037                 int written;
1038 
1039                 sw->buf = hw->mix_buf + rpos2;
1040                 written = audio_pcm_sw_write (sw, NULL, bytes);
1041                 if (written - bytes) {
1042                     dolog ("Could not mix %d bytes into a capture "
1043                            "buffer, mixed %d\n",
1044                            bytes, written);
1045                     break;
1046                 }
1047                 n -= to_write;
1048                 rpos2 = (rpos2 + to_write) % hw->samples;
1049             }
1050         }
1051     }
1052 
1053     n = audio_MIN (samples, hw->samples - rpos);
1054     mixeng_clear (hw->mix_buf + rpos, n);
1055     mixeng_clear (hw->mix_buf, samples - n);
1056 }
1057 
1058 static void audio_run_out (AudioState *s)
1059 {
1060     HWVoiceOut *hw = NULL;
1061     SWVoiceOut *sw;
1062 
1063     while ((hw = audio_pcm_hw_find_any_enabled_out (hw))) {
1064         int played;
1065         int live, free, nb_live, cleanup_required, prev_rpos;
1066 
1067         live = audio_pcm_hw_get_live_out (hw, &nb_live);
1068         if (!nb_live) {
1069             live = 0;
1070         }
1071 
1072         if (audio_bug(__func__, live < 0 || live > hw->samples)) {
1073             dolog ("live=%d hw->samples=%d\n", live, hw->samples);
1074             continue;
1075         }
1076 
1077         if (hw->pending_disable && !nb_live) {
1078             SWVoiceCap *sc;
1079 #ifdef DEBUG_OUT
1080             dolog ("Disabling voice\n");
1081 #endif
1082             hw->enabled = 0;
1083             hw->pending_disable = 0;
1084             hw->pcm_ops->ctl_out (hw, VOICE_DISABLE);
1085             for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1086                 sc->sw.active = 0;
1087                 audio_recalc_and_notify_capture (sc->cap);
1088             }
1089             continue;
1090         }
1091 
1092         if (!live) {
1093             for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1094                 if (sw->active) {
1095                     free = audio_get_free (sw);
1096                     if (free > 0) {
1097                         sw->callback.fn (sw->callback.opaque, free);
1098                     }
1099                 }
1100             }
1101             continue;
1102         }
1103 
1104         prev_rpos = hw->rpos;
1105         played = hw->pcm_ops->run_out (hw, live);
1106         replay_audio_out(&played);
1107         if (audio_bug(__func__, hw->rpos >= hw->samples)) {
1108             dolog ("hw->rpos=%d hw->samples=%d played=%d\n",
1109                    hw->rpos, hw->samples, played);
1110             hw->rpos = 0;
1111         }
1112 
1113 #ifdef DEBUG_OUT
1114         dolog ("played=%d\n", played);
1115 #endif
1116 
1117         if (played) {
1118             hw->ts_helper += played;
1119             audio_capture_mix_and_clear (hw, prev_rpos, played);
1120         }
1121 
1122         cleanup_required = 0;
1123         for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1124             if (!sw->active && sw->empty) {
1125                 continue;
1126             }
1127 
1128             if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1129                 dolog ("played=%d sw->total_hw_samples_mixed=%d\n",
1130                        played, sw->total_hw_samples_mixed);
1131                 played = sw->total_hw_samples_mixed;
1132             }
1133 
1134             sw->total_hw_samples_mixed -= played;
1135 
1136             if (!sw->total_hw_samples_mixed) {
1137                 sw->empty = 1;
1138                 cleanup_required |= !sw->active && !sw->callback.fn;
1139             }
1140 
1141             if (sw->active) {
1142                 free = audio_get_free (sw);
1143                 if (free > 0) {
1144                     sw->callback.fn (sw->callback.opaque, free);
1145                 }
1146             }
1147         }
1148 
1149         if (cleanup_required) {
1150             SWVoiceOut *sw1;
1151 
1152             sw = hw->sw_head.lh_first;
1153             while (sw) {
1154                 sw1 = sw->entries.le_next;
1155                 if (!sw->active && !sw->callback.fn) {
1156                     audio_close_out (sw);
1157                 }
1158                 sw = sw1;
1159             }
1160         }
1161     }
1162 }
1163 
1164 static void audio_run_in (AudioState *s)
1165 {
1166     HWVoiceIn *hw = NULL;
1167 
1168     while ((hw = audio_pcm_hw_find_any_enabled_in (hw))) {
1169         SWVoiceIn *sw;
1170         int captured = 0, min;
1171 
1172         if (replay_mode != REPLAY_MODE_PLAY) {
1173             captured = hw->pcm_ops->run_in(hw);
1174         }
1175         replay_audio_in(&captured, hw->conv_buf, &hw->wpos, hw->samples);
1176 
1177         min = audio_pcm_hw_find_min_in (hw);
1178         hw->total_samples_captured += captured - min;
1179         hw->ts_helper += captured;
1180 
1181         for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1182             sw->total_hw_samples_acquired -= min;
1183 
1184             if (sw->active) {
1185                 int avail;
1186 
1187                 avail = audio_get_avail (sw);
1188                 if (avail > 0) {
1189                     sw->callback.fn (sw->callback.opaque, avail);
1190                 }
1191             }
1192         }
1193     }
1194 }
1195 
1196 static void audio_run_capture (AudioState *s)
1197 {
1198     CaptureVoiceOut *cap;
1199 
1200     for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1201         int live, rpos, captured;
1202         HWVoiceOut *hw = &cap->hw;
1203         SWVoiceOut *sw;
1204 
1205         captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1206         rpos = hw->rpos;
1207         while (live) {
1208             int left = hw->samples - rpos;
1209             int to_capture = audio_MIN (live, left);
1210             struct st_sample *src;
1211             struct capture_callback *cb;
1212 
1213             src = hw->mix_buf + rpos;
1214             hw->clip (cap->buf, src, to_capture);
1215             mixeng_clear (src, to_capture);
1216 
1217             for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1218                 cb->ops.capture (cb->opaque, cap->buf,
1219                                  to_capture << hw->info.shift);
1220             }
1221             rpos = (rpos + to_capture) % hw->samples;
1222             live -= to_capture;
1223         }
1224         hw->rpos = rpos;
1225 
1226         for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1227             if (!sw->active && sw->empty) {
1228                 continue;
1229             }
1230 
1231             if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1232                 dolog ("captured=%d sw->total_hw_samples_mixed=%d\n",
1233                        captured, sw->total_hw_samples_mixed);
1234                 captured = sw->total_hw_samples_mixed;
1235             }
1236 
1237             sw->total_hw_samples_mixed -= captured;
1238             sw->empty = sw->total_hw_samples_mixed == 0;
1239         }
1240     }
1241 }
1242 
1243 void audio_run (const char *msg)
1244 {
1245     AudioState *s = &glob_audio_state;
1246 
1247     audio_run_out (s);
1248     audio_run_in (s);
1249     audio_run_capture (s);
1250 #ifdef DEBUG_POLL
1251     {
1252         static double prevtime;
1253         double currtime;
1254         struct timeval tv;
1255 
1256         if (gettimeofday (&tv, NULL)) {
1257             perror ("audio_run: gettimeofday");
1258             return;
1259         }
1260 
1261         currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1262         dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1263         prevtime = currtime;
1264     }
1265 #endif
1266 }
1267 
1268 static int audio_driver_init(AudioState *s, struct audio_driver *drv,
1269                              bool msg, Audiodev *dev)
1270 {
1271     s->drv_opaque = drv->init(dev);
1272 
1273     if (s->drv_opaque) {
1274         audio_init_nb_voices_out (drv);
1275         audio_init_nb_voices_in (drv);
1276         s->drv = drv;
1277         return 0;
1278     }
1279     else {
1280         if (msg) {
1281             dolog("Could not init `%s' audio driver\n", drv->name);
1282         }
1283         return -1;
1284     }
1285 }
1286 
1287 static void audio_vm_change_state_handler (void *opaque, int running,
1288                                            RunState state)
1289 {
1290     AudioState *s = opaque;
1291     HWVoiceOut *hwo = NULL;
1292     HWVoiceIn *hwi = NULL;
1293     int op = running ? VOICE_ENABLE : VOICE_DISABLE;
1294 
1295     s->vm_running = running;
1296     while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
1297         hwo->pcm_ops->ctl_out(hwo, op);
1298     }
1299 
1300     while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
1301         hwi->pcm_ops->ctl_in(hwi, op);
1302     }
1303     audio_reset_timer (s);
1304 }
1305 
1306 static bool is_cleaning_up;
1307 
1308 bool audio_is_cleaning_up(void)
1309 {
1310     return is_cleaning_up;
1311 }
1312 
1313 void audio_cleanup(void)
1314 {
1315     AudioState *s = &glob_audio_state;
1316     HWVoiceOut *hwo, *hwon;
1317     HWVoiceIn *hwi, *hwin;
1318 
1319     is_cleaning_up = true;
1320     QLIST_FOREACH_SAFE(hwo, &glob_audio_state.hw_head_out, entries, hwon) {
1321         SWVoiceCap *sc;
1322 
1323         if (hwo->enabled) {
1324             hwo->pcm_ops->ctl_out (hwo, VOICE_DISABLE);
1325         }
1326         hwo->pcm_ops->fini_out (hwo);
1327 
1328         for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1329             CaptureVoiceOut *cap = sc->cap;
1330             struct capture_callback *cb;
1331 
1332             for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1333                 cb->ops.destroy (cb->opaque);
1334             }
1335         }
1336         QLIST_REMOVE(hwo, entries);
1337     }
1338 
1339     QLIST_FOREACH_SAFE(hwi, &glob_audio_state.hw_head_in, entries, hwin) {
1340         if (hwi->enabled) {
1341             hwi->pcm_ops->ctl_in (hwi, VOICE_DISABLE);
1342         }
1343         hwi->pcm_ops->fini_in (hwi);
1344         QLIST_REMOVE(hwi, entries);
1345     }
1346 
1347     if (s->drv) {
1348         s->drv->fini (s->drv_opaque);
1349         s->drv = NULL;
1350     }
1351 
1352     if (s->dev) {
1353         qapi_free_Audiodev(s->dev);
1354         s->dev = NULL;
1355     }
1356 }
1357 
1358 static const VMStateDescription vmstate_audio = {
1359     .name = "audio",
1360     .version_id = 1,
1361     .minimum_version_id = 1,
1362     .fields = (VMStateField[]) {
1363         VMSTATE_END_OF_LIST()
1364     }
1365 };
1366 
1367 static void audio_validate_opts(Audiodev *dev, Error **errp);
1368 
1369 static AudiodevListEntry *audiodev_find(
1370     AudiodevListHead *head, const char *drvname)
1371 {
1372     AudiodevListEntry *e;
1373     QSIMPLEQ_FOREACH(e, head, next) {
1374         if (strcmp(AudiodevDriver_str(e->dev->driver), drvname) == 0) {
1375             return e;
1376         }
1377     }
1378 
1379     return NULL;
1380 }
1381 
1382 static int audio_init(Audiodev *dev)
1383 {
1384     size_t i;
1385     int done = 0;
1386     const char *drvname = NULL;
1387     VMChangeStateEntry *e;
1388     AudioState *s = &glob_audio_state;
1389     struct audio_driver *driver;
1390     /* silence gcc warning about uninitialized variable */
1391     AudiodevListHead head = QSIMPLEQ_HEAD_INITIALIZER(head);
1392 
1393     if (s->drv) {
1394         if (dev) {
1395             dolog("Cannot create more than one audio backend, sorry\n");
1396             qapi_free_Audiodev(dev);
1397         }
1398         return -1;
1399     }
1400 
1401     if (dev) {
1402         /* -audiodev option */
1403         drvname = AudiodevDriver_str(dev->driver);
1404     } else {
1405         /* legacy implicit initialization */
1406         head = audio_handle_legacy_opts();
1407         /*
1408          * In case of legacy initialization, all Audiodevs in the list will have
1409          * the same configuration (except the driver), so it does't matter which
1410          * one we chose.  We need an Audiodev to set up AudioState before we can
1411          * init a driver.  Also note that dev at this point is still in the
1412          * list.
1413          */
1414         dev = QSIMPLEQ_FIRST(&head)->dev;
1415         audio_validate_opts(dev, &error_abort);
1416     }
1417     s->dev = dev;
1418 
1419     QLIST_INIT (&s->hw_head_out);
1420     QLIST_INIT (&s->hw_head_in);
1421     QLIST_INIT (&s->cap_head);
1422     atexit(audio_cleanup);
1423 
1424     s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1425 
1426     s->nb_hw_voices_out = audio_get_pdo_out(dev)->voices;
1427     s->nb_hw_voices_in = audio_get_pdo_in(dev)->voices;
1428 
1429     if (s->nb_hw_voices_out <= 0) {
1430         dolog ("Bogus number of playback voices %d, setting to 1\n",
1431                s->nb_hw_voices_out);
1432         s->nb_hw_voices_out = 1;
1433     }
1434 
1435     if (s->nb_hw_voices_in <= 0) {
1436         dolog ("Bogus number of capture voices %d, setting to 0\n",
1437                s->nb_hw_voices_in);
1438         s->nb_hw_voices_in = 0;
1439     }
1440 
1441     if (drvname) {
1442         driver = audio_driver_lookup(drvname);
1443         if (driver) {
1444             done = !audio_driver_init(s, driver, true, dev);
1445         } else {
1446             dolog ("Unknown audio driver `%s'\n", drvname);
1447         }
1448     } else {
1449         for (i = 0; audio_prio_list[i]; i++) {
1450             AudiodevListEntry *e = audiodev_find(&head, audio_prio_list[i]);
1451             driver = audio_driver_lookup(audio_prio_list[i]);
1452 
1453             if (e && driver) {
1454                 s->dev = dev = e->dev;
1455                 audio_validate_opts(dev, &error_abort);
1456                 done = !audio_driver_init(s, driver, false, dev);
1457                 if (done) {
1458                     e->dev = NULL;
1459                     break;
1460                 }
1461             }
1462         }
1463     }
1464     audio_free_audiodev_list(&head);
1465 
1466     if (!done) {
1467         driver = audio_driver_lookup("none");
1468         done = !audio_driver_init(s, driver, false, dev);
1469         assert(done);
1470         dolog("warning: Using timer based audio emulation\n");
1471     }
1472 
1473     if (dev->timer_period <= 0) {
1474         s->period_ticks = 1;
1475     } else {
1476         s->period_ticks = dev->timer_period * SCALE_US;
1477     }
1478 
1479     e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1480     if (!e) {
1481         dolog ("warning: Could not register change state handler\n"
1482                "(Audio can continue looping even after stopping the VM)\n");
1483     }
1484 
1485     QLIST_INIT (&s->card_head);
1486     vmstate_register (NULL, 0, &vmstate_audio, s);
1487     return 0;
1488 }
1489 
1490 void audio_free_audiodev_list(AudiodevListHead *head)
1491 {
1492     AudiodevListEntry *e;
1493     while ((e = QSIMPLEQ_FIRST(head))) {
1494         QSIMPLEQ_REMOVE_HEAD(head, next);
1495         qapi_free_Audiodev(e->dev);
1496         g_free(e);
1497     }
1498 }
1499 
1500 void AUD_register_card (const char *name, QEMUSoundCard *card)
1501 {
1502     audio_init(NULL);
1503     card->name = g_strdup (name);
1504     memset (&card->entries, 0, sizeof (card->entries));
1505     QLIST_INSERT_HEAD (&glob_audio_state.card_head, card, entries);
1506 }
1507 
1508 void AUD_remove_card (QEMUSoundCard *card)
1509 {
1510     QLIST_REMOVE (card, entries);
1511     g_free (card->name);
1512 }
1513 
1514 
1515 CaptureVoiceOut *AUD_add_capture (
1516     struct audsettings *as,
1517     struct audio_capture_ops *ops,
1518     void *cb_opaque
1519     )
1520 {
1521     AudioState *s = &glob_audio_state;
1522     CaptureVoiceOut *cap;
1523     struct capture_callback *cb;
1524 
1525     if (audio_validate_settings (as)) {
1526         dolog ("Invalid settings were passed when trying to add capture\n");
1527         audio_print_settings (as);
1528         return NULL;
1529     }
1530 
1531     cb = g_malloc0(sizeof(*cb));
1532     cb->ops = *ops;
1533     cb->opaque = cb_opaque;
1534 
1535     cap = audio_pcm_capture_find_specific (as);
1536     if (cap) {
1537         QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1538         return cap;
1539     }
1540     else {
1541         HWVoiceOut *hw;
1542         CaptureVoiceOut *cap;
1543 
1544         cap = g_malloc0(sizeof(*cap));
1545 
1546         hw = &cap->hw;
1547         QLIST_INIT (&hw->sw_head);
1548         QLIST_INIT (&cap->cb_head);
1549 
1550         /* XXX find a more elegant way */
1551         hw->samples = 4096 * 4;
1552         hw->mix_buf = g_new0(struct st_sample, hw->samples);
1553 
1554         audio_pcm_init_info (&hw->info, as);
1555 
1556         cap->buf = g_malloc0_n(hw->samples, 1 << hw->info.shift);
1557 
1558         hw->clip = mixeng_clip
1559             [hw->info.nchannels == 2]
1560             [hw->info.sign]
1561             [hw->info.swap_endianness]
1562             [audio_bits_to_index (hw->info.bits)];
1563 
1564         QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1565         QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1566 
1567         QLIST_FOREACH(hw, &glob_audio_state.hw_head_out, entries) {
1568             audio_attach_capture (hw);
1569         }
1570         return cap;
1571     }
1572 }
1573 
1574 void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1575 {
1576     struct capture_callback *cb;
1577 
1578     for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1579         if (cb->opaque == cb_opaque) {
1580             cb->ops.destroy (cb_opaque);
1581             QLIST_REMOVE (cb, entries);
1582             g_free (cb);
1583 
1584             if (!cap->cb_head.lh_first) {
1585                 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
1586 
1587                 while (sw) {
1588                     SWVoiceCap *sc = (SWVoiceCap *) sw;
1589 #ifdef DEBUG_CAPTURE
1590                     dolog ("freeing %s\n", sw->name);
1591 #endif
1592 
1593                     sw1 = sw->entries.le_next;
1594                     if (sw->rate) {
1595                         st_rate_stop (sw->rate);
1596                         sw->rate = NULL;
1597                     }
1598                     QLIST_REMOVE (sw, entries);
1599                     QLIST_REMOVE (sc, entries);
1600                     g_free (sc);
1601                     sw = sw1;
1602                 }
1603                 QLIST_REMOVE (cap, entries);
1604                 g_free (cap->hw.mix_buf);
1605                 g_free (cap->buf);
1606                 g_free (cap);
1607             }
1608             return;
1609         }
1610     }
1611 }
1612 
1613 void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
1614 {
1615     if (sw) {
1616         HWVoiceOut *hw = sw->hw;
1617 
1618         sw->vol.mute = mute;
1619         sw->vol.l = nominal_volume.l * lvol / 255;
1620         sw->vol.r = nominal_volume.r * rvol / 255;
1621 
1622         if (hw->pcm_ops->ctl_out) {
1623             hw->pcm_ops->ctl_out (hw, VOICE_VOLUME, sw);
1624         }
1625     }
1626 }
1627 
1628 void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
1629 {
1630     if (sw) {
1631         HWVoiceIn *hw = sw->hw;
1632 
1633         sw->vol.mute = mute;
1634         sw->vol.l = nominal_volume.l * lvol / 255;
1635         sw->vol.r = nominal_volume.r * rvol / 255;
1636 
1637         if (hw->pcm_ops->ctl_in) {
1638             hw->pcm_ops->ctl_in (hw, VOICE_VOLUME, sw);
1639         }
1640     }
1641 }
1642 
1643 void audio_create_pdos(Audiodev *dev)
1644 {
1645     switch (dev->driver) {
1646 #define CASE(DRIVER, driver, pdo_name)                              \
1647     case AUDIODEV_DRIVER_##DRIVER:                                  \
1648         if (!dev->u.driver.has_in) {                                \
1649             dev->u.driver.in = g_malloc0(                           \
1650                 sizeof(Audiodev##pdo_name##PerDirectionOptions));   \
1651             dev->u.driver.has_in = true;                            \
1652         }                                                           \
1653         if (!dev->u.driver.has_out) {                               \
1654             dev->u.driver.out = g_malloc0(                          \
1655                 sizeof(AudiodevAlsaPerDirectionOptions));           \
1656             dev->u.driver.has_out = true;                           \
1657         }                                                           \
1658         break
1659 
1660         CASE(NONE, none, );
1661         CASE(ALSA, alsa, Alsa);
1662         CASE(COREAUDIO, coreaudio, Coreaudio);
1663         CASE(DSOUND, dsound, );
1664         CASE(OSS, oss, Oss);
1665         CASE(PA, pa, Pa);
1666         CASE(SDL, sdl, );
1667         CASE(SPICE, spice, );
1668         CASE(WAV, wav, );
1669 
1670     case AUDIODEV_DRIVER__MAX:
1671         abort();
1672     };
1673 }
1674 
1675 static void audio_validate_per_direction_opts(
1676     AudiodevPerDirectionOptions *pdo, Error **errp)
1677 {
1678     if (!pdo->has_fixed_settings) {
1679         pdo->has_fixed_settings = true;
1680         pdo->fixed_settings = true;
1681     }
1682     if (!pdo->fixed_settings &&
1683         (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
1684         error_setg(errp,
1685                    "You can't use frequency, channels or format with fixed-settings=off");
1686         return;
1687     }
1688 
1689     if (!pdo->has_frequency) {
1690         pdo->has_frequency = true;
1691         pdo->frequency = 44100;
1692     }
1693     if (!pdo->has_channels) {
1694         pdo->has_channels = true;
1695         pdo->channels = 2;
1696     }
1697     if (!pdo->has_voices) {
1698         pdo->has_voices = true;
1699         pdo->voices = 1;
1700     }
1701     if (!pdo->has_format) {
1702         pdo->has_format = true;
1703         pdo->format = AUDIO_FORMAT_S16;
1704     }
1705 }
1706 
1707 static void audio_validate_opts(Audiodev *dev, Error **errp)
1708 {
1709     Error *err = NULL;
1710 
1711     audio_create_pdos(dev);
1712 
1713     audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
1714     if (err) {
1715         error_propagate(errp, err);
1716         return;
1717     }
1718 
1719     audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
1720     if (err) {
1721         error_propagate(errp, err);
1722         return;
1723     }
1724 
1725     if (!dev->has_timer_period) {
1726         dev->has_timer_period = true;
1727         dev->timer_period = 10000; /* 100Hz -> 10ms */
1728     }
1729 }
1730 
1731 void audio_parse_option(const char *opt)
1732 {
1733     AudiodevListEntry *e;
1734     Audiodev *dev = NULL;
1735 
1736     Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
1737     visit_type_Audiodev(v, NULL, &dev, &error_fatal);
1738     visit_free(v);
1739 
1740     audio_validate_opts(dev, &error_fatal);
1741 
1742     e = g_malloc0(sizeof(AudiodevListEntry));
1743     e->dev = dev;
1744     QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
1745 }
1746 
1747 void audio_init_audiodevs(void)
1748 {
1749     AudiodevListEntry *e;
1750 
1751     QSIMPLEQ_FOREACH(e, &audiodevs, next) {
1752         audio_init(e->dev);
1753     }
1754 }
1755 
1756 audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
1757 {
1758     return (audsettings) {
1759         .freq = pdo->frequency,
1760         .nchannels = pdo->channels,
1761         .fmt = pdo->format,
1762         .endianness = AUDIO_HOST_ENDIANNESS,
1763     };
1764 }
1765 
1766 int audioformat_bytes_per_sample(AudioFormat fmt)
1767 {
1768     switch (fmt) {
1769     case AUDIO_FORMAT_U8:
1770     case AUDIO_FORMAT_S8:
1771         return 1;
1772 
1773     case AUDIO_FORMAT_U16:
1774     case AUDIO_FORMAT_S16:
1775         return 2;
1776 
1777     case AUDIO_FORMAT_U32:
1778     case AUDIO_FORMAT_S32:
1779         return 4;
1780 
1781     case AUDIO_FORMAT__MAX:
1782         ;
1783     }
1784     abort();
1785 }
1786 
1787 
1788 /* frames = freq * usec / 1e6 */
1789 int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
1790                         audsettings *as, int def_usecs)
1791 {
1792     uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
1793     return (as->freq * usecs + 500000) / 1000000;
1794 }
1795 
1796 /* samples = channels * frames = channels * freq * usec / 1e6 */
1797 int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
1798                          audsettings *as, int def_usecs)
1799 {
1800     return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
1801 }
1802 
1803 /*
1804  * bytes = bytes_per_sample * samples =
1805  *     bytes_per_sample * channels * freq * usec / 1e6
1806  */
1807 int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
1808                        audsettings *as, int def_usecs)
1809 {
1810     return audio_buffer_samples(pdo, as, def_usecs) *
1811         audioformat_bytes_per_sample(as->fmt);
1812 }
1813