qemu/audio/alsaaudio.c
<<
>>
Prefs
   1/*
   2 * QEMU ALSA audio driver
   3 *
   4 * Copyright (c) 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
  25#include "qemu/osdep.h"
  26#include <alsa/asoundlib.h>
  27#include "qemu/main-loop.h"
  28#include "qemu/module.h"
  29#include "audio.h"
  30#include "trace.h"
  31
  32#pragma GCC diagnostic ignored "-Waddress"
  33
  34#define AUDIO_CAP "alsa"
  35#include "audio_int.h"
  36
  37struct pollhlp {
  38    snd_pcm_t *handle;
  39    struct pollfd *pfds;
  40    int count;
  41    int mask;
  42    AudioState *s;
  43};
  44
  45typedef struct ALSAVoiceOut {
  46    HWVoiceOut hw;
  47    snd_pcm_t *handle;
  48    struct pollhlp pollhlp;
  49    Audiodev *dev;
  50} ALSAVoiceOut;
  51
  52typedef struct ALSAVoiceIn {
  53    HWVoiceIn hw;
  54    snd_pcm_t *handle;
  55    struct pollhlp pollhlp;
  56    Audiodev *dev;
  57} ALSAVoiceIn;
  58
  59struct alsa_params_req {
  60    int freq;
  61    snd_pcm_format_t fmt;
  62    int nchannels;
  63};
  64
  65struct alsa_params_obt {
  66    int freq;
  67    AudioFormat fmt;
  68    int endianness;
  69    int nchannels;
  70    snd_pcm_uframes_t samples;
  71};
  72
  73static void GCC_FMT_ATTR (2, 3) alsa_logerr (int err, const char *fmt, ...)
  74{
  75    va_list ap;
  76
  77    va_start (ap, fmt);
  78    AUD_vlog (AUDIO_CAP, fmt, ap);
  79    va_end (ap);
  80
  81    AUD_log (AUDIO_CAP, "Reason: %s\n", snd_strerror (err));
  82}
  83
  84static void GCC_FMT_ATTR (3, 4) alsa_logerr2 (
  85    int err,
  86    const char *typ,
  87    const char *fmt,
  88    ...
  89    )
  90{
  91    va_list ap;
  92
  93    AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
  94
  95    va_start (ap, fmt);
  96    AUD_vlog (AUDIO_CAP, fmt, ap);
  97    va_end (ap);
  98
  99    AUD_log (AUDIO_CAP, "Reason: %s\n", snd_strerror (err));
 100}
 101
 102static void alsa_fini_poll (struct pollhlp *hlp)
 103{
 104    int i;
 105    struct pollfd *pfds = hlp->pfds;
 106
 107    if (pfds) {
 108        for (i = 0; i < hlp->count; ++i) {
 109            qemu_set_fd_handler (pfds[i].fd, NULL, NULL, NULL);
 110        }
 111        g_free (pfds);
 112    }
 113    hlp->pfds = NULL;
 114    hlp->count = 0;
 115    hlp->handle = NULL;
 116}
 117
 118static void alsa_anal_close1 (snd_pcm_t **handlep)
 119{
 120    int err = snd_pcm_close (*handlep);
 121    if (err) {
 122        alsa_logerr (err, "Failed to close PCM handle %p\n", *handlep);
 123    }
 124    *handlep = NULL;
 125}
 126
 127static void alsa_anal_close (snd_pcm_t **handlep, struct pollhlp *hlp)
 128{
 129    alsa_fini_poll (hlp);
 130    alsa_anal_close1 (handlep);
 131}
 132
 133static int alsa_recover (snd_pcm_t *handle)
 134{
 135    int err = snd_pcm_prepare (handle);
 136    if (err < 0) {
 137        alsa_logerr (err, "Failed to prepare handle %p\n", handle);
 138        return -1;
 139    }
 140    return 0;
 141}
 142
 143static int alsa_resume (snd_pcm_t *handle)
 144{
 145    int err = snd_pcm_resume (handle);
 146    if (err < 0) {
 147        alsa_logerr (err, "Failed to resume handle %p\n", handle);
 148        return -1;
 149    }
 150    return 0;
 151}
 152
 153static void alsa_poll_handler (void *opaque)
 154{
 155    int err, count;
 156    snd_pcm_state_t state;
 157    struct pollhlp *hlp = opaque;
 158    unsigned short revents;
 159
 160    count = poll (hlp->pfds, hlp->count, 0);
 161    if (count < 0) {
 162        dolog ("alsa_poll_handler: poll %s\n", strerror (errno));
 163        return;
 164    }
 165
 166    if (!count) {
 167        return;
 168    }
 169
 170    /* XXX: ALSA example uses initial count, not the one returned by
 171       poll, correct? */
 172    err = snd_pcm_poll_descriptors_revents (hlp->handle, hlp->pfds,
 173                                            hlp->count, &revents);
 174    if (err < 0) {
 175        alsa_logerr (err, "snd_pcm_poll_descriptors_revents");
 176        return;
 177    }
 178
 179    if (!(revents & hlp->mask)) {
 180        trace_alsa_revents(revents);
 181        return;
 182    }
 183
 184    state = snd_pcm_state (hlp->handle);
 185    switch (state) {
 186    case SND_PCM_STATE_SETUP:
 187        alsa_recover (hlp->handle);
 188        break;
 189
 190    case SND_PCM_STATE_XRUN:
 191        alsa_recover (hlp->handle);
 192        break;
 193
 194    case SND_PCM_STATE_SUSPENDED:
 195        alsa_resume (hlp->handle);
 196        break;
 197
 198    case SND_PCM_STATE_PREPARED:
 199        audio_run(hlp->s, "alsa run (prepared)");
 200        break;
 201
 202    case SND_PCM_STATE_RUNNING:
 203        audio_run(hlp->s, "alsa run (running)");
 204        break;
 205
 206    default:
 207        dolog ("Unexpected state %d\n", state);
 208    }
 209}
 210
 211static int alsa_poll_helper (snd_pcm_t *handle, struct pollhlp *hlp, int mask)
 212{
 213    int i, count, err;
 214    struct pollfd *pfds;
 215
 216    count = snd_pcm_poll_descriptors_count (handle);
 217    if (count <= 0) {
 218        dolog ("Could not initialize poll mode\n"
 219               "Invalid number of poll descriptors %d\n", count);
 220        return -1;
 221    }
 222
 223    pfds = audio_calloc ("alsa_poll_helper", count, sizeof (*pfds));
 224    if (!pfds) {
 225        dolog ("Could not initialize poll mode\n");
 226        return -1;
 227    }
 228
 229    err = snd_pcm_poll_descriptors (handle, pfds, count);
 230    if (err < 0) {
 231        alsa_logerr (err, "Could not initialize poll mode\n"
 232                     "Could not obtain poll descriptors\n");
 233        g_free (pfds);
 234        return -1;
 235    }
 236
 237    for (i = 0; i < count; ++i) {
 238        if (pfds[i].events & POLLIN) {
 239            qemu_set_fd_handler (pfds[i].fd, alsa_poll_handler, NULL, hlp);
 240        }
 241        if (pfds[i].events & POLLOUT) {
 242            trace_alsa_pollout(i, pfds[i].fd);
 243            qemu_set_fd_handler (pfds[i].fd, NULL, alsa_poll_handler, hlp);
 244        }
 245        trace_alsa_set_handler(pfds[i].events, i, pfds[i].fd, err);
 246
 247    }
 248    hlp->pfds = pfds;
 249    hlp->count = count;
 250    hlp->handle = handle;
 251    hlp->mask = mask;
 252    return 0;
 253}
 254
 255static int alsa_poll_out (HWVoiceOut *hw)
 256{
 257    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
 258
 259    return alsa_poll_helper (alsa->handle, &alsa->pollhlp, POLLOUT);
 260}
 261
 262static int alsa_poll_in (HWVoiceIn *hw)
 263{
 264    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
 265
 266    return alsa_poll_helper (alsa->handle, &alsa->pollhlp, POLLIN);
 267}
 268
 269static snd_pcm_format_t aud_to_alsafmt (AudioFormat fmt, int endianness)
 270{
 271    switch (fmt) {
 272    case AUDIO_FORMAT_S8:
 273        return SND_PCM_FORMAT_S8;
 274
 275    case AUDIO_FORMAT_U8:
 276        return SND_PCM_FORMAT_U8;
 277
 278    case AUDIO_FORMAT_S16:
 279        if (endianness) {
 280            return SND_PCM_FORMAT_S16_BE;
 281        } else {
 282            return SND_PCM_FORMAT_S16_LE;
 283        }
 284
 285    case AUDIO_FORMAT_U16:
 286        if (endianness) {
 287            return SND_PCM_FORMAT_U16_BE;
 288        } else {
 289            return SND_PCM_FORMAT_U16_LE;
 290        }
 291
 292    case AUDIO_FORMAT_S32:
 293        if (endianness) {
 294            return SND_PCM_FORMAT_S32_BE;
 295        } else {
 296            return SND_PCM_FORMAT_S32_LE;
 297        }
 298
 299    case AUDIO_FORMAT_U32:
 300        if (endianness) {
 301            return SND_PCM_FORMAT_U32_BE;
 302        } else {
 303            return SND_PCM_FORMAT_U32_LE;
 304        }
 305
 306    case AUDIO_FORMAT_F32:
 307        if (endianness) {
 308            return SND_PCM_FORMAT_FLOAT_BE;
 309        } else {
 310            return SND_PCM_FORMAT_FLOAT_LE;
 311        }
 312
 313    default:
 314        dolog ("Internal logic error: Bad audio format %d\n", fmt);
 315#ifdef DEBUG_AUDIO
 316        abort ();
 317#endif
 318        return SND_PCM_FORMAT_U8;
 319    }
 320}
 321
 322static int alsa_to_audfmt (snd_pcm_format_t alsafmt, AudioFormat *fmt,
 323                           int *endianness)
 324{
 325    switch (alsafmt) {
 326    case SND_PCM_FORMAT_S8:
 327        *endianness = 0;
 328        *fmt = AUDIO_FORMAT_S8;
 329        break;
 330
 331    case SND_PCM_FORMAT_U8:
 332        *endianness = 0;
 333        *fmt = AUDIO_FORMAT_U8;
 334        break;
 335
 336    case SND_PCM_FORMAT_S16_LE:
 337        *endianness = 0;
 338        *fmt = AUDIO_FORMAT_S16;
 339        break;
 340
 341    case SND_PCM_FORMAT_U16_LE:
 342        *endianness = 0;
 343        *fmt = AUDIO_FORMAT_U16;
 344        break;
 345
 346    case SND_PCM_FORMAT_S16_BE:
 347        *endianness = 1;
 348        *fmt = AUDIO_FORMAT_S16;
 349        break;
 350
 351    case SND_PCM_FORMAT_U16_BE:
 352        *endianness = 1;
 353        *fmt = AUDIO_FORMAT_U16;
 354        break;
 355
 356    case SND_PCM_FORMAT_S32_LE:
 357        *endianness = 0;
 358        *fmt = AUDIO_FORMAT_S32;
 359        break;
 360
 361    case SND_PCM_FORMAT_U32_LE:
 362        *endianness = 0;
 363        *fmt = AUDIO_FORMAT_U32;
 364        break;
 365
 366    case SND_PCM_FORMAT_S32_BE:
 367        *endianness = 1;
 368        *fmt = AUDIO_FORMAT_S32;
 369        break;
 370
 371    case SND_PCM_FORMAT_U32_BE:
 372        *endianness = 1;
 373        *fmt = AUDIO_FORMAT_U32;
 374        break;
 375
 376    case SND_PCM_FORMAT_FLOAT_LE:
 377        *endianness = 0;
 378        *fmt = AUDIO_FORMAT_F32;
 379        break;
 380
 381    case SND_PCM_FORMAT_FLOAT_BE:
 382        *endianness = 1;
 383        *fmt = AUDIO_FORMAT_F32;
 384        break;
 385
 386    default:
 387        dolog ("Unrecognized audio format %d\n", alsafmt);
 388        return -1;
 389    }
 390
 391    return 0;
 392}
 393
 394static void alsa_dump_info (struct alsa_params_req *req,
 395                            struct alsa_params_obt *obt,
 396                            snd_pcm_format_t obtfmt,
 397                            AudiodevAlsaPerDirectionOptions *apdo)
 398{
 399    dolog("parameter | requested value | obtained value\n");
 400    dolog("format    |      %10d |     %10d\n", req->fmt, obtfmt);
 401    dolog("channels  |      %10d |     %10d\n",
 402          req->nchannels, obt->nchannels);
 403    dolog("frequency |      %10d |     %10d\n", req->freq, obt->freq);
 404    dolog("============================================\n");
 405    dolog("requested: buffer len %" PRId32 " period len %" PRId32 "\n",
 406          apdo->buffer_length, apdo->period_length);
 407    dolog("obtained: samples %ld\n", obt->samples);
 408}
 409
 410static void alsa_set_threshold (snd_pcm_t *handle, snd_pcm_uframes_t threshold)
 411{
 412    int err;
 413    snd_pcm_sw_params_t *sw_params;
 414
 415    snd_pcm_sw_params_alloca (&sw_params);
 416
 417    err = snd_pcm_sw_params_current (handle, sw_params);
 418    if (err < 0) {
 419        dolog ("Could not fully initialize DAC\n");
 420        alsa_logerr (err, "Failed to get current software parameters\n");
 421        return;
 422    }
 423
 424    err = snd_pcm_sw_params_set_start_threshold (handle, sw_params, threshold);
 425    if (err < 0) {
 426        dolog ("Could not fully initialize DAC\n");
 427        alsa_logerr (err, "Failed to set software threshold to %ld\n",
 428                     threshold);
 429        return;
 430    }
 431
 432    err = snd_pcm_sw_params (handle, sw_params);
 433    if (err < 0) {
 434        dolog ("Could not fully initialize DAC\n");
 435        alsa_logerr (err, "Failed to set software parameters\n");
 436        return;
 437    }
 438}
 439
 440static int alsa_open(bool in, struct alsa_params_req *req,
 441                     struct alsa_params_obt *obt, snd_pcm_t **handlep,
 442                     Audiodev *dev)
 443{
 444    AudiodevAlsaOptions *aopts = &dev->u.alsa;
 445    AudiodevAlsaPerDirectionOptions *apdo = in ? aopts->in : aopts->out;
 446    snd_pcm_t *handle;
 447    snd_pcm_hw_params_t *hw_params;
 448    int err;
 449    unsigned int freq, nchannels;
 450    const char *pcm_name = apdo->has_dev ? apdo->dev : "default";
 451    snd_pcm_uframes_t obt_buffer_size;
 452    const char *typ = in ? "ADC" : "DAC";
 453    snd_pcm_format_t obtfmt;
 454
 455    freq = req->freq;
 456    nchannels = req->nchannels;
 457
 458    snd_pcm_hw_params_alloca (&hw_params);
 459
 460    err = snd_pcm_open (
 461        &handle,
 462        pcm_name,
 463        in ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
 464        SND_PCM_NONBLOCK
 465        );
 466    if (err < 0) {
 467        alsa_logerr2 (err, typ, "Failed to open `%s':\n", pcm_name);
 468        return -1;
 469    }
 470
 471    err = snd_pcm_hw_params_any (handle, hw_params);
 472    if (err < 0) {
 473        alsa_logerr2 (err, typ, "Failed to initialize hardware parameters\n");
 474        goto err;
 475    }
 476
 477    err = snd_pcm_hw_params_set_access (
 478        handle,
 479        hw_params,
 480        SND_PCM_ACCESS_RW_INTERLEAVED
 481        );
 482    if (err < 0) {
 483        alsa_logerr2 (err, typ, "Failed to set access type\n");
 484        goto err;
 485    }
 486
 487    err = snd_pcm_hw_params_set_format (handle, hw_params, req->fmt);
 488    if (err < 0) {
 489        alsa_logerr2 (err, typ, "Failed to set format %d\n", req->fmt);
 490    }
 491
 492    err = snd_pcm_hw_params_set_rate_near (handle, hw_params, &freq, 0);
 493    if (err < 0) {
 494        alsa_logerr2 (err, typ, "Failed to set frequency %d\n", req->freq);
 495        goto err;
 496    }
 497
 498    err = snd_pcm_hw_params_set_channels_near (
 499        handle,
 500        hw_params,
 501        &nchannels
 502        );
 503    if (err < 0) {
 504        alsa_logerr2 (err, typ, "Failed to set number of channels %d\n",
 505                      req->nchannels);
 506        goto err;
 507    }
 508
 509    if (apdo->buffer_length) {
 510        int dir = 0;
 511        unsigned int btime = apdo->buffer_length;
 512
 513        err = snd_pcm_hw_params_set_buffer_time_near(
 514            handle, hw_params, &btime, &dir);
 515
 516        if (err < 0) {
 517            alsa_logerr2(err, typ, "Failed to set buffer time to %" PRId32 "\n",
 518                         apdo->buffer_length);
 519            goto err;
 520        }
 521
 522        if (apdo->has_buffer_length && btime != apdo->buffer_length) {
 523            dolog("Requested buffer time %" PRId32
 524                  " was rejected, using %u\n", apdo->buffer_length, btime);
 525        }
 526    }
 527
 528    if (apdo->period_length) {
 529        int dir = 0;
 530        unsigned int ptime = apdo->period_length;
 531
 532        err = snd_pcm_hw_params_set_period_time_near(handle, hw_params, &ptime,
 533                                                     &dir);
 534
 535        if (err < 0) {
 536            alsa_logerr2(err, typ, "Failed to set period time to %" PRId32 "\n",
 537                         apdo->period_length);
 538            goto err;
 539        }
 540
 541        if (apdo->has_period_length && ptime != apdo->period_length) {
 542            dolog("Requested period time %" PRId32 " was rejected, using %d\n",
 543                  apdo->period_length, ptime);
 544        }
 545    }
 546
 547    err = snd_pcm_hw_params (handle, hw_params);
 548    if (err < 0) {
 549        alsa_logerr2 (err, typ, "Failed to apply audio parameters\n");
 550        goto err;
 551    }
 552
 553    err = snd_pcm_hw_params_get_buffer_size (hw_params, &obt_buffer_size);
 554    if (err < 0) {
 555        alsa_logerr2 (err, typ, "Failed to get buffer size\n");
 556        goto err;
 557    }
 558
 559    err = snd_pcm_hw_params_get_format (hw_params, &obtfmt);
 560    if (err < 0) {
 561        alsa_logerr2 (err, typ, "Failed to get format\n");
 562        goto err;
 563    }
 564
 565    if (alsa_to_audfmt (obtfmt, &obt->fmt, &obt->endianness)) {
 566        dolog ("Invalid format was returned %d\n", obtfmt);
 567        goto err;
 568    }
 569
 570    err = snd_pcm_prepare (handle);
 571    if (err < 0) {
 572        alsa_logerr2 (err, typ, "Could not prepare handle %p\n", handle);
 573        goto err;
 574    }
 575
 576    if (!in && aopts->has_threshold && aopts->threshold) {
 577        struct audsettings as = { .freq = freq };
 578        alsa_set_threshold(
 579            handle,
 580            audio_buffer_frames(qapi_AudiodevAlsaPerDirectionOptions_base(apdo),
 581                                &as, aopts->threshold));
 582    }
 583
 584    obt->nchannels = nchannels;
 585    obt->freq = freq;
 586    obt->samples = obt_buffer_size;
 587
 588    *handlep = handle;
 589
 590    if (obtfmt != req->fmt ||
 591         obt->nchannels != req->nchannels ||
 592         obt->freq != req->freq) {
 593        dolog ("Audio parameters for %s\n", typ);
 594        alsa_dump_info(req, obt, obtfmt, apdo);
 595    }
 596
 597#ifdef DEBUG
 598    alsa_dump_info(req, obt, obtfmt, apdo);
 599#endif
 600    return 0;
 601
 602 err:
 603    alsa_anal_close1 (&handle);
 604    return -1;
 605}
 606
 607static size_t alsa_write(HWVoiceOut *hw, void *buf, size_t len)
 608{
 609    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
 610    size_t pos = 0;
 611    size_t len_frames = len / hw->info.bytes_per_frame;
 612
 613    while (len_frames) {
 614        char *src = advance(buf, pos);
 615        snd_pcm_sframes_t written;
 616
 617        written = snd_pcm_writei(alsa->handle, src, len_frames);
 618
 619        if (written <= 0) {
 620            switch (written) {
 621            case 0:
 622                trace_alsa_wrote_zero(len_frames);
 623                return pos;
 624
 625            case -EPIPE:
 626                if (alsa_recover(alsa->handle)) {
 627                    alsa_logerr(written, "Failed to write %zu frames\n",
 628                                len_frames);
 629                    return pos;
 630                }
 631                trace_alsa_xrun_out();
 632                continue;
 633
 634            case -ESTRPIPE:
 635                /*
 636                 * stream is suspended and waiting for an application
 637                 * recovery
 638                 */
 639                if (alsa_resume(alsa->handle)) {
 640                    alsa_logerr(written, "Failed to write %zu frames\n",
 641                                len_frames);
 642                    return pos;
 643                }
 644                trace_alsa_resume_out();
 645                continue;
 646
 647            case -EAGAIN:
 648                return pos;
 649
 650            default:
 651                alsa_logerr(written, "Failed to write %zu frames from %p\n",
 652                            len, src);
 653                return pos;
 654            }
 655        }
 656
 657        pos += written * hw->info.bytes_per_frame;
 658        if (written < len_frames) {
 659            break;
 660        }
 661        len_frames -= written;
 662    }
 663
 664    return pos;
 665}
 666
 667static void alsa_fini_out (HWVoiceOut *hw)
 668{
 669    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
 670
 671    ldebug ("alsa_fini\n");
 672    alsa_anal_close (&alsa->handle, &alsa->pollhlp);
 673}
 674
 675static int alsa_init_out(HWVoiceOut *hw, struct audsettings *as,
 676                         void *drv_opaque)
 677{
 678    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
 679    struct alsa_params_req req;
 680    struct alsa_params_obt obt;
 681    snd_pcm_t *handle;
 682    struct audsettings obt_as;
 683    Audiodev *dev = drv_opaque;
 684
 685    req.fmt = aud_to_alsafmt (as->fmt, as->endianness);
 686    req.freq = as->freq;
 687    req.nchannels = as->nchannels;
 688
 689    if (alsa_open(0, &req, &obt, &handle, dev)) {
 690        return -1;
 691    }
 692
 693    obt_as.freq = obt.freq;
 694    obt_as.nchannels = obt.nchannels;
 695    obt_as.fmt = obt.fmt;
 696    obt_as.endianness = obt.endianness;
 697
 698    audio_pcm_init_info (&hw->info, &obt_as);
 699    hw->samples = obt.samples;
 700
 701    alsa->pollhlp.s = hw->s;
 702    alsa->handle = handle;
 703    alsa->dev = dev;
 704    return 0;
 705}
 706
 707#define VOICE_CTL_PAUSE 0
 708#define VOICE_CTL_PREPARE 1
 709#define VOICE_CTL_START 2
 710
 711static int alsa_voice_ctl (snd_pcm_t *handle, const char *typ, int ctl)
 712{
 713    int err;
 714
 715    if (ctl == VOICE_CTL_PAUSE) {
 716        err = snd_pcm_drop (handle);
 717        if (err < 0) {
 718            alsa_logerr (err, "Could not stop %s\n", typ);
 719            return -1;
 720        }
 721    } else {
 722        err = snd_pcm_prepare (handle);
 723        if (err < 0) {
 724            alsa_logerr (err, "Could not prepare handle for %s\n", typ);
 725            return -1;
 726        }
 727        if (ctl == VOICE_CTL_START) {
 728            err = snd_pcm_start(handle);
 729            if (err < 0) {
 730                alsa_logerr (err, "Could not start handle for %s\n", typ);
 731                return -1;
 732            }
 733        }
 734    }
 735
 736    return 0;
 737}
 738
 739static void alsa_enable_out(HWVoiceOut *hw, bool enable)
 740{
 741    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
 742    AudiodevAlsaPerDirectionOptions *apdo = alsa->dev->u.alsa.out;
 743
 744    if (enable) {
 745        bool poll_mode = apdo->try_poll;
 746
 747        ldebug("enabling voice\n");
 748        if (poll_mode && alsa_poll_out(hw)) {
 749            poll_mode = 0;
 750        }
 751        hw->poll_mode = poll_mode;
 752        alsa_voice_ctl(alsa->handle, "playback", VOICE_CTL_PREPARE);
 753    } else {
 754        ldebug("disabling voice\n");
 755        if (hw->poll_mode) {
 756            hw->poll_mode = 0;
 757            alsa_fini_poll(&alsa->pollhlp);
 758        }
 759        alsa_voice_ctl(alsa->handle, "playback", VOICE_CTL_PAUSE);
 760    }
 761}
 762
 763static int alsa_init_in(HWVoiceIn *hw, struct audsettings *as, void *drv_opaque)
 764{
 765    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
 766    struct alsa_params_req req;
 767    struct alsa_params_obt obt;
 768    snd_pcm_t *handle;
 769    struct audsettings obt_as;
 770    Audiodev *dev = drv_opaque;
 771
 772    req.fmt = aud_to_alsafmt (as->fmt, as->endianness);
 773    req.freq = as->freq;
 774    req.nchannels = as->nchannels;
 775
 776    if (alsa_open(1, &req, &obt, &handle, dev)) {
 777        return -1;
 778    }
 779
 780    obt_as.freq = obt.freq;
 781    obt_as.nchannels = obt.nchannels;
 782    obt_as.fmt = obt.fmt;
 783    obt_as.endianness = obt.endianness;
 784
 785    audio_pcm_init_info (&hw->info, &obt_as);
 786    hw->samples = obt.samples;
 787
 788    alsa->pollhlp.s = hw->s;
 789    alsa->handle = handle;
 790    alsa->dev = dev;
 791    return 0;
 792}
 793
 794static void alsa_fini_in (HWVoiceIn *hw)
 795{
 796    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
 797
 798    alsa_anal_close (&alsa->handle, &alsa->pollhlp);
 799}
 800
 801static size_t alsa_read(HWVoiceIn *hw, void *buf, size_t len)
 802{
 803    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
 804    size_t pos = 0;
 805
 806    while (len) {
 807        void *dst = advance(buf, pos);
 808        snd_pcm_sframes_t nread;
 809
 810        nread = snd_pcm_readi(
 811            alsa->handle, dst, len / hw->info.bytes_per_frame);
 812
 813        if (nread <= 0) {
 814            switch (nread) {
 815            case 0:
 816                trace_alsa_read_zero(len);
 817                return pos;
 818
 819            case -EPIPE:
 820                if (alsa_recover(alsa->handle)) {
 821                    alsa_logerr(nread, "Failed to read %zu frames\n", len);
 822                    return pos;
 823                }
 824                trace_alsa_xrun_in();
 825                continue;
 826
 827            case -EAGAIN:
 828                return pos;
 829
 830            default:
 831                alsa_logerr(nread, "Failed to read %zu frames to %p\n",
 832                            len, dst);
 833                return pos;
 834            }
 835        }
 836
 837        pos += nread * hw->info.bytes_per_frame;
 838        len -= nread * hw->info.bytes_per_frame;
 839    }
 840
 841    return pos;
 842}
 843
 844static void alsa_enable_in(HWVoiceIn *hw, bool enable)
 845{
 846    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
 847    AudiodevAlsaPerDirectionOptions *apdo = alsa->dev->u.alsa.in;
 848
 849    if (enable) {
 850        bool poll_mode = apdo->try_poll;
 851
 852        ldebug("enabling voice\n");
 853        if (poll_mode && alsa_poll_in(hw)) {
 854            poll_mode = 0;
 855        }
 856        hw->poll_mode = poll_mode;
 857
 858        alsa_voice_ctl(alsa->handle, "capture", VOICE_CTL_START);
 859    } else {
 860        ldebug ("disabling voice\n");
 861        if (hw->poll_mode) {
 862            hw->poll_mode = 0;
 863            alsa_fini_poll(&alsa->pollhlp);
 864        }
 865        alsa_voice_ctl(alsa->handle, "capture", VOICE_CTL_PAUSE);
 866    }
 867}
 868
 869static void alsa_init_per_direction(AudiodevAlsaPerDirectionOptions *apdo)
 870{
 871    if (!apdo->has_try_poll) {
 872        apdo->try_poll = true;
 873        apdo->has_try_poll = true;
 874    }
 875}
 876
 877static void *alsa_audio_init(Audiodev *dev)
 878{
 879    AudiodevAlsaOptions *aopts;
 880    assert(dev->driver == AUDIODEV_DRIVER_ALSA);
 881
 882    aopts = &dev->u.alsa;
 883    alsa_init_per_direction(aopts->in);
 884    alsa_init_per_direction(aopts->out);
 885
 886    /*
 887     * need to define them, as otherwise alsa produces no sound
 888     * doesn't set has_* so alsa_open can identify it wasn't set by the user
 889     */
 890    if (!dev->u.alsa.out->has_period_length) {
 891        /* 1024 frames assuming 44100Hz */
 892        dev->u.alsa.out->period_length = 1024 * 1000000 / 44100;
 893    }
 894    if (!dev->u.alsa.out->has_buffer_length) {
 895        /* 4096 frames assuming 44100Hz */
 896        dev->u.alsa.out->buffer_length = 4096ll * 1000000 / 44100;
 897    }
 898
 899    /*
 900     * OptsVisitor sets unspecified optional fields to zero, but do not depend
 901     * on it...
 902     */
 903    if (!dev->u.alsa.in->has_period_length) {
 904        dev->u.alsa.in->period_length = 0;
 905    }
 906    if (!dev->u.alsa.in->has_buffer_length) {
 907        dev->u.alsa.in->buffer_length = 0;
 908    }
 909
 910    return dev;
 911}
 912
 913static void alsa_audio_fini (void *opaque)
 914{
 915}
 916
 917static struct audio_pcm_ops alsa_pcm_ops = {
 918    .init_out = alsa_init_out,
 919    .fini_out = alsa_fini_out,
 920    .write    = alsa_write,
 921    .run_buffer_out = audio_generic_run_buffer_out,
 922    .enable_out = alsa_enable_out,
 923
 924    .init_in  = alsa_init_in,
 925    .fini_in  = alsa_fini_in,
 926    .read     = alsa_read,
 927    .run_buffer_in = audio_generic_run_buffer_in,
 928    .enable_in = alsa_enable_in,
 929};
 930
 931static struct audio_driver alsa_audio_driver = {
 932    .name           = "alsa",
 933    .descr          = "ALSA http://www.alsa-project.org",
 934    .init           = alsa_audio_init,
 935    .fini           = alsa_audio_fini,
 936    .pcm_ops        = &alsa_pcm_ops,
 937    .can_be_default = 1,
 938    .max_voices_out = INT_MAX,
 939    .max_voices_in  = INT_MAX,
 940    .voice_size_out = sizeof (ALSAVoiceOut),
 941    .voice_size_in  = sizeof (ALSAVoiceIn)
 942};
 943
 944static void register_audio_alsa(void)
 945{
 946    audio_driver_register(&alsa_audio_driver);
 947}
 948type_init(register_audio_alsa);
 949