]> git.ipfire.org Git - thirdparty/qemu.git/blob - audio/audio.c
audio: remove remains of the old backend api
[thirdparty/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->samples)) {
548 dolog("live=%zu hw->samples=%zu\n", live, hw->samples);
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->rpos;
558
559 while (len) {
560 st_sample *src = hw->mix_buf + pos;
561 uint8_t *dst = advance(pcm_buf, clipped << hw->info.shift);
562 size_t samples_till_end_of_buf = hw->samples - 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->samples;
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->samples)) {
583 dolog("live=%zu hw->samples=%zu\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 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->samples;
603
604 live = hw->total_samples_captured - sw->total_hw_samples_acquired;
605 if (audio_bug(__func__, live > hw->samples)) {
606 dolog("live_in=%zu hw->samples=%zu\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 = MIN (swlim, samples);
617
618 while (swlim) {
619 src = hw->conv_buf + rpos;
620 if (hw->wpos > rpos) {
621 isamp = hw->wpos - rpos;
622 } else {
623 isamp = hw->samples - 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->samples;
634 dst += osamp;
635 ret += osamp;
636 total += isamp;
637 }
638
639 if (!(hw->ctl_caps & VOICE_VOLUME_CAP)) {
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->samples)) {
682 dolog("live=%zu hw->samples=%zu\n", live, hw->samples);
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->samples;
703
704 live = sw->total_hw_samples_mixed;
705 if (audio_bug(__func__, live > hwsamples)) {
706 dolog("live=%zu hw->samples=%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->rpos + 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->ctl_caps & VOICE_VOLUME_CAP)) {
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 + wpos,
744 &isamp,
745 &osamp
746 );
747 ret += isamp;
748 swlim -= isamp;
749 pos += isamp;
750 live += osamp;
751 wpos = (wpos + osamp) % hwsamples;
752 total += osamp;
753 }
754
755 sw->total_hw_samples_mixed += total;
756 sw->empty = sw->total_hw_samples_mixed == 0;
757
758 #ifdef DEBUG_OUT
759 dolog (
760 "%s: write size %zu ret %zu total sw %zu\n",
761 SW_NAME (sw),
762 size >> sw->info.shift,
763 ret,
764 sw->total_hw_samples_mixed
765 );
766 #endif
767
768 return ret << sw->info.shift;
769 }
770
771 #ifdef DEBUG_AUDIO
772 static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
773 {
774 dolog ("%s: bits %d, sign %d, freq %d, nchan %d\n",
775 cap, info->bits, info->sign, info->freq, info->nchannels);
776 }
777 #endif
778
779 #define DAC
780 #include "audio_template.h"
781 #undef DAC
782 #include "audio_template.h"
783
784 /*
785 * Timer
786 */
787 static int audio_is_timer_needed(AudioState *s)
788 {
789 HWVoiceIn *hwi = NULL;
790 HWVoiceOut *hwo = NULL;
791
792 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
793 if (!hwo->poll_mode) return 1;
794 }
795 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
796 if (!hwi->poll_mode) return 1;
797 }
798 return 0;
799 }
800
801 static void audio_reset_timer (AudioState *s)
802 {
803 if (audio_is_timer_needed(s)) {
804 timer_mod_anticipate_ns(s->ts,
805 qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
806 if (!s->timer_running) {
807 s->timer_running = true;
808 s->timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
809 trace_audio_timer_start(s->period_ticks / SCALE_MS);
810 }
811 } else {
812 timer_del(s->ts);
813 if (s->timer_running) {
814 s->timer_running = false;
815 trace_audio_timer_stop();
816 }
817 }
818 }
819
820 static void audio_timer (void *opaque)
821 {
822 int64_t now, diff;
823 AudioState *s = opaque;
824
825 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
826 diff = now - s->timer_last;
827 if (diff > s->period_ticks * 3 / 2) {
828 trace_audio_timer_delayed(diff / SCALE_MS);
829 }
830 s->timer_last = now;
831
832 audio_run(s, "timer");
833 audio_reset_timer(s);
834 }
835
836 /*
837 * Public API
838 */
839 size_t AUD_write(SWVoiceOut *sw, void *buf, size_t size)
840 {
841 if (!sw) {
842 /* XXX: Consider options */
843 return size;
844 }
845
846 if (!sw->hw->enabled) {
847 dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
848 return 0;
849 }
850
851 return audio_pcm_sw_write(sw, buf, size);
852 }
853
854 size_t AUD_read(SWVoiceIn *sw, void *buf, size_t size)
855 {
856 if (!sw) {
857 /* XXX: Consider options */
858 return size;
859 }
860
861 if (!sw->hw->enabled) {
862 dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
863 return 0;
864 }
865
866 return audio_pcm_sw_read(sw, buf, size);
867 }
868
869 int AUD_get_buffer_size_out (SWVoiceOut *sw)
870 {
871 return sw->hw->samples << sw->hw->info.shift;
872 }
873
874 void AUD_set_active_out (SWVoiceOut *sw, int on)
875 {
876 HWVoiceOut *hw;
877
878 if (!sw) {
879 return;
880 }
881
882 hw = sw->hw;
883 if (sw->active != on) {
884 AudioState *s = sw->s;
885 SWVoiceOut *temp_sw;
886 SWVoiceCap *sc;
887
888 if (on) {
889 hw->pending_disable = 0;
890 if (!hw->enabled) {
891 hw->enabled = 1;
892 if (s->vm_running) {
893 hw->pcm_ops->ctl_out(hw, VOICE_ENABLE);
894 audio_reset_timer (s);
895 }
896 }
897 }
898 else {
899 if (hw->enabled) {
900 int nb_active = 0;
901
902 for (temp_sw = hw->sw_head.lh_first; temp_sw;
903 temp_sw = temp_sw->entries.le_next) {
904 nb_active += temp_sw->active != 0;
905 }
906
907 hw->pending_disable = nb_active == 1;
908 }
909 }
910
911 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
912 sc->sw.active = hw->enabled;
913 if (hw->enabled) {
914 audio_capture_maybe_changed (sc->cap, 1);
915 }
916 }
917 sw->active = on;
918 }
919 }
920
921 void AUD_set_active_in (SWVoiceIn *sw, int on)
922 {
923 HWVoiceIn *hw;
924
925 if (!sw) {
926 return;
927 }
928
929 hw = sw->hw;
930 if (sw->active != on) {
931 AudioState *s = sw->s;
932 SWVoiceIn *temp_sw;
933
934 if (on) {
935 if (!hw->enabled) {
936 hw->enabled = 1;
937 if (s->vm_running) {
938 hw->pcm_ops->ctl_in(hw, VOICE_ENABLE);
939 audio_reset_timer (s);
940 }
941 }
942 sw->total_hw_samples_acquired = hw->total_samples_captured;
943 }
944 else {
945 if (hw->enabled) {
946 int nb_active = 0;
947
948 for (temp_sw = hw->sw_head.lh_first; temp_sw;
949 temp_sw = temp_sw->entries.le_next) {
950 nb_active += temp_sw->active != 0;
951 }
952
953 if (nb_active == 1) {
954 hw->enabled = 0;
955 hw->pcm_ops->ctl_in (hw, VOICE_DISABLE);
956 }
957 }
958 }
959 sw->active = on;
960 }
961 }
962
963 static size_t audio_get_avail (SWVoiceIn *sw)
964 {
965 size_t live;
966
967 if (!sw) {
968 return 0;
969 }
970
971 live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
972 if (audio_bug(__func__, live > sw->hw->samples)) {
973 dolog("live=%zu sw->hw->samples=%zu\n", live, sw->hw->samples);
974 return 0;
975 }
976
977 ldebug (
978 "%s: get_avail live %d ret %" PRId64 "\n",
979 SW_NAME (sw),
980 live, (((int64_t) live << 32) / sw->ratio) << sw->info.shift
981 );
982
983 return (((int64_t) live << 32) / sw->ratio) << sw->info.shift;
984 }
985
986 static size_t audio_get_free(SWVoiceOut *sw)
987 {
988 size_t live, dead;
989
990 if (!sw) {
991 return 0;
992 }
993
994 live = sw->total_hw_samples_mixed;
995
996 if (audio_bug(__func__, live > sw->hw->samples)) {
997 dolog("live=%zu sw->hw->samples=%zu\n", live, sw->hw->samples);
998 return 0;
999 }
1000
1001 dead = sw->hw->samples - live;
1002
1003 #ifdef DEBUG_OUT
1004 dolog ("%s: get_free live %d dead %d ret %" PRId64 "\n",
1005 SW_NAME (sw),
1006 live, dead, (((int64_t) dead << 32) / sw->ratio) << sw->info.shift);
1007 #endif
1008
1009 return (((int64_t) dead << 32) / sw->ratio) << sw->info.shift;
1010 }
1011
1012 static void audio_capture_mix_and_clear(HWVoiceOut *hw, size_t rpos,
1013 size_t samples)
1014 {
1015 size_t n;
1016
1017 if (hw->enabled) {
1018 SWVoiceCap *sc;
1019
1020 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1021 SWVoiceOut *sw = &sc->sw;
1022 int rpos2 = rpos;
1023
1024 n = samples;
1025 while (n) {
1026 size_t till_end_of_hw = hw->samples - rpos2;
1027 size_t to_write = MIN(till_end_of_hw, n);
1028 size_t bytes = to_write << hw->info.shift;
1029 size_t written;
1030
1031 sw->buf = hw->mix_buf + rpos2;
1032 written = audio_pcm_sw_write (sw, NULL, bytes);
1033 if (written - bytes) {
1034 dolog("Could not mix %zu bytes into a capture "
1035 "buffer, mixed %zu\n",
1036 bytes, written);
1037 break;
1038 }
1039 n -= to_write;
1040 rpos2 = (rpos2 + to_write) % hw->samples;
1041 }
1042 }
1043 }
1044
1045 n = MIN(samples, hw->samples - rpos);
1046 mixeng_clear(hw->mix_buf + rpos, n);
1047 mixeng_clear(hw->mix_buf, samples - n);
1048 }
1049
1050 static size_t audio_pcm_hw_run_out(HWVoiceOut *hw, size_t live)
1051 {
1052 size_t clipped = 0;
1053
1054 while (live) {
1055 size_t size, decr, proc;
1056 void *buf = hw->pcm_ops->get_buffer_out(hw, &size);
1057 if (!buf) {
1058 /* retrying will likely won't help, drop everything. */
1059 hw->rpos = (hw->rpos + live) % hw->samples;
1060 return clipped + live;
1061 }
1062
1063 decr = MIN(size >> hw->info.shift, live);
1064 audio_pcm_hw_clip_out(hw, buf, decr);
1065 proc = hw->pcm_ops->put_buffer_out(hw, buf, decr << hw->info.shift) >>
1066 hw->info.shift;
1067
1068 live -= proc;
1069 clipped += proc;
1070 hw->rpos = (hw->rpos + proc) % hw->samples;
1071
1072 if (proc == 0 || proc < decr) {
1073 break;
1074 }
1075 }
1076
1077 return clipped;
1078 }
1079
1080 static void audio_run_out (AudioState *s)
1081 {
1082 HWVoiceOut *hw = NULL;
1083 SWVoiceOut *sw;
1084
1085 while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1086 size_t played, live, prev_rpos, free;
1087 int nb_live, cleanup_required;
1088
1089 live = audio_pcm_hw_get_live_out (hw, &nb_live);
1090 if (!nb_live) {
1091 live = 0;
1092 }
1093
1094 if (audio_bug(__func__, live > hw->samples)) {
1095 dolog ("live=%zu hw->samples=%zu\n", live, hw->samples);
1096 continue;
1097 }
1098
1099 if (hw->pending_disable && !nb_live) {
1100 SWVoiceCap *sc;
1101 #ifdef DEBUG_OUT
1102 dolog ("Disabling voice\n");
1103 #endif
1104 hw->enabled = 0;
1105 hw->pending_disable = 0;
1106 hw->pcm_ops->ctl_out (hw, VOICE_DISABLE);
1107 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1108 sc->sw.active = 0;
1109 audio_recalc_and_notify_capture (sc->cap);
1110 }
1111 continue;
1112 }
1113
1114 if (!live) {
1115 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1116 if (sw->active) {
1117 free = audio_get_free (sw);
1118 if (free > 0) {
1119 sw->callback.fn (sw->callback.opaque, free);
1120 }
1121 }
1122 }
1123 continue;
1124 }
1125
1126 prev_rpos = hw->rpos;
1127 played = audio_pcm_hw_run_out(hw, live);
1128 replay_audio_out(&played);
1129 if (audio_bug(__func__, hw->rpos >= hw->samples)) {
1130 dolog("hw->rpos=%zu hw->samples=%zu played=%zu\n",
1131 hw->rpos, hw->samples, played);
1132 hw->rpos = 0;
1133 }
1134
1135 #ifdef DEBUG_OUT
1136 dolog("played=%zu\n", played);
1137 #endif
1138
1139 if (played) {
1140 hw->ts_helper += played;
1141 audio_capture_mix_and_clear (hw, prev_rpos, played);
1142 }
1143
1144 cleanup_required = 0;
1145 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1146 if (!sw->active && sw->empty) {
1147 continue;
1148 }
1149
1150 if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1151 dolog("played=%zu sw->total_hw_samples_mixed=%zu\n",
1152 played, sw->total_hw_samples_mixed);
1153 played = sw->total_hw_samples_mixed;
1154 }
1155
1156 sw->total_hw_samples_mixed -= played;
1157
1158 if (!sw->total_hw_samples_mixed) {
1159 sw->empty = 1;
1160 cleanup_required |= !sw->active && !sw->callback.fn;
1161 }
1162
1163 if (sw->active) {
1164 free = audio_get_free (sw);
1165 if (free > 0) {
1166 sw->callback.fn (sw->callback.opaque, free);
1167 }
1168 }
1169 }
1170
1171 if (cleanup_required) {
1172 SWVoiceOut *sw1;
1173
1174 sw = hw->sw_head.lh_first;
1175 while (sw) {
1176 sw1 = sw->entries.le_next;
1177 if (!sw->active && !sw->callback.fn) {
1178 audio_close_out (sw);
1179 }
1180 sw = sw1;
1181 }
1182 }
1183 }
1184 }
1185
1186 static size_t audio_pcm_hw_run_in(HWVoiceIn *hw, size_t samples)
1187 {
1188 size_t conv = 0;
1189
1190 while (samples) {
1191 size_t proc;
1192 size_t size = samples << hw->info.shift;
1193 void *buf = hw->pcm_ops->get_buffer_in(hw, &size);
1194
1195 assert((size & hw->info.align) == 0);
1196 if (size == 0) {
1197 hw->pcm_ops->put_buffer_in(hw, buf, size);
1198 break;
1199 }
1200
1201 proc = MIN(size >> hw->info.shift,
1202 hw->samples - hw->wpos);
1203
1204 hw->conv(hw->conv_buf + hw->wpos, buf, proc);
1205 hw->wpos = (hw->wpos + proc) % hw->samples;
1206
1207 samples -= proc;
1208 conv += proc;
1209 hw->pcm_ops->put_buffer_in(hw, buf, proc << hw->info.shift);
1210 }
1211
1212 return conv;
1213 }
1214
1215 static void audio_run_in (AudioState *s)
1216 {
1217 HWVoiceIn *hw = NULL;
1218
1219 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1220 SWVoiceIn *sw;
1221 size_t captured = 0, min;
1222
1223 if (replay_mode != REPLAY_MODE_PLAY) {
1224 captured = audio_pcm_hw_run_in(
1225 hw, hw->samples - audio_pcm_hw_get_live_in(hw));
1226 }
1227 replay_audio_in(&captured, hw->conv_buf, &hw->wpos, hw->samples);
1228
1229 min = audio_pcm_hw_find_min_in (hw);
1230 hw->total_samples_captured += captured - min;
1231 hw->ts_helper += captured;
1232
1233 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1234 sw->total_hw_samples_acquired -= min;
1235
1236 if (sw->active) {
1237 size_t avail;
1238
1239 avail = audio_get_avail (sw);
1240 if (avail > 0) {
1241 sw->callback.fn (sw->callback.opaque, avail);
1242 }
1243 }
1244 }
1245 }
1246 }
1247
1248 static void audio_run_capture (AudioState *s)
1249 {
1250 CaptureVoiceOut *cap;
1251
1252 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1253 size_t live, rpos, captured;
1254 HWVoiceOut *hw = &cap->hw;
1255 SWVoiceOut *sw;
1256
1257 captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1258 rpos = hw->rpos;
1259 while (live) {
1260 size_t left = hw->samples - rpos;
1261 size_t to_capture = MIN(live, left);
1262 struct st_sample *src;
1263 struct capture_callback *cb;
1264
1265 src = hw->mix_buf + rpos;
1266 hw->clip (cap->buf, src, to_capture);
1267 mixeng_clear (src, to_capture);
1268
1269 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1270 cb->ops.capture (cb->opaque, cap->buf,
1271 to_capture << hw->info.shift);
1272 }
1273 rpos = (rpos + to_capture) % hw->samples;
1274 live -= to_capture;
1275 }
1276 hw->rpos = rpos;
1277
1278 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1279 if (!sw->active && sw->empty) {
1280 continue;
1281 }
1282
1283 if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1284 dolog("captured=%zu sw->total_hw_samples_mixed=%zu\n",
1285 captured, sw->total_hw_samples_mixed);
1286 captured = sw->total_hw_samples_mixed;
1287 }
1288
1289 sw->total_hw_samples_mixed -= captured;
1290 sw->empty = sw->total_hw_samples_mixed == 0;
1291 }
1292 }
1293 }
1294
1295 void audio_run(AudioState *s, const char *msg)
1296 {
1297 audio_run_out(s);
1298 audio_run_in(s);
1299 audio_run_capture(s);
1300
1301 #ifdef DEBUG_POLL
1302 {
1303 static double prevtime;
1304 double currtime;
1305 struct timeval tv;
1306
1307 if (gettimeofday (&tv, NULL)) {
1308 perror ("audio_run: gettimeofday");
1309 return;
1310 }
1311
1312 currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1313 dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1314 prevtime = currtime;
1315 }
1316 #endif
1317 }
1318
1319 void *audio_generic_get_buffer_in(HWVoiceIn *hw, size_t *size)
1320 {
1321 ssize_t start;
1322
1323 if (unlikely(!hw->buf_emul)) {
1324 size_t calc_size = hw->samples << hw->info.shift;
1325 hw->buf_emul = g_malloc(calc_size);
1326 hw->size_emul = calc_size;
1327 hw->pos_emul = hw->pending_emul = 0;
1328 }
1329
1330 while (hw->pending_emul < hw->size_emul) {
1331 size_t read_len = MIN(hw->size_emul - hw->pos_emul,
1332 hw->size_emul - hw->pending_emul);
1333 size_t read = hw->pcm_ops->read(hw, hw->buf_emul + hw->pos_emul,
1334 read_len);
1335 hw->pending_emul += read;
1336 if (read < read_len) {
1337 break;
1338 }
1339 }
1340
1341 start = ((ssize_t) hw->pos_emul) - hw->pending_emul;
1342 if (start < 0) {
1343 start += hw->size_emul;
1344 }
1345 assert(start >= 0 && start < hw->size_emul);
1346
1347 *size = MIN(hw->pending_emul, hw->size_emul - start);
1348 return hw->buf_emul + start;
1349 }
1350
1351 void audio_generic_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
1352 {
1353 assert(size <= hw->pending_emul);
1354 hw->pending_emul -= size;
1355 }
1356
1357 void *audio_generic_get_buffer_out(HWVoiceOut *hw, size_t *size)
1358 {
1359 if (unlikely(!hw->buf_emul)) {
1360 size_t calc_size = hw->samples << hw->info.shift;
1361
1362 hw->buf_emul = g_malloc(calc_size);
1363 hw->size_emul = calc_size;
1364 hw->pos_emul = hw->pending_emul = 0;
1365 }
1366
1367 *size = MIN(hw->size_emul - hw->pending_emul,
1368 hw->size_emul - hw->pos_emul);
1369 return hw->buf_emul + hw->pos_emul;
1370 }
1371
1372 size_t audio_generic_put_buffer_out_nowrite(HWVoiceOut *hw, void *buf,
1373 size_t size)
1374 {
1375 assert(buf == hw->buf_emul + hw->pos_emul &&
1376 size + hw->pending_emul <= hw->size_emul);
1377
1378 hw->pending_emul += size;
1379 hw->pos_emul = (hw->pos_emul + size) % hw->size_emul;
1380
1381 return size;
1382 }
1383
1384 size_t audio_generic_put_buffer_out(HWVoiceOut *hw, void *buf, size_t size)
1385 {
1386 audio_generic_put_buffer_out_nowrite(hw, buf, size);
1387
1388 while (hw->pending_emul) {
1389 size_t write_len, written;
1390 ssize_t start = ((ssize_t) hw->pos_emul) - hw->pending_emul;
1391 if (start < 0) {
1392 start += hw->size_emul;
1393 }
1394 assert(start >= 0 && start < hw->size_emul);
1395
1396 write_len = MIN(hw->pending_emul, hw->size_emul - start);
1397
1398 written = hw->pcm_ops->write(hw, hw->buf_emul + start, write_len);
1399 hw->pending_emul -= written;
1400
1401 if (written < write_len) {
1402 break;
1403 }
1404 }
1405
1406 /*
1407 * fake we have written everything. non-written data remain in pending_emul,
1408 * so we do not have to clip them multiple times
1409 */
1410 return size;
1411 }
1412
1413 size_t audio_generic_write(HWVoiceOut *hw, void *buf, size_t size)
1414 {
1415 size_t dst_size, copy_size;
1416 void *dst = hw->pcm_ops->get_buffer_out(hw, &dst_size);
1417 copy_size = MIN(size, dst_size);
1418
1419 memcpy(dst, buf, copy_size);
1420 return hw->pcm_ops->put_buffer_out(hw, buf, copy_size);
1421 }
1422
1423 size_t audio_generic_read(HWVoiceIn *hw, void *buf, size_t size)
1424 {
1425 size_t dst_size, copy_size;
1426 void *dst = hw->pcm_ops->get_buffer_in(hw, &dst_size);
1427 copy_size = MIN(size, dst_size);
1428
1429 memcpy(dst, buf, copy_size);
1430 hw->pcm_ops->put_buffer_in(hw, buf, copy_size);
1431 return copy_size;
1432 }
1433
1434
1435 static int audio_driver_init(AudioState *s, struct audio_driver *drv,
1436 bool msg, Audiodev *dev)
1437 {
1438 s->drv_opaque = drv->init(dev);
1439
1440 if (s->drv_opaque) {
1441 if (!drv->pcm_ops->get_buffer_in) {
1442 drv->pcm_ops->get_buffer_in = audio_generic_get_buffer_in;
1443 drv->pcm_ops->put_buffer_in = audio_generic_put_buffer_in;
1444 }
1445 if (!drv->pcm_ops->get_buffer_out) {
1446 drv->pcm_ops->get_buffer_out = audio_generic_get_buffer_out;
1447 drv->pcm_ops->put_buffer_out = audio_generic_put_buffer_out;
1448 }
1449
1450 audio_init_nb_voices_out(s, drv);
1451 audio_init_nb_voices_in(s, drv);
1452 s->drv = drv;
1453 return 0;
1454 }
1455 else {
1456 if (msg) {
1457 dolog("Could not init `%s' audio driver\n", drv->name);
1458 }
1459 return -1;
1460 }
1461 }
1462
1463 static void audio_vm_change_state_handler (void *opaque, int running,
1464 RunState state)
1465 {
1466 AudioState *s = opaque;
1467 HWVoiceOut *hwo = NULL;
1468 HWVoiceIn *hwi = NULL;
1469 int op = running ? VOICE_ENABLE : VOICE_DISABLE;
1470
1471 s->vm_running = running;
1472 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
1473 hwo->pcm_ops->ctl_out(hwo, op);
1474 }
1475
1476 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
1477 hwi->pcm_ops->ctl_in(hwi, op);
1478 }
1479 audio_reset_timer (s);
1480 }
1481
1482 static bool is_cleaning_up;
1483
1484 bool audio_is_cleaning_up(void)
1485 {
1486 return is_cleaning_up;
1487 }
1488
1489 static void free_audio_state(AudioState *s)
1490 {
1491 HWVoiceOut *hwo, *hwon;
1492 HWVoiceIn *hwi, *hwin;
1493
1494 QLIST_FOREACH_SAFE(hwo, &s->hw_head_out, entries, hwon) {
1495 SWVoiceCap *sc;
1496
1497 if (hwo->enabled) {
1498 hwo->pcm_ops->ctl_out (hwo, VOICE_DISABLE);
1499 }
1500 hwo->pcm_ops->fini_out (hwo);
1501
1502 for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1503 CaptureVoiceOut *cap = sc->cap;
1504 struct capture_callback *cb;
1505
1506 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1507 cb->ops.destroy (cb->opaque);
1508 }
1509 }
1510 QLIST_REMOVE(hwo, entries);
1511 }
1512
1513 QLIST_FOREACH_SAFE(hwi, &s->hw_head_in, entries, hwin) {
1514 if (hwi->enabled) {
1515 hwi->pcm_ops->ctl_in (hwi, VOICE_DISABLE);
1516 }
1517 hwi->pcm_ops->fini_in (hwi);
1518 QLIST_REMOVE(hwi, entries);
1519 }
1520
1521 if (s->drv) {
1522 s->drv->fini (s->drv_opaque);
1523 s->drv = NULL;
1524 }
1525
1526 if (s->dev) {
1527 qapi_free_Audiodev(s->dev);
1528 s->dev = NULL;
1529 }
1530
1531 if (s->ts) {
1532 timer_free(s->ts);
1533 s->ts = NULL;
1534 }
1535
1536 g_free(s);
1537 }
1538
1539 void audio_cleanup(void)
1540 {
1541 is_cleaning_up = true;
1542 while (!QTAILQ_EMPTY(&audio_states)) {
1543 AudioState *s = QTAILQ_FIRST(&audio_states);
1544 QTAILQ_REMOVE(&audio_states, s, list);
1545 free_audio_state(s);
1546 }
1547 }
1548
1549 static const VMStateDescription vmstate_audio = {
1550 .name = "audio",
1551 .version_id = 1,
1552 .minimum_version_id = 1,
1553 .fields = (VMStateField[]) {
1554 VMSTATE_END_OF_LIST()
1555 }
1556 };
1557
1558 static void audio_validate_opts(Audiodev *dev, Error **errp);
1559
1560 static AudiodevListEntry *audiodev_find(
1561 AudiodevListHead *head, const char *drvname)
1562 {
1563 AudiodevListEntry *e;
1564 QSIMPLEQ_FOREACH(e, head, next) {
1565 if (strcmp(AudiodevDriver_str(e->dev->driver), drvname) == 0) {
1566 return e;
1567 }
1568 }
1569
1570 return NULL;
1571 }
1572
1573 /*
1574 * if we have dev, this function was called because of an -audiodev argument =>
1575 * initialize a new state with it
1576 * if dev == NULL => legacy implicit initialization, return the already created
1577 * state or create a new one
1578 */
1579 static AudioState *audio_init(Audiodev *dev, const char *name)
1580 {
1581 static bool atexit_registered;
1582 size_t i;
1583 int done = 0;
1584 const char *drvname = NULL;
1585 VMChangeStateEntry *e;
1586 AudioState *s;
1587 struct audio_driver *driver;
1588 /* silence gcc warning about uninitialized variable */
1589 AudiodevListHead head = QSIMPLEQ_HEAD_INITIALIZER(head);
1590
1591 if (dev) {
1592 /* -audiodev option */
1593 legacy_config = false;
1594 drvname = AudiodevDriver_str(dev->driver);
1595 } else if (!QTAILQ_EMPTY(&audio_states)) {
1596 if (!legacy_config) {
1597 dolog("Device %s: audiodev default parameter is deprecated, please "
1598 "specify audiodev=%s\n", name,
1599 QTAILQ_FIRST(&audio_states)->dev->id);
1600 }
1601 return QTAILQ_FIRST(&audio_states);
1602 } else {
1603 /* legacy implicit initialization */
1604 head = audio_handle_legacy_opts();
1605 /*
1606 * In case of legacy initialization, all Audiodevs in the list will have
1607 * the same configuration (except the driver), so it does't matter which
1608 * one we chose. We need an Audiodev to set up AudioState before we can
1609 * init a driver. Also note that dev at this point is still in the
1610 * list.
1611 */
1612 dev = QSIMPLEQ_FIRST(&head)->dev;
1613 audio_validate_opts(dev, &error_abort);
1614 }
1615
1616 s = g_malloc0(sizeof(AudioState));
1617 s->dev = dev;
1618
1619 QLIST_INIT (&s->hw_head_out);
1620 QLIST_INIT (&s->hw_head_in);
1621 QLIST_INIT (&s->cap_head);
1622 if (!atexit_registered) {
1623 atexit(audio_cleanup);
1624 atexit_registered = true;
1625 }
1626 QTAILQ_INSERT_TAIL(&audio_states, s, list);
1627
1628 s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1629
1630 s->nb_hw_voices_out = audio_get_pdo_out(dev)->voices;
1631 s->nb_hw_voices_in = audio_get_pdo_in(dev)->voices;
1632
1633 if (s->nb_hw_voices_out <= 0) {
1634 dolog ("Bogus number of playback voices %d, setting to 1\n",
1635 s->nb_hw_voices_out);
1636 s->nb_hw_voices_out = 1;
1637 }
1638
1639 if (s->nb_hw_voices_in <= 0) {
1640 dolog ("Bogus number of capture voices %d, setting to 0\n",
1641 s->nb_hw_voices_in);
1642 s->nb_hw_voices_in = 0;
1643 }
1644
1645 if (drvname) {
1646 driver = audio_driver_lookup(drvname);
1647 if (driver) {
1648 done = !audio_driver_init(s, driver, true, dev);
1649 } else {
1650 dolog ("Unknown audio driver `%s'\n", drvname);
1651 }
1652 } else {
1653 for (i = 0; audio_prio_list[i]; i++) {
1654 AudiodevListEntry *e = audiodev_find(&head, audio_prio_list[i]);
1655 driver = audio_driver_lookup(audio_prio_list[i]);
1656
1657 if (e && driver) {
1658 s->dev = dev = e->dev;
1659 audio_validate_opts(dev, &error_abort);
1660 done = !audio_driver_init(s, driver, false, dev);
1661 if (done) {
1662 e->dev = NULL;
1663 break;
1664 }
1665 }
1666 }
1667 }
1668 audio_free_audiodev_list(&head);
1669
1670 if (!done) {
1671 driver = audio_driver_lookup("none");
1672 done = !audio_driver_init(s, driver, false, dev);
1673 assert(done);
1674 dolog("warning: Using timer based audio emulation\n");
1675 }
1676
1677 if (dev->timer_period <= 0) {
1678 s->period_ticks = 1;
1679 } else {
1680 s->period_ticks = dev->timer_period * SCALE_US;
1681 }
1682
1683 e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1684 if (!e) {
1685 dolog ("warning: Could not register change state handler\n"
1686 "(Audio can continue looping even after stopping the VM)\n");
1687 }
1688
1689 QLIST_INIT (&s->card_head);
1690 vmstate_register (NULL, 0, &vmstate_audio, s);
1691 return s;
1692 }
1693
1694 void audio_free_audiodev_list(AudiodevListHead *head)
1695 {
1696 AudiodevListEntry *e;
1697 while ((e = QSIMPLEQ_FIRST(head))) {
1698 QSIMPLEQ_REMOVE_HEAD(head, next);
1699 qapi_free_Audiodev(e->dev);
1700 g_free(e);
1701 }
1702 }
1703
1704 void AUD_register_card (const char *name, QEMUSoundCard *card)
1705 {
1706 if (!card->state) {
1707 card->state = audio_init(NULL, name);
1708 }
1709
1710 card->name = g_strdup (name);
1711 memset (&card->entries, 0, sizeof (card->entries));
1712 QLIST_INSERT_HEAD(&card->state->card_head, card, entries);
1713 }
1714
1715 void AUD_remove_card (QEMUSoundCard *card)
1716 {
1717 QLIST_REMOVE (card, entries);
1718 g_free (card->name);
1719 }
1720
1721
1722 CaptureVoiceOut *AUD_add_capture(
1723 AudioState *s,
1724 struct audsettings *as,
1725 struct audio_capture_ops *ops,
1726 void *cb_opaque
1727 )
1728 {
1729 CaptureVoiceOut *cap;
1730 struct capture_callback *cb;
1731
1732 if (!s) {
1733 if (!legacy_config) {
1734 dolog("Capturing without setting an audiodev is deprecated\n");
1735 }
1736 s = audio_init(NULL, NULL);
1737 }
1738
1739 if (audio_validate_settings (as)) {
1740 dolog ("Invalid settings were passed when trying to add capture\n");
1741 audio_print_settings (as);
1742 return NULL;
1743 }
1744
1745 cb = g_malloc0(sizeof(*cb));
1746 cb->ops = *ops;
1747 cb->opaque = cb_opaque;
1748
1749 cap = audio_pcm_capture_find_specific(s, as);
1750 if (cap) {
1751 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1752 return cap;
1753 }
1754 else {
1755 HWVoiceOut *hw;
1756 CaptureVoiceOut *cap;
1757
1758 cap = g_malloc0(sizeof(*cap));
1759
1760 hw = &cap->hw;
1761 hw->s = s;
1762 QLIST_INIT (&hw->sw_head);
1763 QLIST_INIT (&cap->cb_head);
1764
1765 /* XXX find a more elegant way */
1766 hw->samples = 4096 * 4;
1767 hw->mix_buf = g_new0(struct st_sample, hw->samples);
1768
1769 audio_pcm_init_info (&hw->info, as);
1770
1771 cap->buf = g_malloc0_n(hw->samples, 1 << hw->info.shift);
1772
1773 hw->clip = mixeng_clip
1774 [hw->info.nchannels == 2]
1775 [hw->info.sign]
1776 [hw->info.swap_endianness]
1777 [audio_bits_to_index (hw->info.bits)];
1778
1779 QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1780 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1781
1782 QLIST_FOREACH(hw, &s->hw_head_out, entries) {
1783 audio_attach_capture (hw);
1784 }
1785 return cap;
1786 }
1787 }
1788
1789 void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1790 {
1791 struct capture_callback *cb;
1792
1793 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1794 if (cb->opaque == cb_opaque) {
1795 cb->ops.destroy (cb_opaque);
1796 QLIST_REMOVE (cb, entries);
1797 g_free (cb);
1798
1799 if (!cap->cb_head.lh_first) {
1800 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
1801
1802 while (sw) {
1803 SWVoiceCap *sc = (SWVoiceCap *) sw;
1804 #ifdef DEBUG_CAPTURE
1805 dolog ("freeing %s\n", sw->name);
1806 #endif
1807
1808 sw1 = sw->entries.le_next;
1809 if (sw->rate) {
1810 st_rate_stop (sw->rate);
1811 sw->rate = NULL;
1812 }
1813 QLIST_REMOVE (sw, entries);
1814 QLIST_REMOVE (sc, entries);
1815 g_free (sc);
1816 sw = sw1;
1817 }
1818 QLIST_REMOVE (cap, entries);
1819 g_free (cap->hw.mix_buf);
1820 g_free (cap->buf);
1821 g_free (cap);
1822 }
1823 return;
1824 }
1825 }
1826 }
1827
1828 void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
1829 {
1830 if (sw) {
1831 HWVoiceOut *hw = sw->hw;
1832
1833 sw->vol.mute = mute;
1834 sw->vol.l = nominal_volume.l * lvol / 255;
1835 sw->vol.r = nominal_volume.r * rvol / 255;
1836
1837 if (hw->pcm_ops->ctl_out) {
1838 hw->pcm_ops->ctl_out (hw, VOICE_VOLUME, sw);
1839 }
1840 }
1841 }
1842
1843 void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
1844 {
1845 if (sw) {
1846 HWVoiceIn *hw = sw->hw;
1847
1848 sw->vol.mute = mute;
1849 sw->vol.l = nominal_volume.l * lvol / 255;
1850 sw->vol.r = nominal_volume.r * rvol / 255;
1851
1852 if (hw->pcm_ops->ctl_in) {
1853 hw->pcm_ops->ctl_in (hw, VOICE_VOLUME, sw);
1854 }
1855 }
1856 }
1857
1858 void audio_create_pdos(Audiodev *dev)
1859 {
1860 switch (dev->driver) {
1861 #define CASE(DRIVER, driver, pdo_name) \
1862 case AUDIODEV_DRIVER_##DRIVER: \
1863 if (!dev->u.driver.has_in) { \
1864 dev->u.driver.in = g_malloc0( \
1865 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
1866 dev->u.driver.has_in = true; \
1867 } \
1868 if (!dev->u.driver.has_out) { \
1869 dev->u.driver.out = g_malloc0( \
1870 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
1871 dev->u.driver.has_out = true; \
1872 } \
1873 break
1874
1875 CASE(NONE, none, );
1876 CASE(ALSA, alsa, Alsa);
1877 CASE(COREAUDIO, coreaudio, Coreaudio);
1878 CASE(DSOUND, dsound, );
1879 CASE(OSS, oss, Oss);
1880 CASE(PA, pa, Pa);
1881 CASE(SDL, sdl, );
1882 CASE(SPICE, spice, );
1883 CASE(WAV, wav, );
1884
1885 case AUDIODEV_DRIVER__MAX:
1886 abort();
1887 };
1888 }
1889
1890 static void audio_validate_per_direction_opts(
1891 AudiodevPerDirectionOptions *pdo, Error **errp)
1892 {
1893 if (!pdo->has_fixed_settings) {
1894 pdo->has_fixed_settings = true;
1895 pdo->fixed_settings = true;
1896 }
1897 if (!pdo->fixed_settings &&
1898 (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
1899 error_setg(errp,
1900 "You can't use frequency, channels or format with fixed-settings=off");
1901 return;
1902 }
1903
1904 if (!pdo->has_frequency) {
1905 pdo->has_frequency = true;
1906 pdo->frequency = 44100;
1907 }
1908 if (!pdo->has_channels) {
1909 pdo->has_channels = true;
1910 pdo->channels = 2;
1911 }
1912 if (!pdo->has_voices) {
1913 pdo->has_voices = true;
1914 pdo->voices = 1;
1915 }
1916 if (!pdo->has_format) {
1917 pdo->has_format = true;
1918 pdo->format = AUDIO_FORMAT_S16;
1919 }
1920 }
1921
1922 static void audio_validate_opts(Audiodev *dev, Error **errp)
1923 {
1924 Error *err = NULL;
1925
1926 audio_create_pdos(dev);
1927
1928 audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
1929 if (err) {
1930 error_propagate(errp, err);
1931 return;
1932 }
1933
1934 audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
1935 if (err) {
1936 error_propagate(errp, err);
1937 return;
1938 }
1939
1940 if (!dev->has_timer_period) {
1941 dev->has_timer_period = true;
1942 dev->timer_period = 10000; /* 100Hz -> 10ms */
1943 }
1944 }
1945
1946 void audio_parse_option(const char *opt)
1947 {
1948 AudiodevListEntry *e;
1949 Audiodev *dev = NULL;
1950
1951 Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
1952 visit_type_Audiodev(v, NULL, &dev, &error_fatal);
1953 visit_free(v);
1954
1955 audio_validate_opts(dev, &error_fatal);
1956
1957 e = g_malloc0(sizeof(AudiodevListEntry));
1958 e->dev = dev;
1959 QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
1960 }
1961
1962 void audio_init_audiodevs(void)
1963 {
1964 AudiodevListEntry *e;
1965
1966 QSIMPLEQ_FOREACH(e, &audiodevs, next) {
1967 audio_init(e->dev, NULL);
1968 }
1969 }
1970
1971 audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
1972 {
1973 return (audsettings) {
1974 .freq = pdo->frequency,
1975 .nchannels = pdo->channels,
1976 .fmt = pdo->format,
1977 .endianness = AUDIO_HOST_ENDIANNESS,
1978 };
1979 }
1980
1981 int audioformat_bytes_per_sample(AudioFormat fmt)
1982 {
1983 switch (fmt) {
1984 case AUDIO_FORMAT_U8:
1985 case AUDIO_FORMAT_S8:
1986 return 1;
1987
1988 case AUDIO_FORMAT_U16:
1989 case AUDIO_FORMAT_S16:
1990 return 2;
1991
1992 case AUDIO_FORMAT_U32:
1993 case AUDIO_FORMAT_S32:
1994 return 4;
1995
1996 case AUDIO_FORMAT__MAX:
1997 ;
1998 }
1999 abort();
2000 }
2001
2002
2003 /* frames = freq * usec / 1e6 */
2004 int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
2005 audsettings *as, int def_usecs)
2006 {
2007 uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
2008 return (as->freq * usecs + 500000) / 1000000;
2009 }
2010
2011 /* samples = channels * frames = channels * freq * usec / 1e6 */
2012 int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
2013 audsettings *as, int def_usecs)
2014 {
2015 return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
2016 }
2017
2018 /*
2019 * bytes = bytes_per_sample * samples =
2020 * bytes_per_sample * channels * freq * usec / 1e6
2021 */
2022 int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
2023 audsettings *as, int def_usecs)
2024 {
2025 return audio_buffer_samples(pdo, as, def_usecs) *
2026 audioformat_bytes_per_sample(as->fmt);
2027 }
2028
2029 AudioState *audio_state_by_name(const char *name)
2030 {
2031 AudioState *s;
2032 QTAILQ_FOREACH(s, &audio_states, list) {
2033 assert(s->dev);
2034 if (strcmp(name, s->dev->id) == 0) {
2035 return s;
2036 }
2037 }
2038 return NULL;
2039 }
2040
2041 const char *audio_get_id(QEMUSoundCard *card)
2042 {
2043 if (card->state) {
2044 assert(card->state->dev);
2045 return card->state->dev->id;
2046 } else {
2047 return "";
2048 }
2049 }