audio.c 46.2 KB
Newer Older
B
bellard 已提交
1 2
/*
 * QEMU Audio subsystem
3 4 5
 *
 * Copyright (c) 2003-2005 Vassili Karpov (malc)
 *
B
bellard 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include "vl.h"

26 27
#define AUDIO_CAP "audio"
#include "audio_int.h"
B
bellard 已提交
28

29 30 31
/* #define DEBUG_PLIVE */
/* #define DEBUG_LIVE */
/* #define DEBUG_OUT */
32
/* #define DEBUG_CAPTURE */
B
bellard 已提交
33

B
bellard 已提交
34 35
#define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
static struct audio_driver *drvtab[] = {
#ifdef CONFIG_OSS
    &oss_audio_driver,
#endif
#ifdef CONFIG_ALSA
    &alsa_audio_driver,
#endif
#ifdef CONFIG_COREAUDIO
    &coreaudio_audio_driver,
#endif
#ifdef CONFIG_DSOUND
    &dsound_audio_driver,
#endif
#ifdef CONFIG_FMOD
    &fmod_audio_driver,
#endif
#ifdef CONFIG_SDL
    &sdl_audio_driver,
#endif
    &no_audio_driver,
    &wav_audio_driver
};
B
bellard 已提交
58

B
bellard 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
struct fixed_settings {
    int enabled;
    int nb_voices;
    int greedy;
    audsettings_t settings;
};

static struct {
    struct fixed_settings fixed_out;
    struct fixed_settings fixed_in;
    union {
        int hz;
        int64_t ticks;
    } period;
    int plive;
B
bellard 已提交
74
    int log_to_monitor;
B
bellard 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
} conf = {
    {                           /* DAC fixed settings */
        1,                      /* enabled */
        1,                      /* nb_voices */
        1,                      /* greedy */
        {
            44100,              /* freq */
            2,                  /* nchannels */
            AUD_FMT_S16         /* fmt */
        }
    },

    {                           /* ADC fixed settings */
        1,                      /* enabled */
        1,                      /* nb_voices */
        1,                      /* greedy */
        {
            44100,              /* freq */
            2,                  /* nchannels */
            AUD_FMT_S16         /* fmt */
        }
    },

98
    { 0 },                      /* period */
B
bellard 已提交
99
    0,                          /* plive */
B
bellard 已提交
100
    0                           /* log_to_monitor */
101 102
};

B
bellard 已提交
103 104
static AudioState glob_audio_state;

105 106 107 108 109 110 111 112 113
volume_t nominal_volume = {
    0,
#ifdef FLOAT_MIXENG
    1.0,
    1.0
#else
    UINT_MAX,
    UINT_MAX
#endif
B
bellard 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
};

/* http://www.df.lth.se/~john_e/gems/gem002d.html */
/* http://www.multi-platforms.com/Tips/PopCount.htm */
uint32_t popcount (uint32_t u)
{
    u = ((u&0x55555555) + ((u>>1)&0x55555555));
    u = ((u&0x33333333) + ((u>>2)&0x33333333));
    u = ((u&0x0f0f0f0f) + ((u>>4)&0x0f0f0f0f));
    u = ((u&0x00ff00ff) + ((u>>8)&0x00ff00ff));
    u = ( u&0x0000ffff) + (u>>16);
    return u;
}

inline uint32_t lsbindex (uint32_t u)
{
    return popcount ((u&-u)-1);
}

133 134 135 136
#ifdef AUDIO_IS_FLAWLESS_AND_NO_CHECKS_ARE_REQURIED
#error No its not
#else
int audio_bug (const char *funcname, int cond)
B
bellard 已提交
137
{
138 139 140
    if (cond) {
        static int shown;

141
        AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
        if (!shown) {
            shown = 1;
            AUD_log (NULL, "Save all your work and restart without audio\n");
            AUD_log (NULL, "Please send bug report to malc@pulsesoft.com\n");
            AUD_log (NULL, "I am sorry\n");
        }
        AUD_log (NULL, "Context:\n");

#if defined AUDIO_BREAKPOINT_ON_BUG
#  if defined HOST_I386
#    if defined __GNUC__
        __asm__ ("int3");
#    elif defined _MSC_VER
        _asm _emit 0xcc;
#    else
        abort ();
#    endif
#  else
        abort ();
#  endif
#endif
B
bellard 已提交
163 164
    }

165
    return cond;
B
bellard 已提交
166
}
167
#endif
B
bellard 已提交
168

B
bellard 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181
void *audio_calloc (const char *funcname, int nmemb, size_t size)
{
    int cond;
    size_t len;

    len = nmemb * size;
    cond = !nmemb || !size;
    cond |= nmemb < 0;
    cond |= len < size;

    if (audio_bug ("audio_calloc", cond)) {
        AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
                 funcname);
B
bellard 已提交
182
        AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
B
bellard 已提交
183 184 185 186 187 188
        return NULL;
    }

    return qemu_mallocz (len);
}

189
static char *audio_alloc_prefix (const char *s)
B
bellard 已提交
190
{
191 192 193
    const char qemu_prefix[] = "QEMU_";
    size_t len;
    char *r;
B
bellard 已提交
194

195 196 197
    if (!s) {
        return NULL;
    }
B
bellard 已提交
198

199 200
    len = strlen (s);
    r = qemu_malloc (len + sizeof (qemu_prefix));
B
bellard 已提交
201

202 203 204
    if (r) {
        size_t i;
        char *u = r + sizeof (qemu_prefix) - 1;
B
bellard 已提交
205

206 207 208 209 210 211
        strcpy (r, qemu_prefix);
        strcat (r, s);

        for (i = 0; i < len; ++i) {
            u[i] = toupper (u[i]);
        }
B
bellard 已提交
212
    }
213
    return r;
B
bellard 已提交
214 215
}

216
const char *audio_audfmt_to_string (audfmt_e fmt)
B
bellard 已提交
217
{
218 219 220
    switch (fmt) {
    case AUD_FMT_U8:
        return "U8";
B
bellard 已提交
221

222 223
    case AUD_FMT_U16:
        return "U16";
B
bellard 已提交
224 225

    case AUD_FMT_S8:
226
        return "S8";
B
bellard 已提交
227 228

    case AUD_FMT_S16:
229
        return "S16";
B
bellard 已提交
230 231
    }

232 233
    dolog ("Bogus audfmt %d returning S16\n", fmt);
    return "S16";
B
bellard 已提交
234 235
}

236
audfmt_e audio_string_to_audfmt (const char *s, audfmt_e defval, int *defaultp)
B
bellard 已提交
237
{
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    if (!strcasecmp (s, "u8")) {
        *defaultp = 0;
        return AUD_FMT_U8;
    }
    else if (!strcasecmp (s, "u16")) {
        *defaultp = 0;
        return AUD_FMT_U16;
    }
    else if (!strcasecmp (s, "s8")) {
        *defaultp = 0;
        return AUD_FMT_S8;
    }
    else if (!strcasecmp (s, "s16")) {
        *defaultp = 0;
        return AUD_FMT_S16;
    }
    else {
        dolog ("Bogus audio format `%s' using %s\n",
               s, audio_audfmt_to_string (defval));
        *defaultp = 1;
        return defval;
    }
B
bellard 已提交
260 261
}

262 263 264
static audfmt_e audio_get_conf_fmt (const char *envname,
                                    audfmt_e defval,
                                    int *defaultp)
B
bellard 已提交
265
{
266 267 268 269
    const char *var = getenv (envname);
    if (!var) {
        *defaultp = 1;
        return defval;
B
bellard 已提交
270
    }
271
    return audio_string_to_audfmt (var, defval, defaultp);
B
bellard 已提交
272 273
}

