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