]> git.ipfire.org Git - thirdparty/qemu.git/blame - audio/audio.c
Use g_new() & friends where that makes obvious sense
[thirdparty/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");
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);
8e30d39b 140 abort();
f941aa25
TS
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);
8e30d39b 158 abort();
c0fe3827
FB
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);
6c6886bd 347 } else {
f941aa25
TS
348 switch (info->bits) {
349 case 8:
2b9cce8c 350 memset(buf, 0x80, len * info->bytes_per_frame);
f941aa25 351 break;
1d14ffa9 352
f941aa25
TS
353 case 16:
354 {
355 int i;
356 uint16_t *p = buf;
f941aa25
TS
357 short s = INT16_MAX;
358
359 if (info->swap_endianness) {
360 s = bswap16 (s);
361 }
362
2b9cce8c 363 for (i = 0; i < len * info->nchannels; i++) {
f941aa25
TS
364 p[i] = s;
365 }
1d14ffa9 366 }
f941aa25
TS
367 break;
368
369 case 32:
370 {
371 int i;
372 uint32_t *p = buf;
f941aa25
TS
373 int32_t s = INT32_MAX;
374
375 if (info->swap_endianness) {
376 s = bswap32 (s);
377 }
1d14ffa9 378
2b9cce8c 379 for (i = 0; i < len * info->nchannels; i++) {
f941aa25
TS
380 p[i] = s;
381 }
1d14ffa9 382 }
f941aa25
TS
383 break;
384
385 default:
386 AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
387 info->bits);
388 break;
1d14ffa9 389 }
85571bc7
FB
390 }
391}
392
8ead62cf
FB
393/*
394 * Capture
395 */
00e07679 396static void noop_conv (struct st_sample *dst, const void *src, int samples)
8ead62cf
FB
397{
398 (void) src;
399 (void) dst;
400 (void) samples;
8ead62cf
FB
401}
402
526fb058
KZ
403static CaptureVoiceOut *audio_pcm_capture_find_specific(AudioState *s,
404 struct audsettings *as)
8ead62cf
FB
405{
406 CaptureVoiceOut *cap;
8ead62cf
FB
407
408 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
d929eba5 409 if (audio_pcm_info_eq (&cap->hw.info, as)) {
8ead62cf
FB
410 return cap;
411 }
412 }
413 return NULL;
414}
415
ec36b695 416static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
8ead62cf 417{
ec36b695
FB
418 struct capture_callback *cb;
419
420#ifdef DEBUG_CAPTURE
421 dolog ("notification %d sent\n", cmd);
422#endif
423 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
424 cb->ops.notify (cb->opaque, cmd);
425 }
426}
8ead62cf 427
ec36b695
FB
428static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
429{
430 if (cap->hw.enabled != enabled) {
431 audcnotification_e cmd;
8ead62cf 432 cap->hw.enabled = enabled;
ec36b695
FB
433 cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
434 audio_notify_capture (cap, cmd);
8ead62cf
FB
435 }
436}
437
438static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
439{
440 HWVoiceOut *hw = &cap->hw;
441 SWVoiceOut *sw;
442 int enabled = 0;
443
ec36b695 444 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
8ead62cf
FB
445 if (sw->active) {
446 enabled = 1;
447 break;
448 }
449 }
ec36b695 450 audio_capture_maybe_changed (cap, enabled);
8ead62cf
FB
451}
452
453static void audio_detach_capture (HWVoiceOut *hw)
454{
ec36b695
FB
455 SWVoiceCap *sc = hw->cap_head.lh_first;
456
457 while (sc) {
458 SWVoiceCap *sc1 = sc->entries.le_next;
459 SWVoiceOut *sw = &sc->sw;
460 CaptureVoiceOut *cap = sc->cap;
461 int was_active = sw->active;
8ead62cf 462
8ead62cf
FB
463 if (sw->rate) {
464 st_rate_stop (sw->rate);
465 sw->rate = NULL;
466 }
467
72cf2d4f
BS
468 QLIST_REMOVE (sw, entries);
469 QLIST_REMOVE (sc, entries);
7267c094 470 g_free (sc);
ec36b695
FB
471 if (was_active) {
472 /* We have removed soft voice from the capture:
473 this might have changed the overall status of the capture
474 since this might have been the only active voice */
475 audio_recalc_and_notify_capture (cap);
476 }
477 sc = sc1;
8ead62cf
FB
478 }
479}
480
1a7dafce 481static int audio_attach_capture (HWVoiceOut *hw)
8ead62cf 482{
526fb058 483 AudioState *s = hw->s;
8ead62cf
FB
484 CaptureVoiceOut *cap;
485
486 audio_detach_capture (hw);
487 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
ec36b695 488 SWVoiceCap *sc;
8ead62cf 489 SWVoiceOut *sw;
ec36b695 490 HWVoiceOut *hw_cap = &cap->hw;
8ead62cf 491
e8d85444 492 sc = g_malloc0(sizeof(*sc));
8ead62cf 493
ec36b695
FB
494 sc->cap = cap;
495 sw = &sc->sw;
8ead62cf 496 sw->hw = hw_cap;
ec36b695 497 sw->info = hw->info;
8ead62cf
FB
498 sw->empty = 1;
499 sw->active = hw->enabled;
500 sw->conv = noop_conv;
501 sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
83617103 502 sw->vol = nominal_volume;
8ead62cf
FB
503 sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
504 if (!sw->rate) {
505 dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
7267c094 506 g_free (sw);
8ead62cf
FB
507 return -1;
508 }
72cf2d4f
BS
509 QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
510 QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
ec36b695 511#ifdef DEBUG_CAPTURE
457b6543
SW
512 sw->name = g_strdup_printf ("for %p %d,%d,%d",
513 hw, sw->info.freq, sw->info.bits,
514 sw->info.nchannels);
ec36b695
FB
515 dolog ("Added %s active = %d\n", sw->name, sw->active);
516#endif
8ead62cf 517 if (sw->active) {
ec36b695 518 audio_capture_maybe_changed (cap, 1);
8ead62cf
FB
519 }
520 }
521 return 0;
522}
523
1d14ffa9
FB
524/*
525 * Hard voice (capture)
526 */
7520462b 527static size_t audio_pcm_hw_find_min_in (HWVoiceIn *hw)
85571bc7 528{
1d14ffa9 529 SWVoiceIn *sw;
7520462b 530 size_t m = hw->total_samples_captured;
1d14ffa9
FB
531
532 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
533 if (sw->active) {
58935915 534 m = MIN (m, sw->total_hw_samples_acquired);
1d14ffa9 535 }
85571bc7 536 }
1d14ffa9 537 return m;
85571bc7
FB
538}
539
3f5bbfc2 540static size_t audio_pcm_hw_get_live_in(HWVoiceIn *hw)
85571bc7 541{
7520462b 542 size_t live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
dc88e38f
KZ
543 if (audio_bug(__func__, live > hw->conv_buf->size)) {
544 dolog("live=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
8e30d39b 545 abort();
85571bc7 546 }
1d14ffa9 547 return live;
85571bc7
FB
548}
549
251f1549
VR
550static size_t audio_pcm_hw_conv_in(HWVoiceIn *hw, void *pcm_buf, size_t samples)
551{
552 size_t conv = 0;
553 STSampleBuffer *conv_buf = hw->conv_buf;
554
555 while (samples) {
556 uint8_t *src = advance(pcm_buf, conv * hw->info.bytes_per_frame);
557 size_t proc = MIN(samples, conv_buf->size - conv_buf->pos);
558
559 hw->conv(conv_buf->samples + conv_buf->pos, src, proc);
560 conv_buf->pos = (conv_buf->pos + proc) % conv_buf->size;
561 samples -= proc;
562 conv += proc;
563 }
564
565 return conv;
566}
567
1d14ffa9
FB
568/*
569 * Soft voice (capture)
570 */
7520462b 571static size_t audio_pcm_sw_read(SWVoiceIn *sw, void *buf, size_t size)
85571bc7 572{
1d14ffa9 573 HWVoiceIn *hw = sw->hw;
7520462b 574 size_t samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
1ea879e5 575 struct st_sample *src, *dst = sw->buf;
1d14ffa9 576
1d14ffa9 577 live = hw->total_samples_captured - sw->total_hw_samples_acquired;
0ceb26af
VR
578 if (!live) {
579 return 0;
580 }
dc88e38f
KZ
581 if (audio_bug(__func__, live > hw->conv_buf->size)) {
582 dolog("live_in=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
8e30d39b 583 abort();
1d14ffa9
FB
584 }
585
0ceb26af
VR
586 rpos = audio_ring_posb(hw->conv_buf->pos, live, hw->conv_buf->size);
587
2b9cce8c 588 samples = size / sw->info.bytes_per_frame;
85571bc7 589
1d14ffa9 590 swlim = (live * sw->ratio) >> 32;
58935915 591 swlim = MIN (swlim, samples);
85571bc7 592
1d14ffa9 593 while (swlim) {
dc88e38f
KZ
594 src = hw->conv_buf->samples + rpos;
595 if (hw->conv_buf->pos > rpos) {
596 isamp = hw->conv_buf->pos - rpos;
7520462b 597 } else {
dc88e38f 598 isamp = hw->conv_buf->size - rpos;
1d14ffa9 599 }
85571bc7 600
1d14ffa9
FB
601 if (!isamp) {
602 break;
603 }
604 osamp = swlim;
85571bc7 605
1d14ffa9
FB
606 st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
607 swlim -= osamp;
dc88e38f 608 rpos = (rpos + isamp) % hw->conv_buf->size;
1d14ffa9
FB
609 dst += osamp;
610 ret += osamp;
611 total += isamp;
612 }
85571bc7 613
669b9522 614 if (!hw->pcm_ops->volume_in) {
c01b2456
MAL
615 mixeng_volume (sw->buf, ret, &sw->vol);
616 }
00e07679 617
571ec3d6 618 sw->clip (buf, sw->buf, ret);
1d14ffa9 619 sw->total_hw_samples_acquired += total;
2b9cce8c 620 return ret * sw->info.bytes_per_frame;
85571bc7
FB
621}
622
1d14ffa9
FB
623/*
624 * Hard voice (playback)
625 */
7520462b 626static size_t audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
1d14ffa9 627{
c0fe3827 628 SWVoiceOut *sw;
7520462b 629 size_t m = SIZE_MAX;
c0fe3827 630 int nb_live = 0;
85571bc7 631
c0fe3827
FB
632 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
633 if (sw->active || !sw->empty) {
58935915 634 m = MIN (m, sw->total_hw_samples_mixed);
c0fe3827
FB
635 nb_live += 1;
636 }
85571bc7 637 }
c0fe3827
FB
638
639 *nb_livep = nb_live;
640 return m;
1d14ffa9 641}
85571bc7 642
7520462b 643static size_t audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
1d14ffa9 644{
7520462b 645 size_t smin;
bdff253c 646 int nb_live1;
85571bc7 647
bdff253c 648 smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
649 if (nb_live) {
650 *nb_live = nb_live1;
85571bc7 651 }
bdff253c 652
653 if (nb_live1) {
7520462b 654 size_t live = smin;
1d14ffa9 655
dc88e38f
KZ
656 if (audio_bug(__func__, live > hw->mix_buf->size)) {
657 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
8e30d39b 658 abort();
85571bc7 659 }
1d14ffa9 660 return live;
85571bc7 661 }
bdff253c 662 return 0;
85571bc7
FB
663}
664
9833438e
VR
665static size_t audio_pcm_hw_get_free(HWVoiceOut *hw)
666{
667 return (hw->pcm_ops->buffer_get_free ? hw->pcm_ops->buffer_get_free(hw) :
668 INT_MAX) / hw->info.bytes_per_frame;
669}
670
8e56a172
VR
671static void audio_pcm_hw_clip_out(HWVoiceOut *hw, void *pcm_buf, size_t len)
672{
673 size_t clipped = 0;
674 size_t pos = hw->mix_buf->pos;
675
676 while (len) {
677 st_sample *src = hw->mix_buf->samples + pos;
678 uint8_t *dst = advance(pcm_buf, clipped * hw->info.bytes_per_frame);
679 size_t samples_till_end_of_buf = hw->mix_buf->size - pos;
680 size_t samples_to_clip = MIN(len, samples_till_end_of_buf);
681
682 hw->clip(dst, src, samples_to_clip);
683
684 pos = (pos + samples_to_clip) % hw->mix_buf->size;
685 len -= samples_to_clip;
686 clipped += samples_to_clip;
687 }
688}
689
1d14ffa9
FB
690/*
691 * Soft voice (playback)
692 */
7520462b 693static size_t audio_pcm_sw_write(SWVoiceOut *sw, void *buf, size_t size)
85571bc7 694{
9833438e
VR
695 size_t hwsamples, samples, isamp, osamp, wpos, live, dead, left, blck;
696 size_t hw_free;
7520462b 697 size_t ret = 0, pos = 0, total = 0;
85571bc7 698
1d14ffa9
FB
699 if (!sw) {
700 return size;
701 }
85571bc7 702
dc88e38f 703 hwsamples = sw->hw->mix_buf->size;
85571bc7 704
1d14ffa9 705 live = sw->total_hw_samples_mixed;
7520462b 706 if (audio_bug(__func__, live > hwsamples)) {
dc88e38f 707 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hwsamples);
8e30d39b 708 abort();
1d14ffa9 709 }
85571bc7 710
1d14ffa9 711 if (live == hwsamples) {
ec36b695 712#ifdef DEBUG_OUT
0c29b786 713 dolog ("%s is full %zu\n", sw->name, live);
ec36b695 714#endif
1d14ffa9
FB
715 return 0;
716 }
85571bc7 717
dc88e38f 718 wpos = (sw->hw->mix_buf->pos + live) % hwsamples;
85571bc7 719
1d14ffa9 720 dead = hwsamples - live;
9833438e
VR
721 hw_free = audio_pcm_hw_get_free(sw->hw);
722 hw_free = hw_free > live ? hw_free - live : 0;
723 samples = ((int64_t)MIN(dead, hw_free) << 32) / sw->ratio;
724 samples = MIN(samples, size / sw->info.bytes_per_frame);
725 if (samples) {
726 sw->conv(sw->buf, buf, samples);
c01b2456 727
669b9522 728 if (!sw->hw->pcm_ops->volume_out) {
9833438e 729 mixeng_volume(sw->buf, samples, &sw->vol);
c01b2456 730 }
1d14ffa9
FB
731 }
732
9833438e 733 while (samples) {
1d14ffa9
FB
734 dead = hwsamples - live;
735 left = hwsamples - wpos;
58935915 736 blck = MIN (dead, left);
1d14ffa9
FB
737 if (!blck) {
738 break;
739 }
9833438e 740 isamp = samples;
1d14ffa9
FB
741 osamp = blck;
742 st_rate_flow_mix (
743 sw->rate,
744 sw->buf + pos,
dc88e38f 745 sw->hw->mix_buf->samples + wpos,
1d14ffa9
FB
746 &isamp,
747 &osamp
748 );
749 ret += isamp;
9833438e 750 samples -= isamp;
1d14ffa9
FB
751 pos += isamp;
752 live += osamp;
753 wpos = (wpos + osamp) % hwsamples;
754 total += osamp;
755 }
756
757 sw->total_hw_samples_mixed += total;
758 sw->empty = sw->total_hw_samples_mixed == 0;
759
760#ifdef DEBUG_OUT
761 dolog (
7520462b 762 "%s: write size %zu ret %zu total sw %zu\n",
c0fe3827 763 SW_NAME (sw),
2b9cce8c 764 size / sw->info.bytes_per_frame,
1d14ffa9 765 ret,
c0fe3827 766 sw->total_hw_samples_mixed
1d14ffa9
FB
767 );
768#endif
769
2b9cce8c 770 return ret * sw->info.bytes_per_frame;
85571bc7
FB
771}
772
1d14ffa9
FB
773#ifdef DEBUG_AUDIO
774static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
85571bc7 775{
ed2a4a79
KZ
776 dolog("%s: bits %d, sign %d, float %d, freq %d, nchan %d\n",
777 cap, info->bits, info->is_signed, info->is_float, info->freq,
778 info->nchannels);
85571bc7 779}
1d14ffa9 780#endif
85571bc7 781
1d14ffa9
FB
782#define DAC
783#include "audio_template.h"
784#undef DAC
785#include "audio_template.h"
786
713a98f8 787/*
788 * Timer
789 */
526fb058 790static int audio_is_timer_needed(AudioState *s)
713a98f8 791{
792 HWVoiceIn *hwi = NULL;
793 HWVoiceOut *hwo = NULL;
794
526fb058 795 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
6c6886bd
ZH
796 if (!hwo->poll_mode) {
797 return 1;
798 }
713a98f8 799 }
526fb058 800 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
6c6886bd
ZH
801 if (!hwi->poll_mode) {
802 return 1;
803 }
713a98f8 804 }
805 return 0;
806}
807
39deb1e4 808static void audio_reset_timer (AudioState *s)
713a98f8 809{
526fb058 810 if (audio_is_timer_needed(s)) {
1ffc2665 811 timer_mod_anticipate_ns(s->ts,
71830221 812 qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
526fb058
KZ
813 if (!s->timer_running) {
814 s->timer_running = true;
815 s->timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
71830221 816 trace_audio_timer_start(s->period_ticks / SCALE_MS);
1a961e78
GH
817 }
818 } else {
819 timer_del(s->ts);
526fb058
KZ
820 if (s->timer_running) {
821 s->timer_running = false;
1a961e78
GH
822 trace_audio_timer_stop();
823 }
713a98f8 824 }
825}
826
39deb1e4 827static void audio_timer (void *opaque)
828{
1a961e78 829 int64_t now, diff;
71830221 830 AudioState *s = opaque;
1a961e78
GH
831
832 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
526fb058 833 diff = now - s->timer_last;
71830221 834 if (diff > s->period_ticks * 3 / 2) {
1a961e78
GH
835 trace_audio_timer_delayed(diff / SCALE_MS);
836 }
526fb058 837 s->timer_last = now;
1a961e78 838
18e2c177 839 audio_run(s, "timer");
71830221 840 audio_reset_timer(s);
39deb1e4 841}
842
713a98f8 843/*
844 * Public API
845 */
7520462b 846size_t AUD_write(SWVoiceOut *sw, void *buf, size_t size)
85571bc7 847{
1930616b
KZ
848 HWVoiceOut *hw;
849
1d14ffa9
FB
850 if (!sw) {
851 /* XXX: Consider options */
852 return size;
853 }
1930616b 854 hw = sw->hw;
85571bc7 855
1930616b 856 if (!hw->enabled) {
c0fe3827 857 dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
85571bc7
FB
858 return 0;
859 }
860
1930616b
KZ
861 if (audio_get_pdo_out(hw->s->dev)->mixing_engine) {
862 return audio_pcm_sw_write(sw, buf, size);
863 } else {
864 return hw->pcm_ops->write(hw, buf, size);
865 }
1d14ffa9
FB
866}
867
7520462b 868size_t AUD_read(SWVoiceIn *sw, void *buf, size_t size)
1d14ffa9 869{
1930616b
KZ
870 HWVoiceIn *hw;
871
1d14ffa9
FB
872 if (!sw) {
873 /* XXX: Consider options */
874 return size;
85571bc7 875 }
1930616b 876 hw = sw->hw;
1d14ffa9 877
1930616b 878 if (!hw->enabled) {
c0fe3827 879 dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
1d14ffa9 880 return 0;
85571bc7 881 }
1d14ffa9 882
1930616b
KZ
883 if (audio_get_pdo_in(hw->s->dev)->mixing_engine) {
884 return audio_pcm_sw_read(sw, buf, size);
885 } else {
886 return hw->pcm_ops->read(hw, buf, size);
887 }
85571bc7
FB
888}
889
69ac0786 890int AUD_get_buffer_size_out(SWVoiceOut *sw)
85571bc7 891{
69ac0786 892 return sw->hw->samples * sw->hw->info.bytes_per_frame;
1d14ffa9
FB
893}
894
895void AUD_set_active_out (SWVoiceOut *sw, int on)
896{
897 HWVoiceOut *hw;
85571bc7 898
1d14ffa9 899 if (!sw) {
85571bc7 900 return;
1d14ffa9 901 }
85571bc7
FB
902
903 hw = sw->hw;
1d14ffa9 904 if (sw->active != on) {
526fb058 905 AudioState *s = sw->s;
1d14ffa9 906 SWVoiceOut *temp_sw;
ec36b695 907 SWVoiceCap *sc;
1d14ffa9
FB
908
909 if (on) {
1d14ffa9
FB
910 hw->pending_disable = 0;
911 if (!hw->enabled) {
912 hw->enabled = 1;
978dd635 913 if (s->vm_running) {
571a8c52
KZ
914 if (hw->pcm_ops->enable_out) {
915 hw->pcm_ops->enable_out(hw, true);
916 }
39deb1e4 917 audio_reset_timer (s);
978dd635 918 }
1d14ffa9 919 }
6c6886bd 920 } else {
1d14ffa9
FB
921 if (hw->enabled) {
922 int nb_active = 0;
923
924 for (temp_sw = hw->sw_head.lh_first; temp_sw;
925 temp_sw = temp_sw->entries.le_next) {
926 nb_active += temp_sw->active != 0;
927 }
928
929 hw->pending_disable = nb_active == 1;
930 }
85571bc7 931 }
ec36b695
FB
932
933 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
934 sc->sw.active = hw->enabled;
8ead62cf 935 if (hw->enabled) {
ec36b695 936 audio_capture_maybe_changed (sc->cap, 1);
8ead62cf
FB
937 }
938 }
1d14ffa9
FB
939 sw->active = on;
940 }
941}
942
943void AUD_set_active_in (SWVoiceIn *sw, int on)
944{
945 HWVoiceIn *hw;
946
947 if (!sw) {
948 return;
85571bc7
FB
949 }
950
1d14ffa9 951 hw = sw->hw;
85571bc7 952 if (sw->active != on) {
526fb058 953 AudioState *s = sw->s;
1d14ffa9
FB
954 SWVoiceIn *temp_sw;
955
85571bc7 956 if (on) {
85571bc7
FB
957 if (!hw->enabled) {
958 hw->enabled = 1;
978dd635 959 if (s->vm_running) {
571a8c52
KZ
960 if (hw->pcm_ops->enable_in) {
961 hw->pcm_ops->enable_in(hw, true);
962 }
39deb1e4 963 audio_reset_timer (s);
978dd635 964 }
85571bc7 965 }
1d14ffa9 966 sw->total_hw_samples_acquired = hw->total_samples_captured;
6c6886bd 967 } else {
1d14ffa9 968 if (hw->enabled) {
85571bc7 969 int nb_active = 0;
1d14ffa9
FB
970
971 for (temp_sw = hw->sw_head.lh_first; temp_sw;
972 temp_sw = temp_sw->entries.le_next) {
973 nb_active += temp_sw->active != 0;
85571bc7
FB
974 }
975
976 if (nb_active == 1) {
1d14ffa9 977 hw->enabled = 0;
571a8c52
KZ
978 if (hw->pcm_ops->enable_in) {
979 hw->pcm_ops->enable_in(hw, false);
980 }
85571bc7
FB
981 }
982 }
983 }
984 sw->active = on;
985 }
986}
987
7520462b 988static size_t audio_get_avail (SWVoiceIn *sw)
1d14ffa9 989{
7520462b 990 size_t live;
1d14ffa9
FB
991
992 if (!sw) {
993 return 0;
994 }
995
996 live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
dc88e38f
KZ
997 if (audio_bug(__func__, live > sw->hw->conv_buf->size)) {
998 dolog("live=%zu sw->hw->conv_buf->size=%zu\n", live,
999 sw->hw->conv_buf->size);
8e30d39b 1000 abort();
1d14ffa9
FB
1001 }
1002
1003 ldebug (
0c29b786 1004 "%s: get_avail live %zu ret %" PRId64 "\n",
c0fe3827 1005 SW_NAME (sw),
2b9cce8c 1006 live, (((int64_t) live << 32) / sw->ratio) * sw->info.bytes_per_frame
1d14ffa9
FB
1007 );
1008
2b9cce8c 1009 return (((int64_t) live << 32) / sw->ratio) * sw->info.bytes_per_frame;
1d14ffa9
FB
1010}
1011
9833438e
VR
1012static size_t audio_sw_bytes_free(SWVoiceOut *sw, size_t free)
1013{
1014 return (((int64_t)free << 32) / sw->ratio) * sw->info.bytes_per_frame;
1015}
1016
7520462b 1017static size_t audio_get_free(SWVoiceOut *sw)
1d14ffa9 1018{
7520462b 1019 size_t live, dead;
1d14ffa9
FB
1020
1021 if (!sw) {
1022 return 0;
1023 }
1024
1025 live = sw->total_hw_samples_mixed;
1026
dc88e38f
KZ
1027 if (audio_bug(__func__, live > sw->hw->mix_buf->size)) {
1028 dolog("live=%zu sw->hw->mix_buf->size=%zu\n", live,
1029 sw->hw->mix_buf->size);
8e30d39b 1030 abort();
1d14ffa9
FB
1031 }
1032
dc88e38f 1033 dead = sw->hw->mix_buf->size - live;
1d14ffa9
FB
1034
1035#ifdef DEBUG_OUT
9833438e
VR
1036 dolog("%s: get_free live %zu dead %zu sw_bytes %zu\n",
1037 SW_NAME(sw), live, dead, audio_sw_bytes_free(sw, dead));
85571bc7 1038#endif
1d14ffa9 1039
9833438e 1040 return dead;
1d14ffa9
FB
1041}
1042
7520462b
KZ
1043static void audio_capture_mix_and_clear(HWVoiceOut *hw, size_t rpos,
1044 size_t samples)
8ead62cf 1045{
7520462b 1046 size_t n;
8ead62cf
FB
1047
1048 if (hw->enabled) {
ec36b695 1049 SWVoiceCap *sc;
8ead62cf 1050
ec36b695
FB
1051 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1052 SWVoiceOut *sw = &sc->sw;
8ead62cf
FB
1053 int rpos2 = rpos;
1054
1055 n = samples;
1056 while (n) {
dc88e38f 1057 size_t till_end_of_hw = hw->mix_buf->size - rpos2;
7520462b 1058 size_t to_write = MIN(till_end_of_hw, n);
2b9cce8c 1059 size_t bytes = to_write * hw->info.bytes_per_frame;
7520462b 1060 size_t written;
8ead62cf 1061
dc88e38f 1062 sw->buf = hw->mix_buf->samples + rpos2;
8ead62cf
FB
1063 written = audio_pcm_sw_write (sw, NULL, bytes);
1064 if (written - bytes) {
7520462b
KZ
1065 dolog("Could not mix %zu bytes into a capture "
1066 "buffer, mixed %zu\n",
1067 bytes, written);
8ead62cf
FB
1068 break;
1069 }
1070 n -= to_write;
dc88e38f 1071 rpos2 = (rpos2 + to_write) % hw->mix_buf->size;
8ead62cf
FB
1072 }
1073 }
1074 }
1075
dc88e38f
KZ
1076 n = MIN(samples, hw->mix_buf->size - rpos);
1077 mixeng_clear(hw->mix_buf->samples + rpos, n);
1078 mixeng_clear(hw->mix_buf->samples, samples - n);
8ead62cf
FB
1079}
1080
ff095e52
KZ
1081static size_t audio_pcm_hw_run_out(HWVoiceOut *hw, size_t live)
1082{
1083 size_t clipped = 0;
1084
1085 while (live) {
aec6d0dc
VR
1086 size_t size = live * hw->info.bytes_per_frame;
1087 size_t decr, proc;
ff095e52 1088 void *buf = hw->pcm_ops->get_buffer_out(hw, &size);
4c3356f9
VR
1089
1090 if (size == 0) {
fb35c2ce 1091 break;
ff095e52
KZ
1092 }
1093
2b9cce8c 1094 decr = MIN(size / hw->info.bytes_per_frame, live);
4c3356f9
VR
1095 if (buf) {
1096 audio_pcm_hw_clip_out(hw, buf, decr);
1097 }
2b9cce8c
KZ
1098 proc = hw->pcm_ops->put_buffer_out(hw, buf,
1099 decr * hw->info.bytes_per_frame) /
1100 hw->info.bytes_per_frame;
ff095e52
KZ
1101
1102 live -= proc;
1103 clipped += proc;
dc88e38f 1104 hw->mix_buf->pos = (hw->mix_buf->pos + proc) % hw->mix_buf->size;
ff095e52
KZ
1105
1106 if (proc == 0 || proc < decr) {
1107 break;
1108 }
1109 }
1110
fdc8c5f4
VR
1111 if (hw->pcm_ops->run_buffer_out) {
1112 hw->pcm_ops->run_buffer_out(hw);
1113 }
1114
ff095e52
KZ
1115 return clipped;
1116}
1117
c0fe3827 1118static void audio_run_out (AudioState *s)
1d14ffa9
FB
1119{
1120 HWVoiceOut *hw = NULL;
1121 SWVoiceOut *sw;
1122
1930616b
KZ
1123 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1124 while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1125 /* there is exactly 1 sw for each hw with no mixeng */
1126 sw = hw->sw_head.lh_first;
1127
1128 if (hw->pending_disable) {
1129 hw->enabled = 0;
1130 hw->pending_disable = 0;
1131 if (hw->pcm_ops->enable_out) {
1132 hw->pcm_ops->enable_out(hw, false);
1133 }
1134 }
1135
1136 if (sw->active) {
1137 sw->callback.fn(sw->callback.opaque, INT_MAX);
1138 }
1139 }
1140 return;
1141 }
1142
526fb058 1143 while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
9833438e
VR
1144 size_t played, live, prev_rpos;
1145 size_t hw_free = audio_pcm_hw_get_free(hw);
6fb0cd50 1146 int nb_live;
1d14ffa9 1147
a806f959
VR
1148 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1149 if (sw->active) {
9833438e
VR
1150 size_t sw_free = audio_get_free(sw);
1151 size_t free;
1152
1153 if (hw_free > sw->total_hw_samples_mixed) {
1154 free = audio_sw_bytes_free(sw,
1155 MIN(sw_free, hw_free - sw->total_hw_samples_mixed));
1156 } else {
1157 free = 0;
1158 }
a806f959
VR
1159 if (free > 0) {
1160 sw->callback.fn(sw->callback.opaque, free);
1161 }
1162 }
1163 }
1164
bdff253c 1165 live = audio_pcm_hw_get_live_out (hw, &nb_live);
1d14ffa9
FB
1166 if (!nb_live) {
1167 live = 0;
1168 }
c0fe3827 1169
dc88e38f
KZ
1170 if (audio_bug(__func__, live > hw->mix_buf->size)) {
1171 dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
8e30d39b 1172 abort();
1d14ffa9
FB
1173 }
1174
1175 if (hw->pending_disable && !nb_live) {
ec36b695 1176 SWVoiceCap *sc;
1d14ffa9
FB
1177#ifdef DEBUG_OUT
1178 dolog ("Disabling voice\n");
85571bc7 1179#endif
1d14ffa9
FB
1180 hw->enabled = 0;
1181 hw->pending_disable = 0;
571a8c52
KZ
1182 if (hw->pcm_ops->enable_out) {
1183 hw->pcm_ops->enable_out(hw, false);
1184 }
ec36b695
FB
1185 for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1186 sc->sw.active = 0;
1187 audio_recalc_and_notify_capture (sc->cap);
8ead62cf 1188 }
1d14ffa9
FB
1189 continue;
1190 }
1191
1192 if (!live) {
a8a98cfd
VR
1193 if (hw->pcm_ops->run_buffer_out) {
1194 hw->pcm_ops->run_buffer_out(hw);
1195 }
1d14ffa9
FB
1196 continue;
1197 }
1198
dc88e38f 1199 prev_rpos = hw->mix_buf->pos;
3f5bbfc2 1200 played = audio_pcm_hw_run_out(hw, live);
3d4d16f4 1201 replay_audio_out(&played);
dc88e38f
KZ
1202 if (audio_bug(__func__, hw->mix_buf->pos >= hw->mix_buf->size)) {
1203 dolog("hw->mix_buf->pos=%zu hw->mix_buf->size=%zu played=%zu\n",
1204 hw->mix_buf->pos, hw->mix_buf->size, played);
8e30d39b 1205 abort();
1d14ffa9
FB
1206 }
1207
1208#ifdef DEBUG_OUT
7520462b 1209 dolog("played=%zu\n", played);
85571bc7 1210#endif
1d14ffa9
FB
1211
1212 if (played) {
1213 hw->ts_helper += played;
8ead62cf 1214 audio_capture_mix_and_clear (hw, prev_rpos, played);
1d14ffa9
FB
1215 }
1216
1217 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1d14ffa9
FB
1218 if (!sw->active && sw->empty) {
1219 continue;
1220 }
1221
470bcabd 1222 if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
7520462b
KZ
1223 dolog("played=%zu sw->total_hw_samples_mixed=%zu\n",
1224 played, sw->total_hw_samples_mixed);
8e30d39b 1225 abort();
1d14ffa9
FB
1226 }
1227
1228 sw->total_hw_samples_mixed -= played;
1229
1230 if (!sw->total_hw_samples_mixed) {
1231 sw->empty = 1;
1d14ffa9 1232 }
1d14ffa9
FB
1233 }
1234 }
1235}
1236
ff095e52
KZ
1237static size_t audio_pcm_hw_run_in(HWVoiceIn *hw, size_t samples)
1238{
1239 size_t conv = 0;
1240
a2893c83
VR
1241 if (hw->pcm_ops->run_buffer_in) {
1242 hw->pcm_ops->run_buffer_in(hw);
1243 }
1244
ff095e52
KZ
1245 while (samples) {
1246 size_t proc;
2b9cce8c 1247 size_t size = samples * hw->info.bytes_per_frame;
ff095e52
KZ
1248 void *buf = hw->pcm_ops->get_buffer_in(hw, &size);
1249
2b9cce8c 1250 assert(size % hw->info.bytes_per_frame == 0);
ff095e52 1251 if (size == 0) {
ff095e52
KZ
1252 break;
1253 }
1254
251f1549 1255 proc = audio_pcm_hw_conv_in(hw, buf, size / hw->info.bytes_per_frame);
ff095e52
KZ
1256
1257 samples -= proc;
1258 conv += proc;
2b9cce8c 1259 hw->pcm_ops->put_buffer_in(hw, buf, proc * hw->info.bytes_per_frame);
ff095e52
KZ
1260 }
1261
1262 return conv;
1263}
1264
c0fe3827 1265static void audio_run_in (AudioState *s)
1d14ffa9
FB
1266{
1267 HWVoiceIn *hw = NULL;
1268
1930616b
KZ
1269 if (!audio_get_pdo_in(s->dev)->mixing_engine) {
1270 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1271 /* there is exactly 1 sw for each hw with no mixeng */
1272 SWVoiceIn *sw = hw->sw_head.lh_first;
1273 if (sw->active) {
1274 sw->callback.fn(sw->callback.opaque, INT_MAX);
1275 }
1276 }
1277 return;
1278 }
1279
526fb058 1280 while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1d14ffa9 1281 SWVoiceIn *sw;
7520462b 1282 size_t captured = 0, min;
1d14ffa9 1283
3d4d16f4 1284 if (replay_mode != REPLAY_MODE_PLAY) {
3f5bbfc2 1285 captured = audio_pcm_hw_run_in(
dc88e38f 1286 hw, hw->conv_buf->size - audio_pcm_hw_get_live_in(hw));
3d4d16f4 1287 }
dc88e38f
KZ
1288 replay_audio_in(&captured, hw->conv_buf->samples, &hw->conv_buf->pos,
1289 hw->conv_buf->size);
1d14ffa9
FB
1290
1291 min = audio_pcm_hw_find_min_in (hw);
1292 hw->total_samples_captured += captured - min;
1293 hw->ts_helper += captured;
1294
1295 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1296 sw->total_hw_samples_acquired -= min;
1297
1298 if (sw->active) {
7520462b 1299 size_t avail;
1d14ffa9
FB
1300
1301 avail = audio_get_avail (sw);
1302 if (avail > 0) {
1303 sw->callback.fn (sw->callback.opaque, avail);
1304 }
1305 }
1306 }
1307 }
1308}
1309
8ead62cf
FB
1310static void audio_run_capture (AudioState *s)
1311{
1312 CaptureVoiceOut *cap;
1313
1314 for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
7520462b 1315 size_t live, rpos, captured;
8ead62cf
FB
1316 HWVoiceOut *hw = &cap->hw;
1317 SWVoiceOut *sw;
1318
bdff253c 1319 captured = live = audio_pcm_hw_get_live_out (hw, NULL);
dc88e38f 1320 rpos = hw->mix_buf->pos;
8ead62cf 1321 while (live) {
dc88e38f 1322 size_t left = hw->mix_buf->size - rpos;
7520462b 1323 size_t to_capture = MIN(live, left);
1ea879e5 1324 struct st_sample *src;
8ead62cf
FB
1325 struct capture_callback *cb;
1326
dc88e38f 1327 src = hw->mix_buf->samples + rpos;
8ead62cf
FB
1328 hw->clip (cap->buf, src, to_capture);
1329 mixeng_clear (src, to_capture);
1330
1331 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1332 cb->ops.capture (cb->opaque, cap->buf,
2b9cce8c 1333 to_capture * hw->info.bytes_per_frame);
8ead62cf 1334 }
dc88e38f 1335 rpos = (rpos + to_capture) % hw->mix_buf->size;
8ead62cf
FB
1336 live -= to_capture;
1337 }
dc88e38f 1338 hw->mix_buf->pos = rpos;
8ead62cf
FB
1339
1340 for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1341 if (!sw->active && sw->empty) {
1342 continue;
1343 }
1344
470bcabd 1345 if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
7520462b
KZ
1346 dolog("captured=%zu sw->total_hw_samples_mixed=%zu\n",
1347 captured, sw->total_hw_samples_mixed);
8e30d39b 1348 abort();
8ead62cf
FB
1349 }
1350
1351 sw->total_hw_samples_mixed -= captured;
1352 sw->empty = sw->total_hw_samples_mixed == 0;
1353 }
1354 }
1355}
1356
18e2c177 1357void audio_run(AudioState *s, const char *msg)
571ec3d6 1358{
18e2c177
KZ
1359 audio_run_out(s);
1360 audio_run_in(s);
1361 audio_run_capture(s);
571ec3d6 1362
713a98f8 1363#ifdef DEBUG_POLL
1364 {
1365 static double prevtime;
1366 double currtime;
1367 struct timeval tv;
571ec3d6 1368
713a98f8 1369 if (gettimeofday (&tv, NULL)) {
1370 perror ("audio_run: gettimeofday");
1371 return;
1372 }
1373
1374 currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1375 dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1376 prevtime = currtime;
1377 }
1378#endif
571ec3d6
FB
1379}
1380
a2893c83 1381void audio_generic_run_buffer_in(HWVoiceIn *hw)
ff095e52 1382{
ff095e52 1383 if (unlikely(!hw->buf_emul)) {
1d8549ad
VR
1384 hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1385 hw->buf_emul = g_malloc(hw->size_emul);
ff095e52
KZ
1386 hw->pos_emul = hw->pending_emul = 0;
1387 }
1388
1389 while (hw->pending_emul < hw->size_emul) {
1390 size_t read_len = MIN(hw->size_emul - hw->pos_emul,
1391 hw->size_emul - hw->pending_emul);
1392 size_t read = hw->pcm_ops->read(hw, hw->buf_emul + hw->pos_emul,
1393 read_len);
1394 hw->pending_emul += read;
7ffc90f3 1395 hw->pos_emul = (hw->pos_emul + read) % hw->size_emul;
ff095e52
KZ
1396 if (read < read_len) {
1397 break;
1398 }
1399 }
a2893c83
VR
1400}
1401
1402void *audio_generic_get_buffer_in(HWVoiceIn *hw, size_t *size)
1403{
18404ff1 1404 size_t start;
ff095e52 1405
18404ff1
VR
1406 start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1407 assert(start < hw->size_emul);
ff095e52 1408
599eac4e
VR
1409 *size = MIN(*size, hw->pending_emul);
1410 *size = MIN(*size, hw->size_emul - start);
ff095e52
KZ
1411 return hw->buf_emul + start;
1412}
1413
1414void audio_generic_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
1415{
1416 assert(size <= hw->pending_emul);
1417 hw->pending_emul -= size;
1418}
1419
9833438e
VR
1420size_t audio_generic_buffer_get_free(HWVoiceOut *hw)
1421{
1422 if (hw->buf_emul) {
1423 return hw->size_emul - hw->pending_emul;
1424 } else {
1425 return hw->samples * hw->info.bytes_per_frame;
1426 }
1427}
1428
fdc8c5f4
VR
1429void audio_generic_run_buffer_out(HWVoiceOut *hw)
1430{
1431 while (hw->pending_emul) {
18404ff1 1432 size_t write_len, written, start;
fdc8c5f4 1433
18404ff1
VR
1434 start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1435 assert(start < hw->size_emul);
fdc8c5f4
VR
1436
1437 write_len = MIN(hw->pending_emul, hw->size_emul - start);
1438
1439 written = hw->pcm_ops->write(hw, hw->buf_emul + start, write_len);
1440 hw->pending_emul -= written;
1441
1442 if (written < write_len) {
1443 break;
1444 }
1445 }
1446}
1447
ff095e52
KZ
1448void *audio_generic_get_buffer_out(HWVoiceOut *hw, size_t *size)
1449{
1450 if (unlikely(!hw->buf_emul)) {
1d8549ad
VR
1451 hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1452 hw->buf_emul = g_malloc(hw->size_emul);
ff095e52
KZ
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
9833438e
VR
1476 if (hw->pcm_ops->buffer_get_free) {
1477 size_t free = hw->pcm_ops->buffer_get_free(hw);
1478
1479 size = MIN(size, free);
1480 }
1481
2d882307
VR
1482 while (total < size) {
1483 size_t dst_size = size - total;
1484 size_t copy_size, proc;
1485 void *dst = hw->pcm_ops->get_buffer_out(hw, &dst_size);
ff095e52 1486
2d882307
VR
1487 if (dst_size == 0) {
1488 break;
1489 }
1490
1491 copy_size = MIN(size - total, dst_size);
1492 if (dst) {
1493 memcpy(dst, (char *)buf + total, copy_size);
1494 }
1495 proc = hw->pcm_ops->put_buffer_out(hw, dst, copy_size);
1496 total += proc;
1497
1498 if (proc == 0 || proc < copy_size) {
1499 break;
1500 }
1501 }
1502
1503 if (hw->pcm_ops->run_buffer_out) {
1504 hw->pcm_ops->run_buffer_out(hw);
1505 }
1506
1507 return total;
ff095e52
KZ
1508}
1509
1510size_t audio_generic_read(HWVoiceIn *hw, void *buf, size_t size)
1511{
b9896dc5 1512 size_t total = 0;
ff095e52 1513
a2893c83
VR
1514 if (hw->pcm_ops->run_buffer_in) {
1515 hw->pcm_ops->run_buffer_in(hw);
1516 }
1517
b9896dc5
VR
1518 while (total < size) {
1519 size_t src_size = size - total;
1520 void *src = hw->pcm_ops->get_buffer_in(hw, &src_size);
ff095e52 1521
b9896dc5 1522 if (src_size == 0) {
b9896dc5
VR
1523 break;
1524 }
1525
1526 memcpy((char *)buf + total, src, src_size);
1527 hw->pcm_ops->put_buffer_in(hw, src, src_size);
1528 total += src_size;
1529 }
1530
1531 return total;
8d1439b6 1532}
ff095e52 1533
71830221
KZ
1534static int audio_driver_init(AudioState *s, struct audio_driver *drv,
1535 bool msg, Audiodev *dev)
85571bc7 1536{
71830221 1537 s->drv_opaque = drv->init(dev);
1d14ffa9 1538
c0fe3827 1539 if (s->drv_opaque) {
ff095e52
KZ
1540 if (!drv->pcm_ops->get_buffer_in) {
1541 drv->pcm_ops->get_buffer_in = audio_generic_get_buffer_in;
1542 drv->pcm_ops->put_buffer_in = audio_generic_put_buffer_in;
1543 }
1544 if (!drv->pcm_ops->get_buffer_out) {
1545 drv->pcm_ops->get_buffer_out = audio_generic_get_buffer_out;
1546 drv->pcm_ops->put_buffer_out = audio_generic_put_buffer_out;
1547 }
1548
526fb058
KZ
1549 audio_init_nb_voices_out(s, drv);
1550 audio_init_nb_voices_in(s, drv);
c0fe3827 1551 s->drv = drv;
1d14ffa9 1552 return 0;
6c6886bd 1553 } else {
fb37ce92
GH
1554 if (msg) {
1555 dolog("Could not init `%s' audio driver\n", drv->name);
1556 }
1d14ffa9 1557 return -1;
85571bc7
FB
1558 }
1559}
1560
538f0497 1561static void audio_vm_change_state_handler (void *opaque, bool running,
1dfb4dd9 1562 RunState state)
85571bc7 1563{
c0fe3827 1564 AudioState *s = opaque;
1d14ffa9
FB
1565 HWVoiceOut *hwo = NULL;
1566 HWVoiceIn *hwi = NULL;
1d14ffa9 1567
978dd635 1568 s->vm_running = running;
526fb058 1569 while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
571a8c52
KZ
1570 if (hwo->pcm_ops->enable_out) {
1571 hwo->pcm_ops->enable_out(hwo, running);
1572 }
1d14ffa9 1573 }
85571bc7 1574
526fb058 1575 while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
571a8c52
KZ
1576 if (hwi->pcm_ops->enable_in) {
1577 hwi->pcm_ops->enable_in(hwi, running);
1578 }
85571bc7 1579 }
39deb1e4 1580 audio_reset_timer (s);
85571bc7
FB
1581}
1582
ecd97e95 1583static void free_audio_state(AudioState *s)
85571bc7 1584{
a384c205
MAL
1585 HWVoiceOut *hwo, *hwon;
1586 HWVoiceIn *hwi, *hwin;
1d14ffa9 1587
526fb058 1588 QLIST_FOREACH_SAFE(hwo, &s->hw_head_out, entries, hwon) {
ec36b695 1589 SWVoiceCap *sc;
8ead62cf 1590
571a8c52
KZ
1591 if (hwo->enabled && hwo->pcm_ops->enable_out) {
1592 hwo->pcm_ops->enable_out(hwo, false);
aeb29b64 1593 }
1d14ffa9 1594 hwo->pcm_ops->fini_out (hwo);
8ead62cf 1595
ec36b695
FB
1596 for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1597 CaptureVoiceOut *cap = sc->cap;
1598 struct capture_callback *cb;
1599
1600 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1601 cb->ops.destroy (cb->opaque);
1602 }
8ead62cf 1603 }
a384c205 1604 QLIST_REMOVE(hwo, entries);
1d14ffa9 1605 }
85571bc7 1606
526fb058 1607 QLIST_FOREACH_SAFE(hwi, &s->hw_head_in, entries, hwin) {
571a8c52
KZ
1608 if (hwi->enabled && hwi->pcm_ops->enable_in) {
1609 hwi->pcm_ops->enable_in(hwi, false);
aeb29b64 1610 }
1d14ffa9 1611 hwi->pcm_ops->fini_in (hwi);
a384c205 1612 QLIST_REMOVE(hwi, entries);
85571bc7 1613 }
c0fe3827
FB
1614
1615 if (s->drv) {
1616 s->drv->fini (s->drv_opaque);
a384c205 1617 s->drv = NULL;
c0fe3827 1618 }
71830221
KZ
1619
1620 if (s->dev) {
1621 qapi_free_Audiodev(s->dev);
1622 s->dev = NULL;
1623 }
e76ba19a
KZ
1624
1625 if (s->ts) {
1626 timer_free(s->ts);
1627 s->ts = NULL;
1628 }
1629
ecd97e95
KZ
1630 g_free(s);
1631}
1632
1633void audio_cleanup(void)
1634{
ecd97e95
KZ
1635 while (!QTAILQ_EMPTY(&audio_states)) {
1636 AudioState *s = QTAILQ_FIRST(&audio_states);
1637 QTAILQ_REMOVE(&audio_states, s, list);
1638 free_audio_state(s);
1639 }
85571bc7
FB
1640}
1641
da77adba
DDAG
1642static bool vmstate_audio_needed(void *opaque)
1643{
1644 /*
1645 * Never needed, this vmstate only exists in case
1646 * an old qemu sends it to us.
1647 */
1648 return false;
1649}
1650
d959fce9
JQ
1651static const VMStateDescription vmstate_audio = {
1652 .name = "audio",
1653 .version_id = 1,
1654 .minimum_version_id = 1,
da77adba 1655 .needed = vmstate_audio_needed,
35d08458 1656 .fields = (VMStateField[]) {
d959fce9 1657 VMSTATE_END_OF_LIST()
1d14ffa9 1658 }
d959fce9 1659};
85571bc7 1660
71830221
KZ
1661static void audio_validate_opts(Audiodev *dev, Error **errp);
1662
1663static AudiodevListEntry *audiodev_find(
1664 AudiodevListHead *head, const char *drvname)
1665{
1666 AudiodevListEntry *e;
1667 QSIMPLEQ_FOREACH(e, head, next) {
1668 if (strcmp(AudiodevDriver_str(e->dev->driver), drvname) == 0) {
1669 return e;
1670 }
1671 }
1672
1673 return NULL;
1674}
1675
ecd97e95
KZ
1676/*
1677 * if we have dev, this function was called because of an -audiodev argument =>
1678 * initialize a new state with it
1679 * if dev == NULL => legacy implicit initialization, return the already created
1680 * state or create a new one
1681 */
af2041ed 1682static AudioState *audio_init(Audiodev *dev, const char *name)
85571bc7 1683{
ecd97e95 1684 static bool atexit_registered;
1d14ffa9 1685 size_t i;
85571bc7 1686 int done = 0;
71830221 1687 const char *drvname = NULL;
713a98f8 1688 VMChangeStateEntry *e;
ecd97e95 1689 AudioState *s;
d3893a39 1690 struct audio_driver *driver;
71830221
KZ
1691 /* silence gcc warning about uninitialized variable */
1692 AudiodevListHead head = QSIMPLEQ_HEAD_INITIALIZER(head);
1d14ffa9 1693
f0c4555e
GH
1694 if (using_spice) {
1695 /*
1696 * When using spice allow the spice audio driver being picked
1697 * as default.
1698 *
1699 * Temporary hack. Using audio devices without explicit
1700 * audiodev= property is already deprecated. Same goes for
1701 * the -soundhw switch. Once this support gets finally
1702 * removed we can also drop the concept of a default audio
1703 * backend and this can go away.
1704 */
1705 driver = audio_driver_lookup("spice");
06c8c375
GH
1706 if (driver) {
1707 driver->can_be_default = 1;
1708 }
f0c4555e
GH
1709 }
1710
71830221
KZ
1711 if (dev) {
1712 /* -audiodev option */
af2041ed 1713 legacy_config = false;
71830221 1714 drvname = AudiodevDriver_str(dev->driver);
ecd97e95 1715 } else if (!QTAILQ_EMPTY(&audio_states)) {
af2041ed 1716 if (!legacy_config) {
4b3b7793
KZ
1717 dolog("Device %s: audiodev default parameter is deprecated, please "
1718 "specify audiodev=%s\n", name,
1719 QTAILQ_FIRST(&audio_states)->dev->id);
af2041ed 1720 }
ecd97e95 1721 return QTAILQ_FIRST(&audio_states);
71830221
KZ
1722 } else {
1723 /* legacy implicit initialization */
1724 head = audio_handle_legacy_opts();
1725 /*
1726 * In case of legacy initialization, all Audiodevs in the list will have
e3a6e0da 1727 * the same configuration (except the driver), so it doesn't matter which
71830221
KZ
1728 * one we chose. We need an Audiodev to set up AudioState before we can
1729 * init a driver. Also note that dev at this point is still in the
1730 * list.
1731 */
1732 dev = QSIMPLEQ_FIRST(&head)->dev;
1733 audio_validate_opts(dev, &error_abort);
1734 }
ecd97e95 1735
b21e2380 1736 s = g_new0(AudioState, 1);
71830221
KZ
1737 s->dev = dev;
1738
72cf2d4f
BS
1739 QLIST_INIT (&s->hw_head_out);
1740 QLIST_INIT (&s->hw_head_in);
1741 QLIST_INIT (&s->cap_head);
ecd97e95
KZ
1742 if (!atexit_registered) {
1743 atexit(audio_cleanup);
1744 atexit_registered = true;
1745 }
1746 QTAILQ_INSERT_TAIL(&audio_states, s, list);
571ec3d6 1747
bc72ad67 1748 s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
571ec3d6 1749
71830221
KZ
1750 s->nb_hw_voices_out = audio_get_pdo_out(dev)->voices;
1751 s->nb_hw_voices_in = audio_get_pdo_in(dev)->voices;
c0fe3827 1752
1d14ffa9 1753 if (s->nb_hw_voices_out <= 0) {
571ec3d6 1754 dolog ("Bogus number of playback voices %d, setting to 1\n",
1d14ffa9
FB
1755 s->nb_hw_voices_out);
1756 s->nb_hw_voices_out = 1;
1757 }
1758
1759 if (s->nb_hw_voices_in <= 0) {
571ec3d6 1760 dolog ("Bogus number of capture voices %d, setting to 0\n",
1d14ffa9 1761 s->nb_hw_voices_in);
571ec3d6 1762 s->nb_hw_voices_in = 0;
1d14ffa9 1763 }
85571bc7 1764
85571bc7 1765 if (drvname) {
d3893a39
GH
1766 driver = audio_driver_lookup(drvname);
1767 if (driver) {
71830221 1768 done = !audio_driver_init(s, driver, true, dev);
d3893a39 1769 } else {
85571bc7
FB
1770 dolog ("Unknown audio driver `%s'\n", drvname);
1771 }
71830221
KZ
1772 } else {
1773 for (i = 0; audio_prio_list[i]; i++) {
1774 AudiodevListEntry *e = audiodev_find(&head, audio_prio_list[i]);
d3893a39 1775 driver = audio_driver_lookup(audio_prio_list[i]);
71830221
KZ
1776
1777 if (e && driver) {
1778 s->dev = dev = e->dev;
1779 audio_validate_opts(dev, &error_abort);
1780 done = !audio_driver_init(s, driver, false, dev);
1781 if (done) {
1782 e->dev = NULL;
1783 break;
1784 }
1d14ffa9 1785 }
85571bc7
FB
1786 }
1787 }
71830221 1788 audio_free_audiodev_list(&head);
85571bc7 1789
85571bc7 1790 if (!done) {
d3893a39 1791 driver = audio_driver_lookup("none");
71830221 1792 done = !audio_driver_init(s, driver, false, dev);
7e274652
MA
1793 assert(done);
1794 dolog("warning: Using timer based audio emulation\n");
85571bc7 1795 }
1d14ffa9 1796
71830221
KZ
1797 if (dev->timer_period <= 0) {
1798 s->period_ticks = 1;
0d9acba8 1799 } else {
40ad46d3 1800 s->period_ticks = dev->timer_period * (int64_t)SCALE_US;
1d14ffa9 1801 }
0d9acba8
PB
1802
1803 e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1804 if (!e) {
1805 dolog ("warning: Could not register change state handler\n"
1806 "(Audio can continue looping even after stopping the VM)\n");
1d14ffa9
FB
1807 }
1808
72cf2d4f 1809 QLIST_INIT (&s->card_head);
0be71e32 1810 vmstate_register (NULL, 0, &vmstate_audio, s);
ecd97e95 1811 return s;
71830221
KZ
1812}
1813
1814void audio_free_audiodev_list(AudiodevListHead *head)
1815{
1816 AudiodevListEntry *e;
1817 while ((e = QSIMPLEQ_FIRST(head))) {
1818 QSIMPLEQ_REMOVE_HEAD(head, next);
1819 qapi_free_Audiodev(e->dev);
1820 g_free(e);
1821 }
85571bc7 1822}
8ead62cf 1823
1a7dafce 1824void AUD_register_card (const char *name, QEMUSoundCard *card)
1825{
ecd97e95 1826 if (!card->state) {
af2041ed 1827 card->state = audio_init(NULL, name);
ecd97e95
KZ
1828 }
1829
7267c094 1830 card->name = g_strdup (name);
1a7dafce 1831 memset (&card->entries, 0, sizeof (card->entries));
ecd97e95 1832 QLIST_INSERT_HEAD(&card->state->card_head, card, entries);
1a7dafce 1833}
1834
1835void AUD_remove_card (QEMUSoundCard *card)
1836{
72cf2d4f 1837 QLIST_REMOVE (card, entries);
7267c094 1838 g_free (card->name);
1a7dafce 1839}
1840
33940dd3 1841static struct audio_pcm_ops capture_pcm_ops;
1a7dafce 1842
ecd97e95
KZ
1843CaptureVoiceOut *AUD_add_capture(
1844 AudioState *s,
1ea879e5 1845 struct audsettings *as,
8ead62cf
FB
1846 struct audio_capture_ops *ops,
1847 void *cb_opaque
1848 )
1849{
1850 CaptureVoiceOut *cap;
1851 struct capture_callback *cb;
1852
ecd97e95 1853 if (!s) {
af2041ed 1854 if (!legacy_config) {
4b3b7793 1855 dolog("Capturing without setting an audiodev is deprecated\n");
af2041ed
KZ
1856 }
1857 s = audio_init(NULL, NULL);
ecd97e95
KZ
1858 }
1859
1930616b
KZ
1860 if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1861 dolog("Can't capture with mixeng disabled\n");
1862 return NULL;
1863 }
1864
ec36b695 1865 if (audio_validate_settings (as)) {
8ead62cf
FB
1866 dolog ("Invalid settings were passed when trying to add capture\n");
1867 audio_print_settings (as);
e8d85444 1868 return NULL;
8ead62cf
FB
1869 }
1870
e8d85444 1871 cb = g_malloc0(sizeof(*cb));
8ead62cf
FB
1872 cb->ops = *ops;
1873 cb->opaque = cb_opaque;
1874
526fb058 1875 cap = audio_pcm_capture_find_specific(s, as);
8ead62cf 1876 if (cap) {
72cf2d4f 1877 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
ec36b695 1878 return cap;
6c6886bd 1879 } else {
8ead62cf
FB
1880 HWVoiceOut *hw;
1881 CaptureVoiceOut *cap;
1882
e8d85444 1883 cap = g_malloc0(sizeof(*cap));
8ead62cf
FB
1884
1885 hw = &cap->hw;
526fb058 1886 hw->s = s;
33940dd3 1887 hw->pcm_ops = &capture_pcm_ops;
72cf2d4f
BS
1888 QLIST_INIT (&hw->sw_head);
1889 QLIST_INIT (&cap->cb_head);
8ead62cf
FB
1890
1891 /* XXX find a more elegant way */
1892 hw->samples = 4096 * 4;
dc88e38f 1893 audio_pcm_hw_alloc_resources_out(hw);
8ead62cf 1894
d929eba5 1895 audio_pcm_init_info (&hw->info, as);
8ead62cf 1896
2b9cce8c 1897 cap->buf = g_malloc0_n(hw->mix_buf->size, hw->info.bytes_per_frame);
8ead62cf 1898
ed2a4a79
KZ
1899 if (hw->info.is_float) {
1900 hw->clip = mixeng_clip_float[hw->info.nchannels == 2];
1901 } else {
1902 hw->clip = mixeng_clip
1903 [hw->info.nchannels == 2]
1904 [hw->info.is_signed]
1905 [hw->info.swap_endianness]
1906 [audio_bits_to_index(hw->info.bits)];
1907 }
8ead62cf 1908
72cf2d4f
BS
1909 QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1910 QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
8ead62cf 1911
526fb058 1912 QLIST_FOREACH(hw, &s->hw_head_out, entries) {
1a7dafce 1913 audio_attach_capture (hw);
8ead62cf 1914 }
ec36b695 1915 return cap;
ec36b695
FB
1916 }
1917}
1918
1919void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1920{
1921 struct capture_callback *cb;
1922
1923 for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1924 if (cb->opaque == cb_opaque) {
1925 cb->ops.destroy (cb_opaque);
72cf2d4f 1926 QLIST_REMOVE (cb, entries);
7267c094 1927 g_free (cb);
ec36b695
FB
1928
1929 if (!cap->cb_head.lh_first) {
1930 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
a3c25997 1931
ec36b695 1932 while (sw) {
a3c25997 1933 SWVoiceCap *sc = (SWVoiceCap *) sw;
ec36b695
FB
1934#ifdef DEBUG_CAPTURE
1935 dolog ("freeing %s\n", sw->name);
1936#endif
a3c25997 1937
ec36b695
FB
1938 sw1 = sw->entries.le_next;
1939 if (sw->rate) {
1940 st_rate_stop (sw->rate);
1941 sw->rate = NULL;
1942 }
72cf2d4f
BS
1943 QLIST_REMOVE (sw, entries);
1944 QLIST_REMOVE (sc, entries);
7267c094 1945 g_free (sc);
ec36b695
FB
1946 sw = sw1;
1947 }
72cf2d4f 1948 QLIST_REMOVE (cap, entries);
3268a845
GH
1949 g_free (cap->hw.mix_buf);
1950 g_free (cap->buf);
7267c094 1951 g_free (cap);
ec36b695
FB
1952 }
1953 return;
1954 }
8ead62cf
FB
1955 }
1956}
683efdcb
AZ
1957
1958void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
cecc1e79
KZ
1959{
1960 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1961 audio_set_volume_out(sw, &vol);
1962}
1963
1964void audio_set_volume_out(SWVoiceOut *sw, Volume *vol)
683efdcb
AZ
1965{
1966 if (sw) {
6c95ab94
MAL
1967 HWVoiceOut *hw = sw->hw;
1968
cecc1e79
KZ
1969 sw->vol.mute = vol->mute;
1970 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
1971 sw->vol.r = nominal_volume.l * vol->vol[vol->channels > 1 ? 1 : 0] /
1972 255;
6c95ab94 1973
571a8c52 1974 if (hw->pcm_ops->volume_out) {
cecc1e79 1975 hw->pcm_ops->volume_out(hw, vol);
6c95ab94 1976 }
683efdcb
AZ
1977 }
1978}
1979
1980void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
cecc1e79
KZ
1981{
1982 Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1983 audio_set_volume_in(sw, &vol);
1984}
1985
1986void audio_set_volume_in(SWVoiceIn *sw, Volume *vol)
683efdcb
AZ
1987{
1988 if (sw) {
6c95ab94
MAL
1989 HWVoiceIn *hw = sw->hw;
1990
cecc1e79
KZ
1991 sw->vol.mute = vol->mute;
1992 sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
1993 sw->vol.r = nominal_volume.r * vol->vol[vol->channels > 1 ? 1 : 0] /
1994 255;
6c95ab94 1995
571a8c52 1996 if (hw->pcm_ops->volume_in) {
cecc1e79 1997 hw->pcm_ops->volume_in(hw, vol);
6c95ab94 1998 }
683efdcb
AZ
1999 }
2000}
71830221
KZ
2001
2002void audio_create_pdos(Audiodev *dev)
2003{
2004 switch (dev->driver) {
2005#define CASE(DRIVER, driver, pdo_name) \
2006 case AUDIODEV_DRIVER_##DRIVER: \
2007 if (!dev->u.driver.has_in) { \
2008 dev->u.driver.in = g_malloc0( \
2009 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
2010 dev->u.driver.has_in = true; \
2011 } \
2012 if (!dev->u.driver.has_out) { \
2013 dev->u.driver.out = g_malloc0( \
725662d6 2014 sizeof(Audiodev##pdo_name##PerDirectionOptions)); \
71830221
KZ
2015 dev->u.driver.has_out = true; \
2016 } \
2017 break
2018
2019 CASE(NONE, none, );
2020 CASE(ALSA, alsa, Alsa);
2021 CASE(COREAUDIO, coreaudio, Coreaudio);
739362d4 2022 CASE(DBUS, dbus, );
71830221 2023 CASE(DSOUND, dsound, );
2e445703 2024 CASE(JACK, jack, Jack);
71830221
KZ
2025 CASE(OSS, oss, Oss);
2026 CASE(PA, pa, Pa);
5a0926c2 2027 CASE(SDL, sdl, Sdl);
71830221
KZ
2028 CASE(SPICE, spice, );
2029 CASE(WAV, wav, );
2030
2031 case AUDIODEV_DRIVER__MAX:
2032 abort();
2033 };
2034}
2035
2036static void audio_validate_per_direction_opts(
2037 AudiodevPerDirectionOptions *pdo, Error **errp)
2038{
1930616b
KZ
2039 if (!pdo->has_mixing_engine) {
2040 pdo->has_mixing_engine = true;
2041 pdo->mixing_engine = true;
2042 }
71830221
KZ
2043 if (!pdo->has_fixed_settings) {
2044 pdo->has_fixed_settings = true;
1930616b 2045 pdo->fixed_settings = pdo->mixing_engine;
71830221
KZ
2046 }
2047 if (!pdo->fixed_settings &&
2048 (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
2049 error_setg(errp,
2050 "You can't use frequency, channels or format with fixed-settings=off");
2051 return;
2052 }
1930616b
KZ
2053 if (!pdo->mixing_engine && pdo->fixed_settings) {
2054 error_setg(errp, "You can't use fixed-settings without mixeng");
2055 return;
2056 }
71830221
KZ
2057
2058 if (!pdo->has_frequency) {
2059 pdo->has_frequency = true;
2060 pdo->frequency = 44100;
2061 }
2062 if (!pdo->has_channels) {
2063 pdo->has_channels = true;
2064 pdo->channels = 2;
2065 }
2066 if (!pdo->has_voices) {
2067 pdo->has_voices = true;
1930616b 2068 pdo->voices = pdo->mixing_engine ? 1 : INT_MAX;
71830221
KZ
2069 }
2070 if (!pdo->has_format) {
2071 pdo->has_format = true;
2072 pdo->format = AUDIO_FORMAT_S16;
2073 }
2074}
2075
2076static void audio_validate_opts(Audiodev *dev, Error **errp)
2077{
2078 Error *err = NULL;
2079
2080 audio_create_pdos(dev);
2081
2082 audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
2083 if (err) {
2084 error_propagate(errp, err);
2085 return;
2086 }
2087
2088 audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
2089 if (err) {
2090 error_propagate(errp, err);
2091 return;
2092 }
2093
2094 if (!dev->has_timer_period) {
2095 dev->has_timer_period = true;
2096 dev->timer_period = 10000; /* 100Hz -> 10ms */
2097 }
2098}
2099
2100void audio_parse_option(const char *opt)
2101{
2102 AudiodevListEntry *e;
2103 Audiodev *dev = NULL;
2104
2105 Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
2106 visit_type_Audiodev(v, NULL, &dev, &error_fatal);
2107 visit_free(v);
2108
2109 audio_validate_opts(dev, &error_fatal);
2110
b21e2380 2111 e = g_new0(AudiodevListEntry, 1);
71830221
KZ
2112 e->dev = dev;
2113 QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
2114}
2115
2116void audio_init_audiodevs(void)
2117{
2118 AudiodevListEntry *e;
2119
2120 QSIMPLEQ_FOREACH(e, &audiodevs, next) {
af2041ed 2121 audio_init(e->dev, NULL);
71830221
KZ
2122 }
2123}
2124
2125audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
2126{
2127 return (audsettings) {
2128 .freq = pdo->frequency,
2129 .nchannels = pdo->channels,
2130 .fmt = pdo->format,
2131 .endianness = AUDIO_HOST_ENDIANNESS,
2132 };
2133}
2134
2135int audioformat_bytes_per_sample(AudioFormat fmt)
2136{
2137 switch (fmt) {
2138 case AUDIO_FORMAT_U8:
2139 case AUDIO_FORMAT_S8:
2140 return 1;
2141
2142 case AUDIO_FORMAT_U16:
2143 case AUDIO_FORMAT_S16:
2144 return 2;
2145
2146 case AUDIO_FORMAT_U32:
2147 case AUDIO_FORMAT_S32:
ed2a4a79 2148 case AUDIO_FORMAT_F32:
71830221
KZ
2149 return 4;
2150
2151 case AUDIO_FORMAT__MAX:
2152 ;
2153 }
2154 abort();
2155}
2156
2157
2158/* frames = freq * usec / 1e6 */
2159int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
2160 audsettings *as, int def_usecs)
2161{
2162 uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
2163 return (as->freq * usecs + 500000) / 1000000;
2164}
2165
2166/* samples = channels * frames = channels * freq * usec / 1e6 */
2167int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
2168 audsettings *as, int def_usecs)
2169{
2170 return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
2171}
2172
2173/*
2174 * bytes = bytes_per_sample * samples =
2175 * bytes_per_sample * channels * freq * usec / 1e6
2176 */
2177int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
2178 audsettings *as, int def_usecs)
2179{
2180 return audio_buffer_samples(pdo, as, def_usecs) *
2181 audioformat_bytes_per_sample(as->fmt);
2182}
ecd97e95
KZ
2183
2184AudioState *audio_state_by_name(const char *name)
2185{
2186 AudioState *s;
2187 QTAILQ_FOREACH(s, &audio_states, list) {
2188 assert(s->dev);
2189 if (strcmp(name, s->dev->id) == 0) {
2190 return s;
2191 }
2192 }
2193 return NULL;
2194}
2195
2196const char *audio_get_id(QEMUSoundCard *card)
2197{
2198 if (card->state) {
2199 assert(card->state->dev);
2200 return card->state->dev->id;
2201 } else {
2202 return "";
2203 }
2204}
857271a2 2205
37a54d05
VR
2206const char *audio_application_name(void)
2207{
2208 const char *vm_name;
2209
2210 vm_name = qemu_get_vm_name();
2211 return vm_name ? vm_name : "qemu";
2212}
2213
857271a2
KZ
2214void audio_rate_start(RateCtl *rate)
2215{
2216 memset(rate, 0, sizeof(RateCtl));
2217 rate->start_ticks = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2218}
2219
2220size_t audio_rate_get_bytes(struct audio_pcm_info *info, RateCtl *rate,
2221 size_t bytes_avail)
2222{
2223 int64_t now;
2224 int64_t ticks;
2225 int64_t bytes;
2226 int64_t samples;
2227 size_t ret;
2228
2229 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2230 ticks = now - rate->start_ticks;
2231 bytes = muldiv64(ticks, info->bytes_per_second, NANOSECONDS_PER_SECOND);
2b9cce8c 2232 samples = (bytes - rate->bytes_sent) / info->bytes_per_frame;
857271a2
KZ
2233 if (samples < 0 || samples > 65536) {
2234 AUD_log(NULL, "Resetting rate control (%" PRId64 " samples)\n", samples);
2235 audio_rate_start(rate);
2236 samples = 0;
2237 }
2238
2b9cce8c 2239 ret = MIN(samples * info->bytes_per_frame, bytes_avail);
857271a2
KZ
2240 rate->bytes_sent += ret;
2241 return ret;
2242}