274
static int audio_get_conf_int (const char *key, int defval, int *defaultp)
B
bellard 已提交
275
{
276 277
    int val;
    char *strval;
B
bellard 已提交
278

279 280 281 282 283 284 285 286 287 288
    strval = getenv (key);
    if (strval) {
        *defaultp = 0;
        val = atoi (strval);
        return val;
    }
    else {
        *defaultp = 1;
        return defval;
    }
B
bellard 已提交
289 290
}

291 292 293
static const char *audio_get_conf_str (const char *key,
                                       const char *defval,
                                       int *defaultp)
B
bellard 已提交
294
{
295 296 297 298 299 300 301 302
    const char *val = getenv (key);
    if (!val) {
        *defaultp = 1;
        return defval;
    }
    else {
        *defaultp = 0;
        return val;
B
bellard 已提交
303 304 305
    }
}

B
bellard 已提交
306
void AUD_vlog (const char *cap, const char *fmt, va_list ap)
B
bellard 已提交
307
{
B
bellard 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320
    if (conf.log_to_monitor) {
        if (cap) {
            term_printf ("%s: ", cap);
        }

        term_vprintf (fmt, ap);
    }
    else {
        if (cap) {
            fprintf (stderr, "%s: ", cap);
        }

        vfprintf (stderr, fmt, ap);
B
bellard 已提交
321 322 323
    }
}

B
bellard 已提交
324
void AUD_log (const char *cap, const char *fmt, ...)
B
bellard 已提交
325
{
B
bellard 已提交
326 327 328 329 330
    va_list ap;

    va_start (ap, fmt);
    AUD_vlog (cap, fmt, ap);
    va_end (ap);
B
bellard 已提交
331 332
}

333 334
static void audio_print_options (const char *prefix,
                                 struct audio_option *opt)
B
bellard 已提交
335
{
336 337 338 339 340 341 342 343 344
    char *uprefix;

    if (!prefix) {
        dolog ("No prefix specified\n");
        return;
    }

    if (!opt) {
        dolog ("No options\n");
B
bellard 已提交
345
        return;
346
    }
B
bellard 已提交
347

348
    uprefix = audio_alloc_prefix (prefix);
B
bellard 已提交
349

350 351 352
    for (; opt->name; opt++) {
        const char *state = "default";
        printf ("  %s_%s: ", uprefix, opt->name);
B
bellard 已提交
353

354 355 356
        if (opt->overridenp && *opt->overridenp) {
            state = "current";
        }
B
bellard 已提交
357

358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
        switch (opt->tag) {
        case AUD_OPT_BOOL:
            {
                int *intp = opt->valp;
                printf ("boolean, %s = %d\n", state, *intp ? 1 : 0);
            }
            break;

        case AUD_OPT_INT:
            {
                int *intp = opt->valp;
                printf ("integer, %s = %d\n", state, *intp);
            }
            break;

        case AUD_OPT_FMT:
            {
                audfmt_e *fmtp = opt->valp;
                printf (
                    "format, %s = %s, (one of: U8 S8 U16 S16)\n",
                    state,
                    audio_audfmt_to_string (*fmtp)
                    );
            }
            break;

        case AUD_OPT_STR:
            {
                const char **strp = opt->valp;
                printf ("string, %s = %s\n",
                        state,
                        *strp ? *strp : "(not set)");
B
bellard 已提交
390
            }
391 392 393 394 395 396 397
            break;

        default:
            printf ("???\n");
            dolog ("Bad value tag for option %s_%s %d\n",
                   uprefix, opt->name, opt->tag);
            break;
B
bellard 已提交
398
        }
399
        printf ("    %s\n", opt->descr);
B
bellard 已提交
400
    }
401 402

    qemu_free (uprefix);
B
bellard 已提交
403 404
}

405 406
static void audio_process_options (const char *prefix,
                                   struct audio_option *opt)
B
bellard 已提交
407
{
408 409 410
    char *optname;
    const char qemu_prefix[] = "QEMU_";
    size_t preflen;
B
bellard 已提交
411

412 413 414 415
    if (audio_bug (AUDIO_FUNC, !prefix)) {
        dolog ("prefix = NULL\n");
        return;
    }
B
bellard 已提交
416

417 418 419
    if (audio_bug (AUDIO_FUNC, !opt)) {
        dolog ("opt = NULL\n");
        return;
B
bellard 已提交
420 421
    }

422
    preflen = strlen (prefix);
B
bellard 已提交
423

424 425 426 427 428 429 430 431 432 433 434
    for (; opt->name; opt++) {
        size_t len, i;
        int def;

        if (!opt->valp) {
            dolog ("Option value pointer for `%s' is not set\n",
                   opt->name);
            continue;
        }

        len = strlen (opt->name);
B
bellard 已提交
435 436 437
        /* len of opt->name + len of prefix + size of qemu_prefix
         * (includes trailing zero) + zero + underscore (on behalf of
         * sizeof) */
438 439
        optname = qemu_malloc (len + preflen + sizeof (qemu_prefix) + 1);
        if (!optname) {
B
bellard 已提交
440
            dolog ("Could not allocate memory for option name `%s'\n",
441 442 443 444 445
                   opt->name);
            continue;
        }

        strcpy (optname, qemu_prefix);
B
bellard 已提交
446 447

        /* copy while upper-casing, including trailing zero */
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
        for (i = 0; i <= preflen; ++i) {
            optname[i + sizeof (qemu_prefix) - 1] = toupper (prefix[i]);
        }
        strcat (optname, "_");
        strcat (optname, opt->name);

        def = 1;
        switch (opt->tag) {
        case AUD_OPT_BOOL:
        case AUD_OPT_INT:
            {
                int *intp = opt->valp;
                *intp = audio_get_conf_int (optname, *intp, &def);
            }
            break;

        case AUD_OPT_FMT:
            {
                audfmt_e *fmtp = opt->valp;
                *fmtp = audio_get_conf_fmt (optname, *fmtp, &def);
            }
            break;

        case AUD_OPT_STR:
            {
                const char **strp = opt->valp;
                *strp = audio_get_conf_str (optname, *strp, &def);
            }
            break;

        default:
            dolog ("Bad value tag for option `%s' - %d\n",
                   optname, opt->tag);
B
bellard 已提交
481 482 483
            break;
        }

484 485 486 487 488 489
        if (!opt->overridenp) {
            opt->overridenp = &opt->overriden;
        }
        *opt->overridenp = !def;
        qemu_free (optname);
    }
B
bellard 已提交
490 491
}

B
bellard 已提交
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
static void audio_print_settings (audsettings_t *as)
{
    dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);

    switch (as->fmt) {
    case AUD_FMT_S8:
        AUD_log (NULL, "S8");
        break;
    case AUD_FMT_U8:
        AUD_log (NULL, "U8");
        break;
    case AUD_FMT_S16:
        AUD_log (NULL, "S16");
        break;
    case AUD_FMT_U16:
        AUD_log (NULL, "U16");
        break;
    default:
        AUD_log (NULL, "invalid(%d)", as->fmt);
        break;
    }
B
bellard 已提交
513 514

    AUD_log (NULL, " endianness=");
B
bellard 已提交
515 516 517 518 519 520 521 522 523 524 525
    switch (as->endianness) {
    case 0:
        AUD_log (NULL, "little");
        break;
    case 1:
        AUD_log (NULL, "big");
        break;
    default:
        AUD_log (NULL, "invalid");
        break;
    }
B
bellard 已提交
526 527 528
    AUD_log (NULL, "\n");
}

B
bellard 已提交
529
static int audio_validate_settings (audsettings_t *as)
B
bellard 已提交
530 531 532 533
{
    int invalid;

    invalid = as->nchannels != 1 && as->nchannels != 2;
B
bellard 已提交
534
    invalid |= as->endianness != 0 && as->endianness != 1;
B
bellard 已提交
535 536 537 538 539 540 541 542 543 544 545 546 547

    switch (as->fmt) {
    case AUD_FMT_S8:
    case AUD_FMT_U8:
    case AUD_FMT_S16:
    case AUD_FMT_U16:
        break;
    default:
        invalid = 1;
        break;
    }

    invalid |= as->freq <= 0;
B
bellard 已提交
548
    return invalid ? -1 : 0;
B
bellard 已提交
549 550 551
}

