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