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