static int audio_pcm_info_eq (struct audio_pcm_info *info, audsettings_t *as)
B
bellard 已提交
552
{
553
    int bits = 8, sign = 0;
B
bellard 已提交
554

B
bellard 已提交
555
    switch (as->fmt) {
556 557 558 559 560 561 562 563 564 565
    case AUD_FMT_S8:
        sign = 1;
    case AUD_FMT_U8:
        break;

    case AUD_FMT_S16:
        sign = 1;
    case AUD_FMT_U16:
        bits = 16;
        break;
B
bellard 已提交
566
    }
B
bellard 已提交
567 568
    return info->freq == as->freq
        && info->nchannels == as->nchannels
569
        && info->sign == sign
B
bellard 已提交
570 571
        && info->bits == bits
        && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
572
}
B
bellard 已提交
573

B
bellard 已提交
574
void audio_pcm_init_info (struct audio_pcm_info *info, audsettings_t *as)
575 576 577
{
    int bits = 8, sign = 0;

B
bellard 已提交
578
    switch (as->fmt) {
B
bellard 已提交
579 580 581 582 583 584 585 586 587 588 589 590
    case AUD_FMT_S8:
        sign = 1;
    case AUD_FMT_U8:
        break;

    case AUD_FMT_S16:
        sign = 1;
    case AUD_FMT_U16:
        bits = 16;
        break;
    }

B
bellard 已提交
591
    info->freq = as->freq;
592 593
    info->bits = bits;
    info->sign = sign;
B
bellard 已提交
594 595
    info->nchannels = as->nchannels;
    info->shift = (as->nchannels == 2) + (bits == 16);
596 597
    info->align = (1 << info->shift) - 1;
    info->bytes_per_second = info->freq << info->shift;
B
bellard 已提交
598
    info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
B
bellard 已提交
599 600
}

601
void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
B
bellard 已提交
602
{
603 604 605 606 607 608
    if (!len) {
        return;
    }

    if (info->sign) {
        memset (buf, len << info->shift, 0x00);
B
bellard 已提交
609 610
    }
    else {
611 612 613 614 615 616 617 618 619
        if (info->bits == 8) {
            memset (buf, len << info->shift, 0x80);
        }
        else {
            int i;
            uint16_t *p = buf;
            int shift = info->nchannels - 1;
            short s = INT16_MAX;

B
bellard 已提交
620
            if (info->swap_endianness) {
621 622 623 624 625 626 627
                s = bswap16 (s);
            }

            for (i = 0; i < len << shift; i++) {
                p[i] = s;
            }
        }
B
bellard 已提交
628 629 630
    }
}

631 632 633 634 635 636 637 638 639 640 641 642 643 644
/*
 * Capture
 */
static void noop_conv (st_sample_t *dst, const void *src,
                       int samples, volume_t *vol)
{
    (void) src;
    (void) dst;
    (void) samples;
    (void) vol;
}

static CaptureVoiceOut *audio_pcm_capture_find_specific (
    AudioState *s,
B
bellard 已提交
645
    audsettings_t *as
646 647 648 649 650
    )
{
    CaptureVoiceOut *cap;

    for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
B
bellard 已提交
651
        if (audio_pcm_info_eq (&cap->hw.info, as)) {
652 653 654 655 656 657
            return cap;
        }
    }
    return NULL;
}

B
bellard 已提交
658
static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
659
{
B
bellard 已提交
660 661 662 663 664 665 666 667 668
    struct capture_callback *cb;

#ifdef DEBUG_CAPTURE
    dolog ("notification %d sent\n", cmd);
#endif
    for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
        cb->ops.notify (cb->opaque, cmd);
    }
}
669

B
bellard 已提交
670 671 672 673
static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
{
    if (cap->hw.enabled != enabled) {
        audcnotification_e cmd;
674
        cap->hw.enabled = enabled;
B
bellard 已提交
675 676
        cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
        audio_notify_capture (cap, cmd);
677 678 679 680 681 682 683 684 685
    }
}

static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
{
    HWVoiceOut *hw = &cap->hw;
    SWVoiceOut *sw;
    int enabled = 0;

B
bellard 已提交
686
    for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
687 688 689 690 691
        if (sw->active) {
            enabled = 1;
            break;
        }
    }
B
bellard 已提交
692
    audio_capture_maybe_changed (cap, enabled);
693 694 695 696
}

static void audio_detach_capture (HWVoiceOut *hw)
{
B
bellard 已提交
697 698 699 700 701 702 703
    SWVoiceCap *sc = hw->cap_head.lh_first;

    while (sc) {
        SWVoiceCap *sc1 = sc->entries.le_next;
        SWVoiceOut *sw = &sc->sw;
        CaptureVoiceOut *cap = sc->cap;
        int was_active = sw->active;
704 705 706 707 708 709 710

        if (sw->rate) {
            st_rate_stop (sw->rate);
            sw->rate = NULL;
        }

        LIST_REMOVE (sw, entries);
B
bellard 已提交
711 712 713 714 715 716 717 718 719
        LIST_REMOVE (sc, entries);
        qemu_free (sc);
        if (was_active) {
            /* We have removed soft voice from the capture:
               this might have changed the overall status of the capture
               since this might have been the only active voice */
            audio_recalc_and_notify_capture (cap);
        }
        sc = sc1;
720 721 722 723 724 725 726 727 728
    }
}

static int audio_attach_capture (AudioState *s, HWVoiceOut *hw)
{
    CaptureVoiceOut *cap;

    audio_detach_capture (hw);
    for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
B
bellard 已提交
729
        SWVoiceCap *sc;
730
        SWVoiceOut *sw;
B
bellard 已提交
731
        HWVoiceOut *hw_cap = &cap->hw;
732

B
bellard 已提交
733 734
        sc = audio_calloc (AUDIO_FUNC, 1, sizeof (*sc));
        if (!sc) {
735
            dolog ("Could not allocate soft capture voice (%zu bytes)\n",
B
bellard 已提交
736
                   sizeof (*sc));
737 738 739
            return -1;
        }

B
bellard 已提交
740 741
        sc->cap = cap;
        sw = &sc->sw;
742
        sw->hw = hw_cap;
B
bellard 已提交
743
        sw->info = hw->info;
744 745 746 747 748 749 750 751 752 753 754
        sw->empty = 1;
        sw->active = hw->enabled;
        sw->conv = noop_conv;
        sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
        sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
        if (!sw->rate) {
            dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
            qemu_free (sw);
            return -1;
        }
        LIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
B
bellard 已提交
755 756 757 758 759 760
        LIST_INSERT_HEAD (&hw->cap_head, sc, entries);
#ifdef DEBUG_CAPTURE
        asprintf (&sw->name, "for %p %d,%d,%d",
                  hw, sw->info.freq, sw->info.bits, sw->info.nchannels);
        dolog ("Added %s active = %d\n", sw->name, sw->active);
#endif
761
        if (sw->active) {
B
bellard 已提交
762
            audio_capture_maybe_changed (cap, 1);
763 764 765 766 767
        }
    }
    return 0;
}

768 769 770
/*
 * Hard voice (capture)
 */
B
bellard 已提交
771
static int audio_pcm_hw_find_min_in (HWVoiceIn *hw)
B
bellard 已提交
772
{
773 774 775 776 777 778 779
    SWVoiceIn *sw;
    int m = hw->total_samples_captured;

    for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
        if (sw->active) {
            m = audio_MIN (m, sw->total_hw_samples_acquired);
        }
B
bellard 已提交
780
    }
781
    return m;
B
bellard 已提交
782 783
}

