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