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