784
int audio_pcm_hw_get_live_in (HWVoiceIn *hw)
B
bellard 已提交
785
{
786 787 788 789
    int live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
    if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
        dolog ("live=%d hw->samples=%d\n", live, hw->samples);
        return 0;
B
bellard 已提交
790
    }
791
    return live;
B
bellard 已提交
792 793
}

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
/*
 * Soft voice (capture)
 */
static int audio_pcm_sw_get_rpos_in (SWVoiceIn *sw)
{
    HWVoiceIn *hw = sw->hw;
    int live = hw->total_samples_captured - sw->total_hw_samples_acquired;
    int rpos;

    if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
        dolog ("live=%d hw->samples=%d\n", live, hw->samples);
        return 0;
    }

    rpos = hw->wpos - live;
    if (rpos >= 0) {
        return rpos;
B
bellard 已提交
811 812
    }
    else {
813
        return hw->samples + rpos;
B
bellard 已提交
814 815 816
    }
}

817
int audio_pcm_sw_read (SWVoiceIn *sw, void *buf, int size)
B
bellard 已提交
818
{
819 820
    HWVoiceIn *hw = sw->hw;
    int samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
B
bellard 已提交
821
    st_sample_t *src, *dst = sw->buf;
822 823 824 825 826 827 828 829 830 831 832 833 834

    rpos = audio_pcm_sw_get_rpos_in (sw) % hw->samples;

    live = hw->total_samples_captured - sw->total_hw_samples_acquired;
    if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
        dolog ("live_in=%d hw->samples=%d\n", live, hw->samples);
        return 0;
    }

    samples = size >> sw->info.shift;
    if (!live) {
        return 0;
    }
B
bellard 已提交
835

836 837
    swlim = (live * sw->ratio) >> 32;
    swlim = audio_MIN (swlim, samples);
B
bellard 已提交
838

839 840 841 842 843 844 845
    while (swlim) {
        src = hw->conv_buf + rpos;
        isamp = hw->wpos - rpos;
        /* XXX: <= ? */
        if (isamp <= 0) {
            isamp = hw->samples - rpos;
        }
B
bellard 已提交
846

847 848 849 850
        if (!isamp) {
            break;
        }
        osamp = swlim;
B
bellard 已提交
851

852 853
        if (audio_bug (AUDIO_FUNC, osamp < 0)) {
            dolog ("osamp=%d\n", osamp);
B
bellard 已提交
854
            return 0;
855
        }
B
bellard 已提交
856

857 858 859 860 861 862 863
        st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
        swlim -= osamp;
        rpos = (rpos + isamp) % hw->samples;
        dst += osamp;
        ret += osamp;
        total += isamp;
    }
B
bellard 已提交
864

B
bellard 已提交
865
    sw->clip (buf, sw->buf, ret);
866 867
    sw->total_hw_samples_acquired += total;
    return ret << sw->info.shift;
B
bellard 已提交
868 869
}

870 871 872
/*
 * Hard voice (playback)
 */
B
bellard 已提交
873
static int audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
874
{
B
bellard 已提交
875 876 877
    SWVoiceOut *sw;
    int m = INT_MAX;
    int nb_live = 0;
B
bellard 已提交
878

B
bellard 已提交
879 880 881 882 883
    for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
        if (sw->active || !sw->empty) {
            m = audio_MIN (m, sw->total_hw_samples_mixed);
            nb_live += 1;
        }
B
bellard 已提交
884
    }
B
bellard 已提交
885 886 887

    *nb_livep = nb_live;
    return m;
888
}
B
bellard 已提交
889

890 891 892
int audio_pcm_hw_get_live_out2 (HWVoiceOut *hw, int *nb_live)
{
    int smin;
B
bellard 已提交
893

894 895 896 897
    smin = audio_pcm_hw_find_min_out (hw, nb_live);

    if (!*nb_live) {
        return 0;
B
bellard 已提交
898 899
    }
    else {
900 901 902 903 904
        int live = smin;

        if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
            dolog ("live=%d hw->samples=%d\n", live, hw->samples);
            return 0;
B
bellard 已提交
905
        }
906
        return live;
B
bellard 已提交
907
    }
908 909 910 911 912 913
}

int audio_pcm_hw_get_live_out (HWVoiceOut *hw)
{
    int nb_live;
    int live;
B
bellard 已提交
914

915 916 917 918
    live = audio_pcm_hw_get_live_out2 (hw, &nb_live);
    if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
        dolog ("live=%d hw->samples=%d\n", live, hw->samples);
        return 0;
B
bellard 已提交
919
    }
920
    return live;
B
bellard 已提交
921 922
}

923 924 925 926
/*
 * Soft voice (playback)
 */
int audio_pcm_sw_write (SWVoiceOut *sw, void *buf, int size)
B
bellard 已提交
927
{
928 929
    int hwsamples, samples, isamp, osamp, wpos, live, dead, left, swlim, blck;
    int ret = 0, pos = 0, total = 0;
B
bellard 已提交
930

931 932 933
    if (!sw) {
        return size;
    }
B
bellard 已提交
934

935
    hwsamples = sw->hw->samples;
B
bellard 已提交
936

937 938 939 940 941
    live = sw->total_hw_samples_mixed;
    if (audio_bug (AUDIO_FUNC, live < 0 || live > hwsamples)){
        dolog ("live=%d hw->samples=%d\n", live, hwsamples);
        return 0;
    }
B
bellard 已提交
942

943
    if (live == hwsamples) {
B
bellard 已提交
944 945 946
#ifdef DEBUG_OUT
        dolog ("%s is full %d\n", sw->name, live);
#endif
947 948
        return 0;
    }
B
bellard 已提交
949

950 951
    wpos = (sw->hw->rpos + live) % hwsamples;
    samples = size >> sw->info.shift;
B
bellard 已提交
952

953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
    dead = hwsamples - live;
    swlim = ((int64_t) dead << 32) / sw->ratio;
    swlim = audio_MIN (swlim, samples);
    if (swlim) {
        sw->conv (sw->buf, buf, swlim, &sw->vol);
    }

    while (swlim) {
        dead = hwsamples - live;
        left = hwsamples - wpos;
        blck = audio_MIN (dead, left);
        if (!blck) {
            break;
        }
        isamp = swlim;
        osamp = blck;
        st_rate_flow_mix (
            sw->rate,
            sw->buf + pos,
            sw->hw->mix_buf + wpos,
            &isamp,
            &osamp
            );
        ret += isamp;
        swlim -= isamp;
        pos += isamp;
        live += osamp;
        wpos = (wpos + osamp) % hwsamples;
        total += osamp;
    }

    sw->total_hw_samples_mixed += total;
    sw->empty = sw->total_hw_samples_mixed == 0;

#ifdef DEBUG_OUT
    dolog (
B
bellard 已提交
989 990
        "%s: write size %d ret %d total sw %d\n",
        SW_NAME (sw),
991 992
        size >> sw->info.shift,
        ret,
B
bellard 已提交
993
        sw->total_hw_samples_mixed
994 995 996 997
        );
#endif

    return ret << sw->info.shift;
B
bellard 已提交
998 999
}

1000 1001
#ifdef DEBUG_AUDIO
static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
B
bellard 已提交
1002
{
1003 1004
    dolog ("%s: bits %d, sign %d, freq %d, nchan %d\n",
           cap, info->bits, info->sign, info->freq, info->nchannels);
B
bellard 已提交
1005
}
1006
#endif
B
bellard 已提交
1007

1008 1009 1010 1011 1012 1013
#define DAC
#include "audio_template.h"
#undef DAC
#include "audio_template.h"

