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