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