int AUD_write (SWVoiceOut *sw, void *buf, int size)
B
bellard 已提交
1014
{
1015
    int bytes;
B
bellard 已提交
1016

1017 1018 1019 1020
    if (!sw) {
        /* XXX: Consider options */
        return size;
    }
B
bellard 已提交
1021

1022
    if (!sw->hw->enabled) {
B
bellard 已提交
1023
        dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
B
bellard 已提交
1024 1025 1026
        return 0;
    }

1027 1028 1029 1030 1031 1032 1033
    bytes = sw->hw->pcm_ops->write (sw, buf, size);
    return bytes;
}

int AUD_read (SWVoiceIn *sw, void *buf, int size)
{
    int bytes;
B
bellard 已提交
1034

1035 1036 1037
    if (!sw) {
        /* XXX: Consider options */
        return size;
B
bellard 已提交
1038
    }
1039 1040

    if (!sw->hw->enabled) {
B
bellard 已提交
1041
        dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
1042
        return 0;
B
bellard 已提交
1043
    }
1044 1045 1046

    bytes = sw->hw->pcm_ops->read (sw, buf, size);
    return bytes;
B
bellard 已提交
1047 1048
}

1049
int AUD_get_buffer_size_out (SWVoiceOut *sw)
B
bellard 已提交
1050
{
B
bellard 已提交
1051
    return sw->hw->samples << sw->hw->info.shift;
1052 1053 1054 1055 1056
}

void AUD_set_active_out (SWVoiceOut *sw, int on)
{
    HWVoiceOut *hw;
B
bellard 已提交
1057

1058
    if (!sw) {
B
bellard 已提交
1059
        return;
1060
    }
B
bellard 已提交
1061 1062

    hw = sw->hw;
1063 1064
    if (sw->active != on) {
        SWVoiceOut *temp_sw;
B
bellard 已提交
1065
        SWVoiceCap *sc;
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084

        if (on) {
            hw->pending_disable = 0;
            if (!hw->enabled) {
                hw->enabled = 1;
                hw->pcm_ops->ctl_out (hw, VOICE_ENABLE);
            }
        }
        else {
            if (hw->enabled) {
                int nb_active = 0;

                for (temp_sw = hw->sw_head.lh_first; temp_sw;
                     temp_sw = temp_sw->entries.le_next) {
                    nb_active += temp_sw->active != 0;
                }

                hw->pending_disable = nb_active == 1;
            }
B
bellard 已提交
1085
        }
B
bellard 已提交
1086 1087 1088

        for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
            sc->sw.active = hw->enabled;
1089
            if (hw->enabled) {
B
bellard 已提交
1090
                audio_capture_maybe_changed (sc->cap, 1);
1091 1092
            }
        }
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
        sw->active = on;
    }
}

void AUD_set_active_in (SWVoiceIn *sw, int on)
{
    HWVoiceIn *hw;

    if (!sw) {
        return;
B
bellard 已提交
1103 1104
    }

1105
    hw = sw->hw;
B
bellard 已提交
1106
    if (sw->active != on) {
1107 1108
        SWVoiceIn *temp_sw;

B
bellard 已提交
1109 1110 1111
        if (on) {
            if (!hw->enabled) {
                hw->enabled = 1;
1112
                hw->pcm_ops->ctl_in (hw, VOICE_ENABLE);
B
bellard 已提交
1113
            }
1114
            sw->total_hw_samples_acquired = hw->total_samples_captured;
B
bellard 已提交
1115 1116
        }
        else {
1117
            if (hw->enabled) {
B
bellard 已提交
1118
                int nb_active = 0;
1119 1120 1121 1122

                for (temp_sw = hw->sw_head.lh_first; temp_sw;
                     temp_sw = temp_sw->entries.le_next) {
                    nb_active += temp_sw->active != 0;
B
bellard 已提交
1123 1124 1125
                }

                if (nb_active == 1) {
1126 1127
                    hw->enabled = 0;
                    hw->pcm_ops->ctl_in (hw, VOICE_DISABLE);
B
bellard 已提交
1128 1129 1130 1131 1132 1133 1134
                }
            }
        }
        sw->active = on;
    }
}

1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
static int audio_get_avail (SWVoiceIn *sw)
{
    int live;

    if (!sw) {
        return 0;
    }

    live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
    if (audio_bug (AUDIO_FUNC, live < 0 || live > sw->hw->samples)) {
        dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples);
        return 0;
    }

    ldebug (
B
bellard 已提交
1150
        "%s: get_avail live %d ret %" PRId64 "\n",
B
bellard 已提交
1151
        SW_NAME (sw),
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
        live, (((int64_t) live << 32) / sw->ratio) << sw->info.shift
        );

    return (((int64_t) live << 32) / sw->ratio) << sw->info.shift;
}

static int audio_get_free (SWVoiceOut *sw)
{
    int live, dead;

    if (!sw) {
        return 0;
    }

    live = sw->total_hw_samples_mixed;

    if (audio_bug (AUDIO_FUNC, live < 0 || live > sw->hw->samples)) {
        dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples);
B
bellard 已提交
1170
        return 0;
1171 1172 1173 1174 1175
    }

    dead = sw->hw->samples - live;

#ifdef DEBUG_OUT
B
bellard 已提交
1176
    dolog ("%s: get_free live %d dead %d ret %" PRId64 "\n",
B
bellard 已提交
1177
           SW_NAME (sw),
1178
           live, dead, (((int64_t) dead << 32) / sw->ratio) << sw->info.shift);
B
bellard 已提交
1179
#endif
1180 1181 1182 1183

    return (((int64_t) dead << 32) / sw->ratio) << sw->info.shift;
}

1184 1185 1186 1187 1188
static void audio_capture_mix_and_clear (HWVoiceOut *hw, int rpos, int samples)
{
    int n;

    if (hw->enabled) {
B
bellard 已提交
1189
        SWVoiceCap *sc;
1190

B
bellard 已提交
1191 1192
        for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
            SWVoiceOut *sw = &sc->sw;
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
            int rpos2 = rpos;

            n = samples;
            while (n) {
                int till_end_of_hw = hw->samples - rpos2;
                int to_write = audio_MIN (till_end_of_hw, n);
                int bytes = to_write << hw->info.shift;
                int written;

                sw->buf = hw->mix_buf + rpos2;
                written = audio_pcm_sw_write (sw, NULL, bytes);
                if (written - bytes) {
B
bellard 已提交
1205 1206 1207
                    dolog ("Could not mix %d bytes into a capture "
                           "buffer, mixed %d\n",
                           bytes, written);
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
                    break;
                }
                n -= to_write;
                rpos2 = (rpos2 + to_write) % hw->samples;
            }
        }
    }

    n = audio_MIN (samples, hw->samples - rpos);
    mixeng_clear (hw->mix_buf + rpos, n);
    mixeng_clear (hw->mix_buf, samples - n);
}

B
bellard 已提交
1221
static void audio_run_out (AudioState *s)
1222 1223 1224 1225
{
    HWVoiceOut *hw = NULL;
    SWVoiceOut *sw;

B
bellard 已提交
1226
    while ((hw = audio_pcm_hw_find_any_enabled_out (s, hw))) {
1227
        int played;
1228
        int live, free, nb_live, cleanup_required, prev_rpos;
1229 1230 1231 1232 1233

        live = audio_pcm_hw_get_live_out2 (hw, &nb_live);
        if (!nb_live) {
            live = 0;
        }
B
bellard 已提交
1234

1235 1236
        if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
            dolog ("live=%d hw->samples=%d\n", live, hw->samples);
B
bellard 已提交
1237
            continue;
1238 1239 1240
        }

        if (hw->pending_disable && !nb_live) {
B
bellard 已提交
1241
            SWVoiceCap *sc;
1242 1243
#ifdef DEBUG_OUT
            dolog ("Disabling voice\n");
B
bellard 已提交
1244
#endif
1245 1246 1247
            hw->enabled = 0;
            hw->pending_disable = 0;
            hw->pcm_ops->ctl_out (hw, VOICE_DISABLE);
B
bellard 已提交
1248 1249 1250
            for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
                sc->sw.active = 0;
                audio_recalc_and_notify_capture (sc->cap);
1251
            }
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
            continue;
        }

        if (!live) {
            for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
                if (sw->active) {
                    free = audio_get_free (sw);
                    if (free > 0) {
                        sw->callback.fn (sw->callback.opaque, free);
                    }
                }
            }
            continue;
        }

