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