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