1267
        prev_rpos = hw->rpos;
1268 1269 1270 1271 1272 1273 1274 1275
        played = hw->pcm_ops->run_out (hw);
        if (audio_bug (AUDIO_FUNC, hw->rpos >= hw->samples)) {
            dolog ("hw->rpos=%d hw->samples=%d played=%d\n",
                   hw->rpos, hw->samples, played);
            hw->rpos = 0;
        }

#ifdef DEBUG_OUT
B
bellard 已提交
1276
        dolog ("played=%d\n", played);
B
bellard 已提交
1277
#endif
1278 1279 1280

        if (played) {
            hw->ts_helper += played;
1281
            audio_capture_mix_and_clear (hw, prev_rpos, played);
1282 1283
        }

B
bellard 已提交
1284
        cleanup_required = 0;
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
        for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
            if (!sw->active && sw->empty) {
                continue;
            }

            if (audio_bug (AUDIO_FUNC, played > sw->total_hw_samples_mixed)) {
                dolog ("played=%d sw->total_hw_samples_mixed=%d\n",
                       played, sw->total_hw_samples_mixed);
                played = sw->total_hw_samples_mixed;
            }

            sw->total_hw_samples_mixed -= played;

            if (!sw->total_hw_samples_mixed) {
                sw->empty = 1;
B
bellard 已提交
1300
                cleanup_required |= !sw->active && !sw->callback.fn;
1301 1302 1303 1304 1305 1306 1307 1308 1309
            }

            if (sw->active) {
                free = audio_get_free (sw);
                if (free > 0) {
                    sw->callback.fn (sw->callback.opaque, free);
                }
            }
        }
B
bellard 已提交
1310 1311

        if (cleanup_required) {
B
bellard 已提交
1312 1313 1314 1315 1316
            SWVoiceOut *sw1;

            sw = hw->sw_head.lh_first;
            while (sw) {
                sw1 = sw->entries.le_next;
B
bellard 已提交
1317 1318 1319 1320 1321 1322
                if (!sw->active && !sw->callback.fn) {
#ifdef DEBUG_PLIVE
                    dolog ("Finishing with old voice\n");
#endif
                    audio_close_out (s, sw);
                }
B
bellard 已提交
1323
                sw = sw1;
B
bellard 已提交
1324 1325
            }
        }
1326 1327 1328
    }
}

B
bellard 已提交
1329
static void audio_run_in (AudioState *s)
1330 1331 1332
{
    HWVoiceIn *hw = NULL;

B
bellard 已提交
1333
    while ((hw = audio_pcm_hw_find_any_enabled_in (s, hw))) {
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
        SWVoiceIn *sw;
        int captured, min;

        captured = hw->pcm_ops->run_in (hw);

        min = audio_pcm_hw_find_min_in (hw);
        hw->total_samples_captured += captured - min;
        hw->ts_helper += captured;

        for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
            sw->total_hw_samples_acquired -= min;

            if (sw->active) {
                int avail;

                avail = audio_get_avail (sw);
                if (avail > 0) {
                    sw->callback.fn (sw->callback.opaque, avail);
                }
            }
        }
    }
}

1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
static void audio_run_capture (AudioState *s)
{
    CaptureVoiceOut *cap;

    for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
        int live, rpos, captured;
        HWVoiceOut *hw = &cap->hw;
        SWVoiceOut *sw;

        captured = live = audio_pcm_hw_get_live_out (hw);
        rpos = hw->rpos;
        while (live) {
            int left = hw->samples - rpos;
            int to_capture = audio_MIN (live, left);
            st_sample_t *src;
            struct capture_callback *cb;

            src = hw->mix_buf + rpos;
            hw->clip (cap->buf, src, to_capture);
            mixeng_clear (src, to_capture);

            for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
                cb->ops.capture (cb->opaque, cap->buf,
                                 to_capture << hw->info.shift);
            }
            rpos = (rpos + to_capture) % hw->samples;
            live -= to_capture;
        }
        hw->rpos = rpos;

        for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
            if (!sw->active && sw->empty) {
                continue;
            }

            if (audio_bug (AUDIO_FUNC, captured > sw->total_hw_samples_mixed)) {
                dolog ("captured=%d sw->total_hw_samples_mixed=%d\n",
                       captured, sw->total_hw_samples_mixed);
                captured = sw->total_hw_samples_mixed;
            }

            sw->total_hw_samples_mixed -= captured;
            sw->empty = sw->total_hw_samples_mixed == 0;
        }
    }
}

B
bellard 已提交
1405 1406 1407 1408 1409 1410
static void audio_timer (void *opaque)
{
    AudioState *s = opaque;

    audio_run_out (s);
    audio_run_in (s);
1411
    audio_run_capture (s);
B
bellard 已提交
1412 1413 1414 1415

    qemu_mod_timer (s->ts, qemu_get_clock (vm_clock) + conf.period.ticks);
}

1416 1417
static struct audio_option audio_options[] = {
    /* DAC */
B
bellard 已提交
1418
    {"DAC_FIXED_SETTINGS", AUD_OPT_BOOL, &conf.fixed_out.enabled,
1419 1420
     "Use fixed settings for host DAC", NULL, 0},

B
bellard 已提交
1421
    {"DAC_FIXED_FREQ", AUD_OPT_INT, &conf.fixed_out.settings.freq,
1422 1423
     "Frequency for fixed host DAC", NULL, 0},

B
bellard 已提交
1424
    {"DAC_FIXED_FMT", AUD_OPT_FMT, &conf.fixed_out.settings.fmt,
1425 1426
     "Format for fixed host DAC", NULL, 0},

B
bellard 已提交
1427
    {"DAC_FIXED_CHANNELS", AUD_OPT_INT, &conf.fixed_out.settings.nchannels,
1428 1429
     "Number of channels for fixed DAC (1 - mono, 2 - stereo)", NULL, 0},

B
bellard 已提交
1430
    {"DAC_VOICES", AUD_OPT_INT, &conf.fixed_out.nb_voices,
1431 1432 1433
     "Number of voices for DAC", NULL, 0},

    /* ADC */
B
bellard 已提交
1434
    {"ADC_FIXED_SETTINGS", AUD_OPT_BOOL, &conf.fixed_in.enabled,
1435 1436
     "Use fixed settings for host ADC", NULL, 0},

B
bellard 已提交
1437 1438
    {"ADC_FIXED_FREQ", AUD_OPT_INT, &conf.fixed_in.settings.freq,
     "Frequency for fixed host ADC", NULL, 0},
1439

B
bellard 已提交
1440 1441
    {"ADC_FIXED_FMT", AUD_OPT_FMT, &conf.fixed_in.settings.fmt,
     "Format for fixed host ADC", NULL, 0},
1442

B
bellard 已提交
1443
    {"ADC_FIXED_CHANNELS", AUD_OPT_INT, &conf.fixed_in.settings.nchannels,
1444 1445
     "Number of channels for fixed ADC (1 - mono, 2 - stereo)", NULL, 0},

B
bellard 已提交
1446
    {"ADC_VOICES", AUD_OPT_INT, &conf.fixed_in.nb_voices,
1447 1448 1449
     "Number of voices for ADC", NULL, 0},

