qemu/audio/audio.c
<<
>>
Prefs
   1/*
   2 * QEMU Audio subsystem
   3 *
   4 * Copyright (c) 2003-2005 Vassili Karpov (malc)
   5 *
   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 */
  24#include "qemu/osdep.h"
  25#include "hw/hw.h"
  26#include "audio.h"
  27#include "monitor/monitor.h"
  28#include "qemu/timer.h"
  29#include "qapi/error.h"
  30#include "qapi/qobject-input-visitor.h"
  31#include "qapi/qapi-visit-audio.h"
  32#include "sysemu/sysemu.h"
  33#include "qemu/cutils.h"
  34#include "sysemu/replay.h"
  35#include "trace.h"
  36
  37#define AUDIO_CAP "audio"
  38#include "audio_int.h"
  39
  40/* #define DEBUG_LIVE */
  41/* #define DEBUG_OUT */
  42/* #define DEBUG_CAPTURE */
  43/* #define DEBUG_POLL */
  44
  45#define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
  46
  47
  48/* Order of CONFIG_AUDIO_DRIVERS is import.
  49   The 1st one is the one used by default, that is the reason
  50    that we generate the list.
  51*/
  52const char *audio_prio_list[] = {
  53    "spice",
  54    CONFIG_AUDIO_DRIVERS
  55    "none",
  56    "wav",
  57    NULL
  58};
  59
  60static QLIST_HEAD(, audio_driver) audio_drivers;
  61static AudiodevListHead audiodevs = QSIMPLEQ_HEAD_INITIALIZER(audiodevs);
  62
  63void audio_driver_register(audio_driver *drv)
  64{
  65    QLIST_INSERT_HEAD(&audio_drivers, drv, next);
  66}
  67
  68audio_driver *audio_driver_lookup(const char *name)
  69{
  70    struct audio_driver *d;
  71
  72    QLIST_FOREACH(d, &audio_drivers, next) {
  73        if (strcmp(name, d->name) == 0) {
  74            return d;
  75        }
  76    }
  77
  78    audio_module_load_one(name);
  79    QLIST_FOREACH(d, &audio_drivers, next) {
  80        if (strcmp(name, d->name) == 0) {
  81            return d;
  82        }
  83    }
  84
  85    return NULL;
  86}
  87
  88static AudioState glob_audio_state;
  89
  90const struct mixeng_volume nominal_volume = {
  91    .mute = 0,
  92#ifdef FLOAT_MIXENG
  93    .r = 1.0,
  94    .l = 1.0,
  95#else
  96    .r = 1ULL << 32,
  97    .l = 1ULL << 32,
  98#endif
  99};
 100
 101#ifdef AUDIO_IS_FLAWLESS_AND_NO_CHECKS_ARE_REQURIED
 102#error No its not
 103#else
 104int audio_bug (const char *funcname, int cond)
 105{
 106    if (cond) {
 107        static int shown;
 108
 109        AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
 110        if (!shown) {
 111            shown = 1;
 112            AUD_log (NULL, "Save all your work and restart without audio\n");
 113            AUD_log (NULL, "I am sorry\n");
 114        }
 115        AUD_log (NULL, "Context:\n");
 116
 117#if defined AUDIO_BREAKPOINT_ON_BUG
 118#  if defined HOST_I386
 119#    if defined __GNUC__
 120        __asm__ ("int3");
 121#    elif defined _MSC_VER
 122        _asm _emit 0xcc;
 123#    else
 124        abort ();
 125#    endif
 126#  else
 127        abort ();
 128#  endif
 129#endif
 130    }
 131
 132    return cond;
 133}
 134#endif
 135
 136static inline int audio_bits_to_index (int bits)
 137{
 138    switch (bits) {
 139    case 8:
 140        return 0;
 141
 142    case 16:
 143        return 1;
 144
 145    case 32:
 146        return 2;
 147
 148    default:
 149        audio_bug ("bits_to_index", 1);
 150        AUD_log (NULL, "invalid bits %d\n", bits);
 151        return 0;
 152    }
 153}
 154
 155void *audio_calloc (const char *funcname, int nmemb, size_t size)
 156{
 157    int cond;
 158    size_t len;
 159
 160    len = nmemb * size;
 161    cond = !nmemb || !size;
 162    cond |= nmemb < 0;
 163    cond |= len < size;
 164
 165    if (audio_bug ("audio_calloc", cond)) {
 166        AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
 167                 funcname);
 168        AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
 169        return NULL;
 170    }
 171
 172    return g_malloc0 (len);
 173}
 174
 175void AUD_vlog (const char *cap, const char *fmt, va_list ap)
 176{
 177    if (cap) {
 178        fprintf(stderr, "%s: ", cap);
 179    }
 180
 181    vfprintf(stderr, fmt, ap);
 182}
 183
 184void AUD_log (const char *cap, const char *fmt, ...)
 185{
 186    va_list ap;
 187
 188    va_start (ap, fmt);
 189    AUD_vlog (cap, fmt, ap);
 190    va_end (ap);
 191}
 192
 193static void audio_print_settings (struct audsettings *as)
 194{
 195    dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
 196
 197    switch (as->fmt) {
 198    case AUDIO_FORMAT_S8:
 199        AUD_log (NULL, "S8");
 200        break;
 201    case AUDIO_FORMAT_U8:
 202        AUD_log (NULL, "U8");
 203        break;
 204    case AUDIO_FORMAT_S16:
 205        AUD_log (NULL, "S16");
 206        break;
 207    case AUDIO_FORMAT_U16:
 208        AUD_log (NULL, "U16");
 209        break;
 210    case AUDIO_FORMAT_S32:
 211        AUD_log (NULL, "S32");
 212        break;
 213    case AUDIO_FORMAT_U32:
 214        AUD_log (NULL, "U32");
 215        break;
 216    default:
 217        AUD_log (NULL, "invalid(%d)", as->fmt);
 218        break;
 219    }
 220
 221    AUD_log (NULL, " endianness=");
 222    switch (as->endianness) {
 223    case 0:
 224        AUD_log (NULL, "little");
 225        break;
 226    case 1:
 227        AUD_log (NULL, "big");
 228        break;
 229    default:
 230        AUD_log (NULL, "invalid");
 231        break;
 232    }
 233    AUD_log (NULL, "\n");
 234}
 235
 236static int audio_validate_settings (struct audsettings *as)
 237{
 238    int invalid;
 239
 240    invalid = as->nchannels != 1 && as->nchannels != 2;
 241    invalid |= as->endianness != 0 && as->endianness != 1;
 242
 243    switch (as->fmt) {
 244    case AUDIO_FORMAT_S8:
 245    case AUDIO_FORMAT_U8:
 246    case AUDIO_FORMAT_S16:
 247    case AUDIO_FORMAT_U16:
 248    case AUDIO_FORMAT_S32:
 249    case AUDIO_FORMAT_U32:
 250        break;
 251    default:
 252        invalid = 1;
 253        break;
 254    }
 255
 256    invalid |= as->freq <= 0;
 257    return invalid ? -1 : 0;
 258}
 259
 260static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
 261{
 262    int bits = 8, sign = 0;
 263
 264    switch (as->fmt) {
 265    case AUDIO_FORMAT_S8:
 266        sign = 1;
 267        /* fall through */
 268    case AUDIO_FORMAT_U8:
 269        break;
 270
 271    case AUDIO_FORMAT_S16:
 272        sign = 1;
 273        /* fall through */
 274    case AUDIO_FORMAT_U16:
 275        bits = 16;
 276        break;
 277
 278    case AUDIO_FORMAT_S32:
 279        sign = 1;
 280        /* fall through */
 281    case AUDIO_FORMAT_U32:
 282        bits = 32;
 283        break;
 284
 285    default:
 286        abort();
 287    }
 288    return info->freq == as->freq
 289        && info->nchannels == as->nchannels
 290        && info->sign == sign
 291        && info->bits == bits
 292        && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
 293}
 294
 295void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
 296{
 297    int bits = 8, sign = 0, shift = 0;
 298
 299    switch (as->fmt) {
 300    case AUDIO_FORMAT_S8:
 301        sign = 1;
 302    case AUDIO_FORMAT_U8:
 303        break;
 304
 305    case AUDIO_FORMAT_S16:
 306        sign = 1;
 307    case AUDIO_FORMAT_U16:
 308        bits = 16;
 309        shift = 1;
 310        break;
 311
 312    case AUDIO_FORMAT_S32:
 313        sign = 1;
 314    case AUDIO_FORMAT_U32:
 315        bits = 32;
 316        shift = 2;
 317        break;
 318
 319    default:
 320        abort();
 321    }
 322
 323    info->freq = as->freq;
 324    info->bits = bits;
 325    info->sign = sign;
 326    info->nchannels = as->nchannels;
 327    info->shift = (as->nchannels == 2) + shift;
 328    info->align = (1 << info->shift) - 1;
 329    info->bytes_per_second = info->freq << info->shift;
 330    info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
 331}
 332
 333void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
 334{
 335    if (!len) {
 336        return;
 337    }
 338
 339    if (info->sign) {
 340        memset (buf, 0x00, len << info->shift);
 341    }
 342    else {
 343        switch (info->bits) {
 344        case 8:
 345            memset (buf, 0x80, len << info->shift);
 346            break;
 347
 348        case 16:
 349            {
 350                int i;
 351                uint16_t *p = buf;
 352                int shift = info->nchannels - 1;
 353                short s = INT16_MAX;
 354
 355                if (info->swap_endianness) {
 356                    s = bswap16 (s);
 357                }
 358
 359                for (i = 0; i < len << shift; i++) {
 360                    p[i] = s;
 361                }
 362            }
 363            break;
 364
 365        case 32:
 366            {
 367                int i;
 368                uint32_t *p = buf;
 369                int shift = info->nchannels - 1;
 370                int32_t s = INT32_MAX;
 371
 372                if (info->swap_endianness) {
 373                    s = bswap32 (s);
 374                }
 375
 376                for (i = 0; i < len << shift; i++) {
 377                    p[i] = s;
 378                }
 379            }
 380            break;
 381
 382        default:
 383            AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
 384                     info->bits);
 385            break;
 386        }
 387    }
 388}
 389
 390/*
 391 * Capture
 392 */
 393static void noop_conv (struct st_sample *dst, const void *src, int samples)
 394{
 395    (void) src;
 396    (void) dst;
 397    (void) samples;
 398}
 399
 400static CaptureVoiceOut *audio_pcm_capture_find_specific (
 401    struct audsettings *as
 402    )
 403{
 404    CaptureVoiceOut *cap;
 405    AudioState *s = &glob_audio_state;
 406
 407    for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
 408        if (audio_pcm_info_eq (&cap->hw.info, as)) {
 409            return cap;
 410        }
 411    }
 412    return NULL;
 413}
 414
 415static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
 416{
 417    struct capture_callback *cb;
 418
 419#ifdef DEBUG_CAPTURE
 420    dolog ("notification %d sent\n", cmd);
 421#endif
 422    for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
 423        cb->ops.notify (cb->opaque, cmd);
 424    }
 425}
 426
 427static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
 428{
 429    if (cap->hw.enabled != enabled) {
 430        audcnotification_e cmd;
 431        cap->hw.enabled = enabled;
 432        cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
 433        audio_notify_capture (cap, cmd);
 434    }
 435}
 436
 437static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
 438{
 439    HWVoiceOut *hw = &cap->hw;
 440    SWVoiceOut *sw;
 441    int enabled = 0;
 442
 443    for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
 444        if (sw->active) {
 445            enabled = 1;
 446            break;
 447        }
 448    }
 449    audio_capture_maybe_changed (cap, enabled);
 450}
 451
 452static void audio_detach_capture (HWVoiceOut *hw)
 453{
 454    SWVoiceCap *sc = hw->cap_head.lh_first;
 455
 456    while (sc) {
 457        SWVoiceCap *sc1 = sc->entries.le_next;
 458        SWVoiceOut *sw = &sc->sw;
 459        CaptureVoiceOut *cap = sc->cap;
 460        int was_active = sw->active;
 461
 462        if (sw->rate) {
 463            st_rate_stop (sw->rate);
 464            sw->rate = NULL;
 465        }
 466
 467        QLIST_REMOVE (sw, entries);
 468        QLIST_REMOVE (sc, entries);
 469        g_free (sc);
 470        if (was_active) {
 471            /* We have removed soft voice from the capture:
 472               this might have changed the overall status of the capture
 473               since this might have been the only active voice */
 474            audio_recalc_and_notify_capture (cap);
 475        }
 476        sc = sc1;
 477    }
 478}
 479
 480static int audio_attach_capture (HWVoiceOut *hw)
 481{
 482    AudioState *s = &glob_audio_state;
 483    CaptureVoiceOut *cap;
 484
 485    audio_detach_capture (hw);
 486    for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
 487        SWVoiceCap *sc;
 488        SWVoiceOut *sw;
 489        HWVoiceOut *hw_cap = &cap->hw;
 490
 491        sc = g_malloc0(sizeof(*sc));
 492
 493        sc->cap = cap;
 494        sw = &sc->sw;
 495        sw->hw = hw_cap;
 496        sw->info = hw->info;
 497        sw->empty = 1;
 498        sw->active = hw->enabled;
 499        sw->conv = noop_conv;
 500        sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
 501        sw->vol = nominal_volume;
 502        sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
 503        if (!sw->rate) {
 504            dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
 505            g_free (sw);
 506            return -1;
 507        }
 508        QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
 509        QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
 510#ifdef DEBUG_CAPTURE
 511        sw->name = g_strdup_printf ("for %p %d,%d,%d",
 512                                    hw, sw->info.freq, sw->info.bits,
 513                                    sw->info.nchannels);
 514        dolog ("Added %s active = %d\n", sw->name, sw->active);
 515#endif
 516        if (sw->active) {
 517            audio_capture_maybe_changed (cap, 1);
 518        }
 519    }
 520    return 0;
 521}
 522
 523/*
 524 * Hard voice (capture)
 525 */
 526static int audio_pcm_hw_find_min_in (HWVoiceIn *hw)
 527{
 528    SWVoiceIn *sw;
 529    int m = hw->total_samples_captured;
 530
 531    for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
 532        if (sw->active) {
 533            m = audio_MIN (m, sw->total_hw_samples_acquired);
 534        }
 535    }
 536    return m;
 537}
 538
 539int audio_pcm_hw_get_live_in (HWVoiceIn *hw)
 540{
 541    int live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
 542    if (audio_bug(__func__, live < 0 || live > hw->samples)) {
 543        dolog ("live=%d hw->samples=%d\n", live, hw->samples);
 544        return 0;
 545    }
 546    return live;
 547}
 548
 549int audio_pcm_hw_clip_out (HWVoiceOut *hw, void *pcm_buf,
 550                           int live, int pending)
 551{
 552    int left = hw->samples - pending;
 553    int len = audio_MIN (left, live);
 554    int clipped = 0;
 555
 556    while (len) {
 557        struct st_sample *src = hw->mix_buf + hw->rpos;
 558        uint8_t *dst = advance (pcm_buf, hw->rpos << hw->info.shift);
 559        int samples_till_end_of_buf = hw->samples - hw->rpos;
 560        int samples_to_clip = audio_MIN (len, samples_till_end_of_buf);
 561
 562        hw->clip (dst, src, samples_to_clip);
 563
 564        hw->rpos = (hw->rpos + samples_to_clip) % hw->samples;
 565        len -= samples_to_clip;
 566        clipped += samples_to_clip;
 567    }
 568    return clipped;
 569}
 570
 571/*
 572 * Soft voice (capture)
 573 */
 574static int audio_pcm_sw_get_rpos_in (SWVoiceIn *sw)
 575{
 576    HWVoiceIn *hw = sw->hw;
 577    int live = hw->total_samples_captured - sw->total_hw_samples_acquired;
 578    int rpos;
 579
 580    if (audio_bug(__func__, live < 0 || live > hw->samples)) {
 581        dolog ("live=%d hw->samples=%d\n", live, hw->samples);
 582        return 0;
 583    }
 584
 585    rpos = hw->wpos - live;
 586    if (rpos >= 0) {
 587        return rpos;
 588    }
 589    else {
 590        return hw->samples + rpos;
 591    }
 592}
 593
 594int audio_pcm_sw_read (SWVoiceIn *sw, void *buf, int size)
 595{
 596    HWVoiceIn *hw = sw->hw;
 597    int samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
 598    struct st_sample *src, *dst = sw->buf;
 599
 600    rpos = audio_pcm_sw_get_rpos_in (sw) % hw->samples;
 601
 602    live = hw->total_samples_captured - sw->total_hw_samples_acquired;
 603    if (audio_bug(__func__, live < 0 || live > hw->samples)) {
 604        dolog ("live_in=%d hw->samples=%d\n", live, hw->samples);
 605        return 0;
 606    }
 607
 608    samples = size >> sw->info.shift;
 609    if (!live) {
 610        return 0;
 611    }
 612
 613    swlim = (live * sw->ratio) >> 32;
 614    swlim = audio_MIN (swlim, samples);
 615
 616    while (swlim) {
 617        src = hw->conv_buf + rpos;
 618        isamp = hw->wpos - rpos;
 619        /* XXX: <= ? */
 620        if (isamp <= 0) {
 621            isamp = hw->samples - rpos;
 622        }
 623
 624        if (!isamp) {
 625            break;
 626        }
 627        osamp = swlim;
 628
 629        if (audio_bug(__func__, osamp < 0)) {
 630            dolog ("osamp=%d\n", osamp);
 631            return 0;
 632        }
 633
 634        st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
 635        swlim -= osamp;
 636        rpos = (rpos + isamp) % hw->samples;
 637        dst += osamp;
 638        ret += osamp;
 639        total += isamp;
 640    }
 641
 642    if (!(hw->ctl_caps & VOICE_VOLUME_CAP)) {
 643        mixeng_volume (sw->buf, ret, &sw->vol);
 644    }
 645
 646    sw->clip (buf, sw->buf, ret);
 647    sw->total_hw_samples_acquired += total;
 648    return ret << sw->info.shift;
 649}
 650
 651/*
 652 * Hard voice (playback)
 653 */
 654static int audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
 655{
 656    SWVoiceOut *sw;
 657    int m = INT_MAX;
 658    int nb_live = 0;
 659
 660    for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
 661        if (sw->active || !sw->empty) {
 662            m = audio_MIN (m, sw->total_hw_samples_mixed);
 663            nb_live += 1;
 664        }
 665    }
 666
 667    *nb_livep = nb_live;
 668    return m;
 669}
 670
 671static int audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
 672{
 673    int smin;
 674    int nb_live1;
 675
 676    smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
 677    if (nb_live) {
 678        *nb_live = nb_live1;
 679    }
 680
 681    if (nb_live1) {
 682        int live = smin;
 683
 684        if (audio_bug(__func__, live < 0 || live > hw->samples)) {
 685            dolog ("live=%d hw->samples=%d\n", live, hw->samples);
 686            return 0;
 687        }
 688        return live;
 689    }
 690    return 0;
 691}
 692
 693/*
 694 * Soft voice (playback)
 695 */
 696int audio_pcm_sw_write (SWVoiceOut *sw, void *buf, int size)
 697{
 698    int hwsamples, samples, isamp, osamp, wpos, live, dead, left, swlim, blck;
 699    int ret = 0, pos = 0, total = 0;
 700
 701    if (!sw) {
 702        return size;
 703    }
 704
 705    hwsamples = sw->hw->samples;
 706
 707    live = sw->total_hw_samples_mixed;
 708    if (audio_bug(__func__, live < 0 || live > hwsamples)) {
 709        dolog ("live=%d hw->samples=%d\n", live, hwsamples);
 710        return 0;
 711    }
 712
 713    if (live == hwsamples) {
 714#ifdef DEBUG_OUT
 715        dolog ("%s is full %d\n", sw->name, live);
 716#endif
 717        return 0;
 718    }
 719
 720    wpos = (sw->hw->rpos + live) % hwsamples;
 721    samples = size >> sw->info.shift;
 722
 723    dead = hwsamples - live;
 724    swlim = ((int64_t) dead << 32) / sw->ratio;
 725    swlim = audio_MIN (swlim, samples);
 726    if (swlim) {
 727        sw->conv (sw->buf, buf, swlim);
 728
 729        if (!(sw->hw->ctl_caps & VOICE_VOLUME_CAP)) {
 730            mixeng_volume (sw->buf, swlim, &sw->vol);
 731        }
 732    }
 733
 734    while (swlim) {
 735        dead = hwsamples - live;
 736        left = hwsamples - wpos;
 737        blck = audio_MIN (dead, left);
 738        if (!blck) {
 739            break;
 740        }
 741        isamp = swlim;
 742        osamp = blck;
 743        st_rate_flow_mix (
 744            sw->rate,
 745            sw->buf + pos,
 746            sw->hw->mix_buf + wpos,
 747            &isamp,
 748            &osamp
 749            );
 750        ret += isamp;
 751        swlim -= isamp;
 752        pos += isamp;
 753        live += osamp;
 754        wpos = (wpos + osamp) % hwsamples;
 755        total += osamp;
 756    }
 757
 758    sw->total_hw_samples_mixed += total;
 759    sw->empty = sw->total_hw_samples_mixed == 0;
 760
 761#ifdef DEBUG_OUT
 762    dolog (
 763        "%s: write size %d ret %d total sw %d\n",
 764        SW_NAME (sw),
 765        size >> sw->info.shift,
 766        ret,
 767        sw->total_hw_samples_mixed
 768        );
 769#endif
 770
 771    return ret << sw->info.shift;
 772}
 773
 774#ifdef DEBUG_AUDIO
 775static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
 776{
 777    dolog ("%s: bits %d, sign %d, freq %d, nchan %d\n",
 778           cap, info->bits, info->sign, info->freq, info->nchannels);
 779}
 780#endif
 781
 782#define DAC
 783#include "audio_template.h"
 784#undef DAC
 785#include "audio_template.h"
 786
 787/*
 788 * Timer
 789 */
 790
 791static bool audio_timer_running;
 792static uint64_t audio_timer_last;
 793
 794static int audio_is_timer_needed (void)
 795{
 796    HWVoiceIn *hwi = NULL;
 797    HWVoiceOut *hwo = NULL;
 798
 799    while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
 800        if (!hwo->poll_mode) return 1;
 801    }
 802    while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
 803        if (!hwi->poll_mode) return 1;
 804    }
 805    return 0;
 806}
 807
 808static void audio_reset_timer (AudioState *s)
 809{
 810    if (audio_is_timer_needed ()) {
 811        timer_mod_anticipate_ns(s->ts,
 812            qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
 813        if (!audio_timer_running) {
 814            audio_timer_running = true;
 815            audio_timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
 816            trace_audio_timer_start(s->period_ticks / SCALE_MS);
 817        }
 818    } else {
 819        timer_del(s->ts);
 820        if (audio_timer_running) {
 821            audio_timer_running = false;
 822            trace_audio_timer_stop();
 823        }
 824    }
 825}
 826
 827static void audio_timer (void *opaque)
 828{
 829    int64_t now, diff;
 830    AudioState *s = opaque;
 831
 832    now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
 833    diff = now - audio_timer_last;
 834    if (diff > s->period_ticks * 3 / 2) {
 835        trace_audio_timer_delayed(diff / SCALE_MS);
 836    }
 837    audio_timer_last = now;
 838
 839    audio_run("timer");
 840    audio_reset_timer(s);
 841}
 842
 843/*
 844 * Public API
 845 */
 846int AUD_write (SWVoiceOut *sw, void *buf, int size)
 847{
 848    if (!sw) {
 849        /* XXX: Consider options */
 850        return size;
 851    }
 852
 853    if (!sw->hw->enabled) {
 854        dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
 855        return 0;
 856    }
 857
 858    return sw->hw->pcm_ops->write(sw, buf, size);
 859}
 860
 861int AUD_read (SWVoiceIn *sw, void *buf, int size)
 862{
 863    if (!sw) {
 864        /* XXX: Consider options */
 865        return size;
 866    }
 867
 868    if (!sw->hw->enabled) {
 869        dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
 870        return 0;
 871    }
 872
 873    return sw->hw->pcm_ops->read(sw, buf, size);
 874}
 875
 876int AUD_get_buffer_size_out (SWVoiceOut *sw)
 877{
 878    return sw->hw->samples << sw->hw->info.shift;
 879}
 880
 881void AUD_set_active_out (SWVoiceOut *sw, int on)
 882{
 883    HWVoiceOut *hw;
 884
 885    if (!sw) {
 886        return;
 887    }
 888
 889    hw = sw->hw;
 890    if (sw->active != on) {
 891        AudioState *s = &glob_audio_state;
 892        SWVoiceOut *temp_sw;
 893        SWVoiceCap *sc;
 894
 895        if (on) {
 896            hw->pending_disable = 0;
 897            if (!hw->enabled) {
 898                hw->enabled = 1;
 899                if (s->vm_running) {
 900                    hw->pcm_ops->ctl_out(hw, VOICE_ENABLE);
 901                    audio_reset_timer (s);
 902                }
 903            }
 904        }
 905        else {
 906            if (hw->enabled) {
 907                int nb_active = 0;
 908
 909                for (temp_sw = hw->sw_head.lh_first; temp_sw;
 910                     temp_sw = temp_sw->entries.le_next) {
 911                    nb_active += temp_sw->active != 0;
 912                }
 913
 914                hw->pending_disable = nb_active == 1;
 915            }
 916        }
 917
 918        for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
 919            sc->sw.active = hw->enabled;
 920            if (hw->enabled) {
 921                audio_capture_maybe_changed (sc->cap, 1);
 922            }
 923        }
 924        sw->active = on;
 925    }
 926}
 927
 928void AUD_set_active_in (SWVoiceIn *sw, int on)
 929{
 930    HWVoiceIn *hw;
 931
 932    if (!sw) {
 933        return;
 934    }
 935
 936    hw = sw->hw;
 937    if (sw->active != on) {
 938        AudioState *s = &glob_audio_state;
 939        SWVoiceIn *temp_sw;
 940
 941        if (on) {
 942            if (!hw->enabled) {
 943                hw->enabled = 1;
 944                if (s->vm_running) {
 945                    hw->pcm_ops->ctl_in(hw, VOICE_ENABLE);
 946                    audio_reset_timer (s);
 947                }
 948            }
 949            sw->total_hw_samples_acquired = hw->total_samples_captured;
 950        }
 951        else {
 952            if (hw->enabled) {
 953                int nb_active = 0;
 954
 955                for (temp_sw = hw->sw_head.lh_first; temp_sw;
 956                     temp_sw = temp_sw->entries.le_next) {
 957                    nb_active += temp_sw->active != 0;
 958                }
 959
 960                if (nb_active == 1) {
 961                    hw->enabled = 0;
 962                    hw->pcm_ops->ctl_in (hw, VOICE_DISABLE);
 963                }
 964            }
 965        }
 966        sw->active = on;
 967    }
 968}
 969
 970static int audio_get_avail (SWVoiceIn *sw)
 971{
 972    int live;
 973
 974    if (!sw) {
 975        return 0;
 976    }
 977
 978    live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
 979    if (audio_bug(__func__, live < 0 || live > sw->hw->samples)) {
 980        dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples);
 981        return 0;
 982    }
 983
 984    ldebug (
 985        "%s: get_avail live %d ret %" PRId64 "\n",
 986        SW_NAME (sw),
 987        live, (((int64_t) live << 32) / sw->ratio) << sw->info.shift
 988        );
 989
 990    return (((int64_t) live << 32) / sw->ratio) << sw->info.shift;
 991}
 992
 993static int audio_get_free (SWVoiceOut *sw)
 994{
 995    int live, dead;
 996
 997    if (!sw) {
 998        return 0;
 999    }
1000
1001    live = sw->total_hw_samples_mixed;
1002
1003    if (audio_bug(__func__, live < 0 || live > sw->hw->samples)) {
1004        dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples);
1005        return 0;
1006    }
1007
1008    dead = sw->hw->samples - live;
1009
1010#ifdef DEBUG_OUT
1011    dolog ("%s: get_free live %d dead %d ret %" PRId64 "\n",
1012           SW_NAME (sw),
1013           live, dead, (((int64_t) dead << 32) / sw->ratio) << sw->info.shift);
1014#endif
1015
1016    return (((int64_t) dead << 32) / sw->ratio) << sw->info.shift;
1017}
1018
1019static void audio_capture_mix_and_clear (HWVoiceOut *hw, int rpos, int samples)
1020{
1021    int n;
1022
1023    if (hw->enabled) {
1024        SWVoiceCap *sc;
1025
1026        for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1027            SWVoiceOut *sw = &sc->sw;
1028            int rpos2 = rpos;
1029
1030            n = samples;
1031            while (n) {
1032                int till_end_of_hw = hw->samples - rpos2;
1033                int to_write = audio_MIN (till_end_of_hw, n);
1034                int bytes = to_write << hw->info.shift;
1035                int written;
1036
1037                sw->buf = hw->mix_buf + rpos2;
1038                written = audio_pcm_sw_write (sw, NULL, bytes);
1039                if (written - bytes) {
1040                    dolog ("Could not mix %d bytes into a capture "
1041                           "buffer, mixed %d\n",
1042                           bytes, written);
1043                    break;
1044                }
1045                n -= to_write;
1046                rpos2 = (rpos2 + to_write) % hw->samples;
1047            }
1048        }
1049    }
1050
1051    n = audio_MIN (samples, hw->samples - rpos);
1052    mixeng_clear (hw->mix_buf + rpos, n);
1053    mixeng_clear (hw->mix_buf, samples - n);
1054}
1055
1056static void audio_run_out (AudioState *s)
1057{
1058    HWVoiceOut *hw = NULL;
1059    SWVoiceOut *sw;
1060
1061    while ((hw = audio_pcm_hw_find_any_enabled_out (hw))) {
1062        int played;
1063        int live, free, nb_live, cleanup_required, prev_rpos;
1064
1065        live = audio_pcm_hw_get_live_out (hw, &nb_live);
1066        if (!nb_live) {
1067            live = 0;
1068        }
1069
1070        if (audio_bug(__func__, live < 0 || live > hw->samples)) {
1071            dolog ("live=%d hw->samples=%d\n", live, hw->samples);
1072            continue;
1073        }
1074
1075        if (hw->pending_disable && !nb_live) {
1076            SWVoiceCap *sc;
1077#ifdef DEBUG_OUT
1078            dolog ("Disabling voice\n");
1079#endif
1080            hw->enabled = 0;
1081            hw->pending_disable = 0;
1082            hw->pcm_ops->ctl_out (hw, VOICE_DISABLE);
1083            for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1084                sc->sw.active = 0;
1085                audio_recalc_and_notify_capture (sc->cap);
1086            }
1087            continue;
1088        }
1089
1090        if (!live) {
1091            for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1092                if (sw->active) {
1093                    free = audio_get_free (sw);
1094                    if (free > 0) {
1095                        sw->callback.fn (sw->callback.opaque, free);
1096                    }
1097                }
1098            }
1099            continue;
1100        }
1101
1102        prev_rpos = hw->rpos;
1103        played = hw->pcm_ops->run_out (hw, live);
1104        replay_audio_out(&played);
1105        if (audio_bug(__func__, hw->rpos >= hw->samples)) {
1106            dolog ("hw->rpos=%d hw->samples=%d played=%d\n",
1107                   hw->rpos, hw->samples, played);
1108            hw->rpos = 0;
1109        }
1110
1111#ifdef DEBUG_OUT
1112        dolog ("played=%d\n", played);
1113#endif
1114
1115        if (played) {
1116            hw->ts_helper += played;
1117            audio_capture_mix_and_clear (hw, prev_rpos, played);
1118        }
1119
1120        cleanup_required = 0;
1121        for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1122            if (!sw->active && sw->empty) {
1123                continue;
1124            }
1125
1126            if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1127                dolog ("played=%d sw->total_hw_samples_mixed=%d\n",
1128                       played, sw->total_hw_samples_mixed);
1129                played = sw->total_hw_samples_mixed;
1130            }
1131
1132            sw->total_hw_samples_mixed -= played;
1133
1134            if (!sw->total_hw_samples_mixed) {
1135                sw->empty = 1;
1136                cleanup_required |= !sw->active && !sw->callback.fn;
1137            }
1138
1139            if (sw->active) {
1140                free = audio_get_free (sw);
1141                if (free > 0) {
1142                    sw->callback.fn (sw->callback.opaque, free);
1143                }
1144            }
1145        }
1146
1147        if (cleanup_required) {
1148            SWVoiceOut *sw1;
1149
1150            sw = hw->sw_head.lh_first;
1151            while (sw) {
1152                sw1 = sw->entries.le_next;
1153                if (!sw->active && !sw->callback.fn) {
1154                    audio_close_out (sw);
1155                }
1156                sw = sw1;
1157            }
1158        }
1159    }
1160}
1161
1162static void audio_run_in (AudioState *s)
1163{
1164    HWVoiceIn *hw = NULL;
1165
1166    while ((hw = audio_pcm_hw_find_any_enabled_in (hw))) {
1167        SWVoiceIn *sw;
1168        int captured = 0, min;
1169
1170        if (replay_mode != REPLAY_MODE_PLAY) {
1171            captured = hw->pcm_ops->run_in(hw);
1172        }
1173        replay_audio_in(&captured, hw->conv_buf, &hw->wpos, hw->samples);
1174
1175        min = audio_pcm_hw_find_min_in (hw);
1176        hw->total_samples_captured += captured - min;
1177        hw->ts_helper += captured;
1178
1179        for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1180            sw->total_hw_samples_acquired -= min;
1181
1182            if (sw->active) {
1183                int avail;
1184
1185                avail = audio_get_avail (sw);
1186                if (avail > 0) {
1187                    sw->callback.fn (sw->callback.opaque, avail);
1188                }
1189            }
1190        }
1191    }
1192}
1193
1194static void audio_run_capture (AudioState *s)
1195{
1196    CaptureVoiceOut *cap;
1197
1198    for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1199        int live, rpos, captured;
1200        HWVoiceOut *hw = &cap->hw;
1201        SWVoiceOut *sw;
1202
1203        captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1204        rpos = hw->rpos;
1205        while (live) {
1206            int left = hw->samples - rpos;
1207            int to_capture = audio_MIN (live, left);
1208            struct st_sample *src;
1209            struct capture_callback *cb;
1210
1211            src = hw->mix_buf + rpos;
1212            hw->clip (cap->buf, src, to_capture);
1213            mixeng_clear (src, to_capture);
1214
1215            for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1216                cb->ops.capture (cb->opaque, cap->buf,
1217                                 to_capture << hw->info.shift);
1218            }
1219            rpos = (rpos + to_capture) % hw->samples;
1220            live -= to_capture;
1221        }
1222        hw->rpos = rpos;
1223
1224        for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1225            if (!sw->active && sw->empty) {
1226                continue;
1227            }
1228
1229            if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1230                dolog ("captured=%d sw->total_hw_samples_mixed=%d\n",
1231                       captured, sw->total_hw_samples_mixed);
1232                captured = sw->total_hw_samples_mixed;
1233            }
1234
1235            sw->total_hw_samples_mixed -= captured;
1236            sw->empty = sw->total_hw_samples_mixed == 0;
1237        }
1238    }
1239}
1240
1241void audio_run (const char *msg)
1242{
1243    AudioState *s = &glob_audio_state;
1244
1245    audio_run_out (s);
1246    audio_run_in (s);
1247    audio_run_capture (s);
1248#ifdef DEBUG_POLL
1249    {
1250        static double prevtime;
1251        double currtime;
1252        struct timeval tv;
1253
1254        if (gettimeofday (&tv, NULL)) {
1255            perror ("audio_run: gettimeofday");
1256            return;
1257        }
1258
1259        currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1260        dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1261        prevtime = currtime;
1262    }
1263#endif
1264}
1265
1266static int audio_driver_init(AudioState *s, struct audio_driver *drv,
1267                             bool msg, Audiodev *dev)
1268{
1269    s->drv_opaque = drv->init(dev);
1270
1271    if (s->drv_opaque) {
1272        audio_init_nb_voices_out (drv);
1273        audio_init_nb_voices_in (drv);
1274        s->drv = drv;
1275        return 0;
1276    }
1277    else {
1278        if (msg) {
1279            dolog("Could not init `%s' audio driver\n", drv->name);
1280        }
1281        return -1;
1282    }
1283}
1284
1285static void audio_vm_change_state_handler (void *opaque, int running,
1286                                           RunState state)
1287{
1288    AudioState *s = opaque;
1289    HWVoiceOut *hwo = NULL;
1290    HWVoiceIn *hwi = NULL;
1291    int op = running ? VOICE_ENABLE : VOICE_DISABLE;
1292
1293    s->vm_running = running;
1294    while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
1295        hwo->pcm_ops->ctl_out(hwo, op);
1296    }
1297
1298    while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
1299        hwi->pcm_ops->ctl_in(hwi, op);
1300    }
1301    audio_reset_timer (s);
1302}
1303
1304static bool is_cleaning_up;
1305
1306bool audio_is_cleaning_up(void)
1307{
1308    return is_cleaning_up;
1309}
1310
1311void audio_cleanup(void)
1312{
1313    AudioState *s = &glob_audio_state;
1314    HWVoiceOut *hwo, *hwon;
1315    HWVoiceIn *hwi, *hwin;
1316
1317    is_cleaning_up = true;
1318    QLIST_FOREACH_SAFE(hwo, &glob_audio_state.hw_head_out, entries, hwon) {
1319        SWVoiceCap *sc;
1320
1321        if (hwo->enabled) {
1322            hwo->pcm_ops->ctl_out (hwo, VOICE_DISABLE);
1323        }
1324        hwo->pcm_ops->fini_out (hwo);
1325
1326        for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1327            CaptureVoiceOut *cap = sc->cap;
1328            struct capture_callback *cb;
1329
1330            for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1331                cb->ops.destroy (cb->opaque);
1332            }
1333        }
1334        QLIST_REMOVE(hwo, entries);
1335    }
1336
1337    QLIST_FOREACH_SAFE(hwi, &glob_audio_state.hw_head_in, entries, hwin) {
1338        if (hwi->enabled) {
1339            hwi->pcm_ops->ctl_in (hwi, VOICE_DISABLE);
1340        }
1341        hwi->pcm_ops->fini_in (hwi);
1342        QLIST_REMOVE(hwi, entries);
1343    }
1344
1345    if (s->drv) {
1346        s->drv->fini (s->drv_opaque);
1347        s->drv = NULL;
1348    }
1349
1350    if (s->dev) {
1351        qapi_free_Audiodev(s->dev);
1352        s->dev = NULL;
1353    }
1354}
1355
1356static const VMStateDescription vmstate_audio = {
1357    .name = "audio",
1358    .version_id = 1,
1359    .minimum_version_id = 1,
1360    .fields = (VMStateField[]) {
1361        VMSTATE_END_OF_LIST()
1362    }
1363};
1364
1365static void audio_validate_opts(Audiodev *dev, Error **errp);
1366
1367static AudiodevListEntry *audiodev_find(
1368    AudiodevListHead *head, const char *drvname)
1369{
1370    AudiodevListEntry *e;
1371    QSIMPLEQ_FOREACH(e, head, next) {
1372        if (strcmp(AudiodevDriver_str(e->dev->driver), drvname) == 0) {
1373            return e;
1374        }
1375    }
1376
1377    return NULL;
1378}
1379
1380static int audio_init(Audiodev *dev)
1381{
1382    size_t i;
1383    int done = 0;
1384    const char *drvname = NULL;
1385    VMChangeStateEntry *e;
1386    AudioState *s = &glob_audio_state;
1387    struct audio_driver *driver;
1388    /* silence gcc warning about uninitialized variable */
1389    AudiodevListHead head = QSIMPLEQ_HEAD_INITIALIZER(head);
1390
1391    if (s->drv) {
1392        if (dev) {
1393            dolog("Cannot create more than one audio backend, sorry\n");
1394            qapi_free_Audiodev(dev);
1395        }
1396        return -1;
1397    }
1398
1399    if (dev) {
1400        /* -audiodev option */
1401        drvname = AudiodevDriver_str(dev->driver);
1402    } else {
1403        /* legacy implicit initialization */
1404        head = audio_handle_legacy_opts();
1405        /*
1406         * In case of legacy initialization, all Audiodevs in the list will have
1407         * the same configuration (except the driver), so it does't matter which
1408         * one we chose.  We need an Audiodev to set up AudioState before we can
1409         * init a driver.  Also note that dev at this point is still in the
1410         * list.
1411         */
1412        dev = QSIMPLEQ_FIRST(&head)->dev;
1413        audio_validate_opts(dev, &error_abort);
1414    }
1415    s->dev = dev;
1416
1417    QLIST_INIT (&s->hw_head_out);
1418    QLIST_INIT (&s->hw_head_in);
1419    QLIST_INIT (&s->cap_head);
1420    atexit(audio_cleanup);
1421
1422    s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1423
1424    s->nb_hw_voices_out = audio_get_pdo_out(dev)->voices;
1425    s->nb_hw_voices_in = audio_get_pdo_in(dev)->voices;
1426
1427    if (s->nb_hw_voices_out <= 0) {
1428        dolog ("Bogus number of playback voices %d, setting to 1\n",
1429               s->nb_hw_voices_out);
1430        s->nb_hw_voices_out = 1;
1431    }
1432
1433    if (s->nb_hw_voices_in <= 0) {
1434        dolog ("Bogus number of capture voices %d, setting to 0\n",
1435               s->nb_hw_voices_in);
1436        s->nb_hw_voices_in = 0;
1437    }
1438
1439    if (drvname) {
1440        driver = audio_driver_lookup(drvname);
1441        if (driver) {
1442            done = !audio_driver_init(s, driver, true, dev);
1443        } else {
1444            dolog ("Unknown audio driver `%s'\n", drvname);
1445        }
1446    } else {
1447        for (i = 0; audio_prio_list[i]; i++) {
1448            AudiodevListEntry *e = audiodev_find(&head, audio_prio_list[i]);
1449            driver = audio_driver_lookup(audio_prio_list[i]);
1450
1451            if (e && driver) {
1452                s->dev = dev = e->dev;
1453                audio_validate_opts(dev, &error_abort);
1454                done = !audio_driver_init(s, driver, false, dev);
1455                if (done) {
1456                    e->dev = NULL;
1457                    break;
1458                }
1459            }
1460        }
1461    }
1462    audio_free_audiodev_list(&head);
1463
1464    if (!done) {
1465        driver = audio_driver_lookup("none");
1466        done = !audio_driver_init(s, driver, false, dev);
1467        assert(done);
1468        dolog("warning: Using timer based audio emulation\n");
1469    }
1470
1471    if (dev->timer_period <= 0) {
1472        s->period_ticks = 1;
1473    } else {
1474        s->period_ticks = dev->timer_period * SCALE_US;
1475    }
1476
1477    e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1478    if (!e) {
1479        dolog ("warning: Could not register change state handler\n"
1480               "(Audio can continue looping even after stopping the VM)\n");
1481    }
1482
1483    QLIST_INIT (&s->card_head);
1484    vmstate_register (NULL, 0, &vmstate_audio, s);
1485    return 0;
1486}
1487
1488void audio_free_audiodev_list(AudiodevListHead *head)
1489{
1490    AudiodevListEntry *e;
1491    while ((e = QSIMPLEQ_FIRST(head))) {
1492        QSIMPLEQ_REMOVE_HEAD(head, next);
1493        qapi_free_Audiodev(e->dev);
1494        g_free(e);
1495    }
1496}
1497
1498void AUD_register_card (const char *name, QEMUSoundCard *card)
1499{
1500    audio_init(NULL);
1501    card->name = g_strdup (name);
1502    memset (&card->entries, 0, sizeof (card->entries));
1503    QLIST_INSERT_HEAD (&glob_audio_state.card_head, card, entries);
1504}
1505
1506void AUD_remove_card (QEMUSoundCard *card)
1507{
1508    QLIST_REMOVE (card, entries);
1509    g_free (card->name);
1510}
1511
1512
1513CaptureVoiceOut *AUD_add_capture (
1514    struct audsettings *as,
1515    struct audio_capture_ops *ops,
1516    void *cb_opaque
1517    )
1518{
1519    AudioState *s = &glob_audio_state;
1520    CaptureVoiceOut *cap;
1521    struct capture_callback *cb;
1522
1523    if (audio_validate_settings (as)) {
1524        dolog ("Invalid settings were passed when trying to add capture\n");
1525        audio_print_settings (as);
1526        return NULL;
1527    }
1528
1529    cb = g_malloc0(sizeof(*cb));
1530    cb->ops = *ops;
1531    cb->opaque = cb_opaque;
1532
1533    cap = audio_pcm_capture_find_specific (as);
1534    if (cap) {
1535        QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1536        return cap;
1537    }
1538    else {
1539        HWVoiceOut *hw;
1540        CaptureVoiceOut *cap;
1541
1542        cap = g_malloc0(sizeof(*cap));
1543
1544        hw = &cap->hw;
1545        QLIST_INIT (&hw->sw_head);
1546        QLIST_INIT (&cap->cb_head);
1547
1548        /* XXX find a more elegant way */
1549        hw->samples = 4096 * 4;
1550        hw->mix_buf = g_new0(struct st_sample, hw->samples);
1551
1552        audio_pcm_init_info (&hw->info, as);
1553
1554        cap->buf = g_malloc0_n(hw->samples, 1 << hw->info.shift);
1555
1556        hw->clip = mixeng_clip
1557            [hw->info.nchannels == 2]
1558            [hw->info.sign]
1559            [hw->info.swap_endianness]
1560            [audio_bits_to_index (hw->info.bits)];
1561
1562        QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1563        QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1564
1565        QLIST_FOREACH(hw, &glob_audio_state.hw_head_out, entries) {
1566            audio_attach_capture (hw);
1567        }
1568        return cap;
1569    }
1570}
1571
1572void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1573{
1574    struct capture_callback *cb;
1575
1576    for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1577        if (cb->opaque == cb_opaque) {
1578            cb->ops.destroy (cb_opaque);
1579            QLIST_REMOVE (cb, entries);
1580            g_free (cb);
1581
1582            if (!cap->cb_head.lh_first) {
1583                SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
1584
1585                while (sw) {
1586                    SWVoiceCap *sc = (SWVoiceCap *) sw;
1587#ifdef DEBUG_CAPTURE
1588                    dolog ("freeing %s\n", sw->name);
1589#endif
1590
1591                    sw1 = sw->entries.le_next;
1592                    if (sw->rate) {
1593                        st_rate_stop (sw->rate);
1594                        sw->rate = NULL;
1595                    }
1596                    QLIST_REMOVE (sw, entries);
1597                    QLIST_REMOVE (sc, entries);
1598                    g_free (sc);
1599                    sw = sw1;
1600                }
1601                QLIST_REMOVE (cap, entries);
1602                g_free (cap->hw.mix_buf);
1603                g_free (cap->buf);
1604                g_free (cap);
1605            }
1606            return;
1607        }
1608    }
1609}
1610
1611void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
1612{
1613    if (sw) {
1614        HWVoiceOut *hw = sw->hw;
1615
1616        sw->vol.mute = mute;
1617        sw->vol.l = nominal_volume.l * lvol / 255;
1618        sw->vol.r = nominal_volume.r * rvol / 255;
1619
1620        if (hw->pcm_ops->ctl_out) {
1621            hw->pcm_ops->ctl_out (hw, VOICE_VOLUME, sw);
1622        }
1623    }
1624}
1625
1626void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
1627{
1628    if (sw) {
1629        HWVoiceIn *hw = sw->hw;
1630
1631        sw->vol.mute = mute;
1632        sw->vol.l = nominal_volume.l * lvol / 255;
1633        sw->vol.r = nominal_volume.r * rvol / 255;
1634
1635        if (hw->pcm_ops->ctl_in) {
1636            hw->pcm_ops->ctl_in (hw, VOICE_VOLUME, sw);
1637        }
1638    }
1639}
1640
1641void audio_create_pdos(Audiodev *dev)
1642{
1643    switch (dev->driver) {
1644#define CASE(DRIVER, driver, pdo_name)                              \
1645    case AUDIODEV_DRIVER_##DRIVER:                                  \
1646        if (!dev->u.driver.has_in) {                                \
1647            dev->u.driver.in = g_malloc0(                           \
1648                sizeof(Audiodev##pdo_name##PerDirectionOptions));   \
1649            dev->u.driver.has_in = true;                            \
1650        }                                                           \
1651        if (!dev->u.driver.has_out) {                               \
1652            dev->u.driver.out = g_malloc0(                          \
1653                sizeof(AudiodevAlsaPerDirectionOptions));           \
1654            dev->u.driver.has_out = true;                           \
1655        }                                                           \
1656        break
1657
1658        CASE(NONE, none, );
1659        CASE(ALSA, alsa, Alsa);
1660        CASE(COREAUDIO, coreaudio, Coreaudio);
1661        CASE(DSOUND, dsound, );
1662        CASE(OSS, oss, Oss);
1663        CASE(PA, pa, Pa);
1664        CASE(SDL, sdl, );
1665        CASE(SPICE, spice, );
1666        CASE(WAV, wav, );
1667
1668    case AUDIODEV_DRIVER__MAX:
1669        abort();
1670    };
1671}
1672
1673static void audio_validate_per_direction_opts(
1674    AudiodevPerDirectionOptions *pdo, Error **errp)
1675{
1676    if (!pdo->has_fixed_settings) {
1677        pdo->has_fixed_settings = true;
1678        pdo->fixed_settings = true;
1679    }
1680    if (!pdo->fixed_settings &&
1681        (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
1682        error_setg(errp,
1683                   "You can't use frequency, channels or format with fixed-settings=off");
1684        return;
1685    }
1686
1687    if (!pdo->has_frequency) {
1688        pdo->has_frequency = true;
1689        pdo->frequency = 44100;
1690    }
1691    if (!pdo->has_channels) {
1692        pdo->has_channels = true;
1693        pdo->channels = 2;
1694    }
1695    if (!pdo->has_voices) {
1696        pdo->has_voices = true;
1697        pdo->voices = 1;
1698    }
1699    if (!pdo->has_format) {
1700        pdo->has_format = true;
1701        pdo->format = AUDIO_FORMAT_S16;
1702    }
1703}
1704
1705static void audio_validate_opts(Audiodev *dev, Error **errp)
1706{
1707    Error *err = NULL;
1708
1709    audio_create_pdos(dev);
1710
1711    audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
1712    if (err) {
1713        error_propagate(errp, err);
1714        return;
1715    }
1716
1717    audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
1718    if (err) {
1719        error_propagate(errp, err);
1720        return;
1721    }
1722
1723    if (!dev->has_timer_period) {
1724        dev->has_timer_period = true;
1725        dev->timer_period = 10000; /* 100Hz -> 10ms */
1726    }
1727}
1728
1729void audio_parse_option(const char *opt)
1730{
1731    AudiodevListEntry *e;
1732    Audiodev *dev = NULL;
1733
1734    Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
1735    visit_type_Audiodev(v, NULL, &dev, &error_fatal);
1736    visit_free(v);
1737
1738    audio_validate_opts(dev, &error_fatal);
1739
1740    e = g_malloc0(sizeof(AudiodevListEntry));
1741    e->dev = dev;
1742    QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
1743}
1744
1745void audio_init_audiodevs(void)
1746{
1747    AudiodevListEntry *e;
1748
1749    QSIMPLEQ_FOREACH(e, &audiodevs, next) {
1750        audio_init(e->dev);
1751    }
1752}
1753
1754audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
1755{
1756    return (audsettings) {
1757        .freq = pdo->frequency,
1758        .nchannels = pdo->channels,
1759        .fmt = pdo->format,
1760        .endianness = AUDIO_HOST_ENDIANNESS,
1761    };
1762}
1763
1764int audioformat_bytes_per_sample(AudioFormat fmt)
1765{
1766    switch (fmt) {
1767    case AUDIO_FORMAT_U8:
1768    case AUDIO_FORMAT_S8:
1769        return 1;
1770
1771    case AUDIO_FORMAT_U16:
1772    case AUDIO_FORMAT_S16:
1773        return 2;
1774
1775    case AUDIO_FORMAT_U32:
1776    case AUDIO_FORMAT_S32:
1777        return 4;
1778
1779    case AUDIO_FORMAT__MAX:
1780        ;
1781    }
1782    abort();
1783}
1784
1785
1786/* frames = freq * usec / 1e6 */
1787int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
1788                        audsettings *as, int def_usecs)
1789{
1790    uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
1791    return (as->freq * usecs + 500000) / 1000000;
1792}
1793
1794/* samples = channels * frames = channels * freq * usec / 1e6 */
1795int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
1796                         audsettings *as, int def_usecs)
1797{
1798    return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
1799}
1800
1801/*
1802 * bytes = bytes_per_sample * samples =
1803 *     bytes_per_sample * channels * freq * usec / 1e6
1804 */
1805int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
1806                       audsettings *as, int def_usecs)
1807{
1808    return audio_buffer_samples(pdo, as, def_usecs) *
1809        audioformat_bytes_per_sample(as->fmt);
1810}
1811