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