    /* Misc */
B
bellard 已提交
1450 1451
    {"TIMER_PERIOD", AUD_OPT_INT, &conf.period.hz,
     "Timer period in HZ (0 - use lowest possible)", NULL, 0},
1452

B
bellard 已提交
1453
    {"PLIVE", AUD_OPT_BOOL, &conf.plive,
1454 1455
     "(undocumented)", NULL, 0},

B
bellard 已提交
1456 1457 1458
    {"LOG_TO_MONITOR", AUD_OPT_BOOL, &conf.log_to_monitor,
     "print logging messages to montior instead of stderr", NULL, 0},

1459
    {NULL, 0, NULL, NULL, NULL, 0}
B
bellard 已提交
1460 1461
};

B
bellard 已提交
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
static void audio_pp_nb_voices (const char *typ, int nb)
{
    switch (nb) {
    case 0:
        printf ("Does not support %s\n", typ);
        break;
    case 1:
        printf ("One %s voice\n", typ);
        break;
    case INT_MAX:
        printf ("Theoretically supports many %s voices\n", typ);
        break;
    default:
        printf ("Theoretically supports upto %d %s voices\n", nb, typ);
        break;
    }

}

1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
void AUD_help (void)
{
    size_t i;

    audio_process_options ("AUDIO", audio_options);
    for (i = 0; i < sizeof (drvtab) / sizeof (drvtab[0]); i++) {
        struct audio_driver *d = drvtab[i];
        if (d->options) {
            audio_process_options (d->name, d->options);
        }
    }

    printf ("Audio options:\n");
    audio_print_options ("AUDIO", audio_options);
    printf ("\n");

    printf ("Available drivers:\n");

    for (i = 0; i < sizeof (drvtab) / sizeof (drvtab[0]); i++) {
        struct audio_driver *d = drvtab[i];

        printf ("Name: %s\n", d->name);
        printf ("Description: %s\n", d->descr);

B
bellard 已提交
1505 1506
        audio_pp_nb_voices ("playback", d->max_voices_out);
        audio_pp_nb_voices ("capture", d->max_voices_in);
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522

        if (d->options) {
            printf ("Options:\n");
            audio_print_options (d->name, d->options);
        }
        else {
            printf ("No options\n");
        }
        printf ("\n");
    }

    printf (
        "Options are settable through environment variables.\n"
        "Example:\n"
#ifdef _WIN32
        "  set QEMU_AUDIO_DRV=wav\n"
B
bellard 已提交
1523
        "  set QEMU_WAV_PATH=c:\\tune.wav\n"
1524 1525 1526 1527 1528 1529 1530 1531 1532
#else
        "  export QEMU_AUDIO_DRV=wav\n"
        "  export QEMU_WAV_PATH=$HOME/tune.wav\n"
        "(for csh replace export with setenv in the above)\n"
#endif
        "  qemu ...\n\n"
        );
}

B
bellard 已提交
1533
static int audio_driver_init (AudioState *s, struct audio_driver *drv)
B
bellard 已提交
1534
{
1535 1536 1537
    if (drv->options) {
        audio_process_options (drv->name, drv->options);
    }
B
bellard 已提交
1538
    s->drv_opaque = drv->init ();
1539

B
bellard 已提交
1540
    if (s->drv_opaque) {
B
bellard 已提交
1541 1542
        audio_init_nb_voices_out (s, drv);
        audio_init_nb_voices_in (s, drv);
B
bellard 已提交
1543
        s->drv = drv;
1544
        return 0;
B
bellard 已提交
1545 1546
    }
    else {
1547 1548
        dolog ("Could not init `%s' audio driver\n", drv->name);
        return -1;
B
bellard 已提交
1549 1550 1551
    }
}

B
bellard 已提交
1552
static void audio_vm_change_state_handler (void *opaque, int running)
B
bellard 已提交
1553
{
B
bellard 已提交
1554
    AudioState *s = opaque;
1555 1556
    HWVoiceOut *hwo = NULL;
    HWVoiceIn *hwi = NULL;
B
bellard 已提交
1557
    int op = running ? VOICE_ENABLE : VOICE_DISABLE;
1558

B
bellard 已提交
1559 1560
    while ((hwo = audio_pcm_hw_find_any_enabled_out (s, hwo))) {
        hwo->pcm_ops->ctl_out (hwo, op);
1561
    }
B
bellard 已提交
1562

B
bellard 已提交
1563 1564
    while ((hwi = audio_pcm_hw_find_any_enabled_in (s, hwi))) {
        hwi->pcm_ops->ctl_in (hwi, op);
B
bellard 已提交
1565 1566 1567 1568 1569
    }
}

static void audio_atexit (void)
{
B
bellard 已提交
1570
    AudioState *s = &glob_audio_state;
1571 1572 1573
    HWVoiceOut *hwo = NULL;
    HWVoiceIn *hwi = NULL;

B
bellard 已提交
1574
    while ((hwo = audio_pcm_hw_find_any_enabled_out (s, hwo))) {
B
bellard 已提交
1575
        SWVoiceCap *sc;
1576

B
bellard 已提交
1577
        hwo->pcm_ops->ctl_out (hwo, VOICE_DISABLE);
1578
        hwo->pcm_ops->fini_out (hwo);
1579

B
bellard 已提交
1580 1581 1582 1583 1584 1585 1586
        for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
            CaptureVoiceOut *cap = sc->cap;
            struct capture_callback *cb;

            for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
                cb->ops.destroy (cb->opaque);
            }
1587
        }
1588
    }
B
bellard 已提交
1589

B
bellard 已提交
1590 1591
    while ((hwi = audio_pcm_hw_find_any_enabled_in (s, hwi))) {
        hwi->pcm_ops->ctl_in (hwi, VOICE_DISABLE);
1592
        hwi->pcm_ops->fini_in (hwi);
B
bellard 已提交
1593
    }
B
bellard 已提交
1594 1595 1596 1597

    if (s->drv) {
        s->drv->fini (s->drv_opaque);
    }
B
bellard 已提交
1598 1599 1600 1601
}

static void audio_save (QEMUFile *f, void *opaque)
{
1602 1603
    (void) f;
    (void) opaque;
B
bellard 已提交
1604 1605 1606 1607
}

static int audio_load (QEMUFile *f, void *opaque, int version_id)
{
1608 1609 1610 1611
    (void) f;
    (void) opaque;

    if (version_id != 1) {
B
bellard 已提交
1612
        return -EINVAL;
1613
    }
B
bellard 已提交
1614 1615 1616 1617

    return 0;
}

B
bellard 已提交
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
void AUD_register_card (AudioState *s, const char *name, QEMUSoundCard *card)
{
    card->audio = s;
    card->name = qemu_strdup (name);
    memset (&card->entries, 0, sizeof (card->entries));
    LIST_INSERT_HEAD (&s->card_head, card, entries);
}

void AUD_remove_card (QEMUSoundCard *card)
{
    LIST_REMOVE (card, entries);
    card->audio = NULL;
    qemu_free (card->name);
}

AudioState *AUD_init (void)
B
bellard 已提交
1634
{
1635
    size_t i;
B
bellard 已提交
1636 1637
    int done = 0;
    const char *drvname;
B
bellard 已提交
1638
    AudioState *s = &glob_audio_state;
1639

B
bellard 已提交
1640 1641
    LIST_INIT (&s->hw_head_out);
    LIST_INIT (&s->hw_head_in);
1642
    LIST_INIT (&s->cap_head);
B
bellard 已提交
1643 1644 1645 1646 1647 1648 1649 1650
    atexit (audio_atexit);

    s->ts = qemu_new_timer (vm_clock, audio_timer, s);
    if (!s->ts) {
        dolog ("Could not create audio timer\n");
        return NULL;
    }

1651 1652
    audio_process_options ("AUDIO", audio_options);

B
bellard 已提交
1653 1654 1655
    s->nb_hw_voices_out = conf.fixed_out.nb_voices;
    s->nb_hw_voices_in = conf.fixed_in.nb_voices;

1656
    if (s->nb_hw_voices_out <= 0) {
B
bellard 已提交
1657
        dolog ("Bogus number of playback voices %d, setting to 1\n",
1658 1659 1660 1661 1662
               s->nb_hw_voices_out);
        s->nb_hw_voices_out = 1;
    }

    if (s->nb_hw_voices_in <= 0) {
B
bellard 已提交
1663
        dolog ("Bogus number of capture voices %d, setting to 0\n",
1664
               s->nb_hw_voices_in);
B
bellard 已提交
1665
        s->nb_hw_voices_in = 0;
1666
    }
B
bellard 已提交
1667

1668 1669 1670 1671
    {
        int def;
        drvname = audio_get_conf_str ("QEMU_AUDIO_DRV", NULL, &def);
    }
B
bellard 已提交
1672 1673 1674

    if (drvname) {
        int found = 0;
1675

B
bellard 已提交
1676 1677
        for (i = 0; i < sizeof (drvtab) / sizeof (drvtab[0]); i++) {
            if (!strcmp (drvname, drvtab[i]->name)) {
B
bellard 已提交
1678
                done = !audio_driver_init (s, drvtab[i]);
B
bellard 已提交
1679 1680 1681 1682
                found = 1;
                break;
            }
        }
1683

B
bellard 已提交
1684 1685
        if (!found) {
            dolog ("Unknown audio driver `%s'\n", drvname);
1686
            dolog ("Run with -audio-help to list available drivers\n");
B
bellard 已提交
1687 1688 1689 1690 1691
        }
    }

    if (!done) {
        for (i = 0; !done && i < sizeof (drvtab) / sizeof (drvtab[0]); i++) {
1692
            if (drvtab[i]->can_be_default) {
B
bellard 已提交
1693
                done = !audio_driver_init (s, drvtab[i]);
1694
            }
B
bellard 已提交
1695 1696 1697 1698
        }
    }

    if (!done) {
B
bellard 已提交
1699 1700 1701
        done = !audio_driver_init (s, &no_audio_driver);
        if (!done) {
            dolog ("Could not initialize audio subsystem\n");
1702 1703
        }
        else {
B
bellard 已提交
1704
            dolog ("warning: Using timer based audio emulation\n");
1705
        }
B
bellard 已提交
1706
    }
1707

B
bellard 已提交
1708
    if (done) {
B
bellard 已提交
1709 1710
        VMChangeStateEntry *e;

B
bellard 已提交
1711 1712 1713 1714 1715 1716 1717
        if (conf.period.hz <= 0) {
            if (conf.period.hz < 0) {
                dolog ("warning: Timer period is negative - %d "
                       "treating as zero\n",
                       conf.period.hz);
            }
            conf.period.ticks = 1;
1718
        }
B
bellard 已提交
1719 1720 1721 1722
        else {
            conf.period.ticks = ticks_per_sec / conf.period.hz;
        }

B
bellard 已提交
1723 1724 1725 1726 1727
        e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
        if (!e) {
            dolog ("warning: Could not register change state handler\n"
                   "(Audio can continue looping even after stopping the VM)\n");
        }
1728 1729
    }
    else {
B
bellard 已提交
1730 1731
        qemu_del_timer (s->ts);
        return NULL;
1732 1733
    }

B
bellard 已提交
1734 1735 1736 1737
    LIST_INIT (&s->card_head);
    register_savevm ("audio", 0, 1, audio_save, audio_load, s);
    qemu_mod_timer (s->ts, qemu_get_clock (vm_clock) + conf.period.ticks);
    return s;
B
bellard 已提交
1738
}
1739

B
bellard 已提交
1740
CaptureVoiceOut *AUD_add_capture (
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
    AudioState *s,
    audsettings_t *as,
    struct audio_capture_ops *ops,
    void *cb_opaque
    )
{
    CaptureVoiceOut *cap;
    struct capture_callback *cb;

    if (!s) {
        /* XXX suppress */
        s = &glob_audio_state;
    }

B
bellard 已提交
1755
    if (audio_validate_settings (as)) {
1756 1757
        dolog ("Invalid settings were passed when trying to add capture\n");
        audio_print_settings (as);
B
bellard 已提交
1758
        goto err0;
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
    }

    cb = audio_calloc (AUDIO_FUNC, 1, sizeof (*cb));
    if (!cb) {
        dolog ("Could not allocate capture callback information, size %zu\n",
               sizeof (*cb));
        goto err0;
    }
    cb->ops = *ops;
    cb->opaque = cb_opaque;

B
bellard 已提交
1770
    cap = audio_pcm_capture_find_specific (s, as);
1771 1772
    if (cap) {
        LIST_INSERT_HEAD (&cap->cb_head, cb, entries);
B
bellard 已提交
1773
        return cap;
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
    }
    else {
        HWVoiceOut *hw;
        CaptureVoiceOut *cap;

        cap = audio_calloc (AUDIO_FUNC, 1, sizeof (*cap));
        if (!cap) {
            dolog ("Could not allocate capture voice, size %zu\n",
                   sizeof (*cap));
            goto err1;
        }

        hw = &cap->hw;
        LIST_INIT (&hw->sw_head);
        LIST_INIT (&cap->cb_head);

        /* XXX find a more elegant way */
        hw->samples = 4096 * 4;
        hw->mix_buf = audio_calloc (AUDIO_FUNC, hw->samples,
                                    sizeof (st_sample_t));
        if (!hw->mix_buf) {
            dolog ("Could not allocate capture mix buffer (%d samples)\n",
                   hw->samples);
            goto err2;
        }

B
bellard 已提交
1800
        audio_pcm_init_info (&hw->info, as);
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812

        cap->buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);
        if (!cap->buf) {
            dolog ("Could not allocate capture buffer "
                   "(%d samples, each %d bytes)\n",
                   hw->samples, 1 << hw->info.shift);
            goto err3;
        }

        hw->clip = mixeng_clip
            [hw->info.nchannels == 2]
            [hw->info.sign]
B
bellard 已提交
1813
            [hw->info.swap_endianness]
1814 1815 1816 1817 1818 1819 1820 1821 1822
            [hw->info.bits == 16];

        LIST_INSERT_HEAD (&s->cap_head, cap, entries);
        LIST_INSERT_HEAD (&cap->cb_head, cb, entries);

        hw = NULL;
        while ((hw = audio_pcm_hw_find_any_out (s, hw))) {
            audio_attach_capture (s, hw);
        }
B
bellard 已提交
1823
        return cap;
1824 1825 1826 1827 1828 1829 1830 1831

    err3:
        qemu_free (cap->hw.mix_buf);
    err2:
        qemu_free (cap);
    err1:
        qemu_free (cb);
    err0:
B
bellard 已提交
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
        return NULL;
    }
}

void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
{
    struct capture_callback *cb;

    for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
        if (cb->opaque == cb_opaque) {
            cb->ops.destroy (cb_opaque);
            LIST_REMOVE (cb, entries);
            qemu_free (cb);

            if (!cap->cb_head.lh_first) {
                SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
B
bellard 已提交
1848

B
bellard 已提交
1849
                while (sw) {
B
bellard 已提交
1850
                    SWVoiceCap *sc = (SWVoiceCap *) sw;
B
bellard 已提交
1851 1852 1853
#ifdef DEBUG_CAPTURE
                    dolog ("freeing %s\n", sw->name);
#endif
B
bellard 已提交
1854

B
bellard 已提交
1855 1856 1857 1858 1859 1860
                    sw1 = sw->entries.le_next;
                    if (sw->rate) {
                        st_rate_stop (sw->rate);
                        sw->rate = NULL;
                    }
                    LIST_REMOVE (sw, entries);
B
bellard 已提交
1861 1862
                    LIST_REMOVE (sc, entries);
                    qemu_free (sc);
B
bellard 已提交
1863 1864 1865 1866 1867 1868 1869
                    sw = sw1;
                }
                LIST_REMOVE (cap, entries);
                qemu_free (cap);
            }
            return;
        }
1870 1871
    }
}