pulse.c 32 KB
Newer Older
1 2 3 4
/*****************************************************************************
 * pulse.c : Pulseaudio output plugin for vlc
 *****************************************************************************
 * Copyright (C) 2008 the VideoLAN team
5
 * Copyright (C) 2009-2011 Rémi Denis-Courmont
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 *
 * Authors: Martin Hamrle <hamrle @ post . cz>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

28
#include <math.h>
29
#include <vlc_common.h>
30
#include <vlc_plugin.h>
31
#include <vlc_aout.h>
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
32
#include <vlc_cpu.h>
33 34

#include <pulse/pulseaudio.h>
35
#include "vlcpulse.h"
36 37 38
#if !PA_CHECK_VERSION(0,9,22)
# include <vlc_xlib.h>
#endif
39 40 41 42

static int  Open        ( vlc_object_t * );
static void Close       ( vlc_object_t * );

43
vlc_module_begin ()
44
    set_shortname( "PulseAudio" )
45
    set_description( N_("Pulseaudio audio output") )
46
    set_capability( "audio output", 160 )
47 48
    set_category( CAT_AUDIO )
    set_subcategory( SUBCAT_AUDIO_AOUT )
49
    add_shortcut( "pulseaudio", "pa" )
50 51
    set_callbacks( Open, Close )
vlc_module_end ()
52

53 54 55 56 57 58 59
/* TODO:
 * - pause input on policy event
 * - resample to compensate for long term drift
 * - select music or video stream property correctly (?)
 * - set further appropriate stream properties
 * - update output devices list dynamically
 */
60

61 62
/* NOTE:
 * Be careful what you do when the PulseAudio mainloop is held, which is to say
63
 * within PulseAudio callbacks, or after pa_threaded_mainloop_lock().
64 65
 * In particular, a VLC variable callback cannot be triggered nor deleted with
 * the PulseAudio mainloop lock held, if the callback acquires the lock. */
66

67 68 69 70
struct aout_sys_t
{
    pa_stream *stream; /**< PulseAudio playback stream object */
    pa_context *context; /**< PulseAudio connection context */
71
    pa_threaded_mainloop *mainloop; /**< PulseAudio thread */
72
    pa_time_event *trigger; /**< Deferred stream trigger */
73 74
    pa_volume_t base_volume; /**< 0dB reference volume */
    pa_cvolume cvolume; /**< actual sink input volume */
75
    mtime_t paused; /**< Time when (last) paused */
76 77 78
    mtime_t pts; /**< Play time of buffer write offset */
    mtime_t desync; /**< Measured desynchronization */
    unsigned rate; /**< Current stream sample rate */
79 80
};

81
static void sink_list_cb(pa_context *, const pa_sink_info *, int, void *);
82 83 84 85 86 87 88 89 90 91 92 93 94
static void sink_input_info_cb(pa_context *, const pa_sink_input_info *,
                               int, void *);

/*** Context ***/
static void context_cb(pa_context *ctx, pa_subscription_event_type_t type,
                       uint32_t idx, void *userdata)
{
    audio_output_t *aout = userdata;
    aout_sys_t *sys = aout->sys;
    pa_operation *op;

    switch (type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK)
    {
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
      case PA_SUBSCRIPTION_EVENT_SINK:
        switch (type & PA_SUBSCRIPTION_EVENT_TYPE_MASK)
        {
          case PA_SUBSCRIPTION_EVENT_NEW:
          case PA_SUBSCRIPTION_EVENT_CHANGE:
            op = pa_context_get_sink_info_by_index(ctx, idx, sink_list_cb, aout);
            if (likely(op != NULL))
                pa_operation_unref(op);
            break;

          case PA_SUBSCRIPTION_EVENT_REMOVE:
            var_Change(aout, "audio-device", VLC_VAR_DELCHOICE,
                       &(vlc_value_t){ .i_int = idx }, NULL);
            break;
        }
        break;

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
      case PA_SUBSCRIPTION_EVENT_SINK_INPUT:
        if (idx != pa_stream_get_index(sys->stream))
            break; /* only interested in our sink input */

        /* Gee... PA will not provide the infos directly in the event. */
        switch (type & PA_SUBSCRIPTION_EVENT_TYPE_MASK)
        {
          case PA_SUBSCRIPTION_EVENT_REMOVE:
            msg_Err(aout, "sink input killed!");
            break;

          default:
            op = pa_context_get_sink_input_info(ctx, idx, sink_input_info_cb,
                                                aout);
            if (likely(op != NULL))
                pa_operation_unref(op);
            break;
        }
        break;

      default: /* unsubscribed facility?! */
        assert(0);
    }
}


138
/*** Sink ***/
139 140 141
static void sink_list_cb(pa_context *c, const pa_sink_info *i, int eol,
                         void *userdata)
{
142
    audio_output_t *aout = userdata;
143 144 145 146 147 148 149 150 151 152
    vlc_value_t val, text;

    if (eol)
        return;
    (void) c;

    msg_Dbg(aout, "listing sink %s (%"PRIu32"): %s", i->name, i->index,
            i->description);
    val.i_int = i->index;
    text.psz_string = (char *)i->description;
153
    /* FIXME: There is no way to replace a choice explicitly. */
154
    var_Change(aout, "audio-device", VLC_VAR_DELCHOICE, &val, NULL);
155
    var_Change(aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
156 157 158 159 160
    /* FIXME: var_Change() can change the variable value if we remove the
     * current value from the choice list, or if we add a choice while there
     * was none. So force the correct value back. */
    val.i_int = pa_stream_get_device_index(aout->sys->stream);
    var_Change(aout, "audio-device", VLC_VAR_SETVALUE, &val, NULL);
161 162
}

163 164 165
static void sink_info_cb(pa_context *c, const pa_sink_info *i, int eol,
                         void *userdata)
{
166
    audio_output_t *aout = userdata;
167
    aout_sys_t *sys = aout->sys;
168 169 170 171 172

    if (eol)
        return;
    (void) c;

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
173 174 175 176 177
    /* PulseAudio flat volume NORM / 100% / 0dB corresponds to no software
     * amplification and maximum hardware amplification.
     * VLC maps DEFAULT / 100% to no gain at all (software/hardware).
     * Thus we need to use the sink base_volume as a multiplier,
     * if and only if flat volume is active for our current sink. */
178 179 180 181
    if (i->flags & PA_SINK_FLAT_VOLUME)
        sys->base_volume = i->base_volume;
    else
        sys->base_volume = PA_VOLUME_NORM;
182
    msg_Dbg(aout, "base volume: %"PRIu32, sys->base_volume);
183 184
}

185 186

/*** Latency management and lip synchronization ***/
187
static void stream_reset_sync(pa_stream *s, audio_output_t *aout)
188
{
189 190
    aout_sys_t *sys = aout->sys;
    const unsigned rate = aout->format.i_rate;
191 192 193 194 195 196 197 198 199 200

    sys->pts = VLC_TS_INVALID;
    sys->desync = 0;
    pa_operation *op = pa_stream_update_sample_rate(s, rate, NULL, NULL);
    if (unlikely(op == NULL))
        return;
    pa_operation_unref(op);
    sys->rate = rate;
}

201 202 203 204 205 206
static void stream_start(pa_stream *s, audio_output_t *aout)
{
    aout_sys_t *sys = aout->sys;
    pa_operation *op;

    if (sys->trigger != NULL) {
207
        vlc_pa_rttime_free(sys->mainloop, sys->trigger);
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
        sys->trigger = NULL;
    }

    op = pa_stream_cork(s, 0, NULL, NULL);
    if (op != NULL)
        pa_operation_unref(op);
    op = pa_stream_trigger(s, NULL, NULL);
    if (likely(op != NULL))
        pa_operation_unref(op);
}

static void stream_stop(pa_stream *s, audio_output_t *aout)
{
    aout_sys_t *sys = aout->sys;
    pa_operation *op;

    if (sys->trigger != NULL) {
225
        vlc_pa_rttime_free(sys->mainloop, sys->trigger);
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
        sys->trigger = NULL;
    }

    op = pa_stream_cork(s, 1, NULL, NULL);
    if (op != NULL)
        pa_operation_unref(op);
}

static void stream_trigger_cb(pa_mainloop_api *api, pa_time_event *e,
                              const struct timeval *tv, void *userdata)
{
    audio_output_t *aout = userdata;
    aout_sys_t *sys = aout->sys;

    msg_Dbg(aout, "starting deferred");
    assert (sys->trigger == e);
    stream_start(sys->stream, aout);
    (void) api; (void) e; (void) tv;
}

246 247 248 249 250 251 252
/**
 * Starts or resumes the playback stream.
 * Tries start playing back audio samples at the most accurate time
 * in order to minimize desync and resampling during early playback.
 * @note PulseAudio lock required.
 */
static void stream_resync(audio_output_t *aout, pa_stream *s)
253
{
254 255 256 257 258 259 260 261 262 263 264
    aout_sys_t *sys = aout->sys;
    mtime_t delta;

    assert (sys->pts != VLC_TS_INVALID);

    delta = vlc_pa_get_latency(aout, sys->context, s);
    if (unlikely(delta == VLC_TS_INVALID))
        delta = 0; /* screwed */

    delta = (sys->pts - mdate()) - delta;
    if (delta > 0) {
265 266 267 268 269 270 271
        if (sys->trigger == NULL) {
            msg_Dbg(aout, "deferring start (%"PRId64" us)", delta);
            delta += pa_rtclock_now();
            sys->trigger = pa_context_rttime_new(sys->context, delta,
                                                 stream_trigger_cb, aout);
        }
    } else {
272
        msg_Warn(aout, "starting late (%"PRId64" us)", delta);
273 274
        stream_start(s, aout);
    }
275 276
}

277 278
static void stream_latency_cb(pa_stream *s, void *userdata)
{
279
    audio_output_t *aout = userdata;
280
    aout_sys_t *sys = aout->sys;
281 282
    mtime_t delta, change;

283 284
    if (pa_stream_is_corked(s))
        return;
285 286 287 288 289 290 291
    if (sys->pts == VLC_TS_INVALID)
    {
        msg_Dbg(aout, "missing latency from input");
        return;
    }

    /* Compute lip desynchronization */
292 293 294
    delta = vlc_pa_get_latency(aout, sys->context, s);
    if (delta == VLC_TS_INVALID)
        return;
295

296
    delta = (sys->pts - mdate()) - delta;
297 298 299 300 301
    change = delta - sys->desync;
    sys->desync = delta;
    //msg_Dbg(aout, "desync: %+"PRId64" us (variation: %+"PRId64" us)",
    //        delta, change);

302 303 304 305
    const unsigned inrate = aout->format.i_rate;
    unsigned outrate = sys->rate;
    bool sync = false;

306
    if (delta < -AOUT_MAX_PTS_DELAY)
307
        msg_Warn(aout, "too late by %"PRId64" us", -delta);
308
    else if (delta > +AOUT_MAX_PTS_ADVANCE)
309
        msg_Warn(aout, "too early by %"PRId64" us", delta);
310 311 312 313
    else if (outrate  == inrate)
        return; /* In sync, do not add unnecessary disturbance! */
    else
        sync = true;
314

315
    /* Compute playback sample rate */
316 317
    /* This is empirical (especially the shift values).
     * Feel free to define something smarter. */
318
    int adj = sync ? (outrate - inrate)
319
                   : outrate * ((delta >> 4) + change) / (CLOCK_FREQ << 2);
320 321 322 323 324 325 326
    /* This avoids too quick rate variation. It sounds really bad and
     * causes unstability (e.g. oscillation around the correct rate). */
    int limit = inrate >> 10;
    /* However, to improve stability and try to converge, closing to the
     * nominal rate is favored over drifting from it. */
    if ((adj > 0) == (sys->rate > inrate))
        limit *= 2;
327 328 329 330
    if (adj > +limit)
        adj = +limit;
    if (adj < -limit)
        adj = -limit;
331
    outrate -= adj;
332 333 334

    /* This keeps the effective rate within specified range
     * (+/-AOUT_MAX_RESAMPLING% - see <vlc_aout.h>) of the nominal rate. */
335
    limit = inrate * AOUT_MAX_RESAMPLING / 100;
336
    if (outrate > inrate + limit)
337
        outrate = inrate + limit;
338
    if (outrate < inrate - limit)
339 340 341
        outrate = inrate - limit;

    /* Apply adjusted sample rate */
342
    if (outrate == sys->rate)
343 344 345 346 347 348 349
        return;
    pa_operation *op = pa_stream_update_sample_rate(s, outrate, NULL, NULL);
    if (unlikely(op == NULL)) {
        vlc_pa_error(aout, "cannot change sample rate", sys->context);
        return;
    }
    pa_operation_unref(op);
350
    msg_Dbg(aout, "changed sample rate to %u Hz",outrate);
351 352 353
    sys->rate = outrate;
}

354 355 356 357

/*** Stream helpers ***/
static void stream_state_cb(pa_stream *s, void *userdata)
{
358 359
    pa_threaded_mainloop *mainloop = userdata;

360 361 362 363
    switch (pa_stream_get_state(s)) {
        case PA_STREAM_READY:
        case PA_STREAM_FAILED:
        case PA_STREAM_TERMINATED:
364
            pa_threaded_mainloop_signal(mainloop, 0);
365 366 367 368 369
        default:
            break;
    }
}

370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
static void stream_event_cb(pa_stream *s, const char *name, pa_proplist *pl,
                            void *userdata)
{
    audio_output_t *aout = userdata;

#if PA_CHECK_VERSION(1,0,0)
    /* FIXME: expose aout_Restart() directly */
    if (!strcmp(name, PA_STREAM_EVENT_FORMAT_LOST)) {
        vlc_value_t dummy = { .i_int = 0 };

        msg_Dbg (aout, "format lost");
        aout_ChannelsRestart (VLC_OBJECT(aout), "audio-device",
                              dummy, dummy, NULL);
    } else
#endif
        msg_Warn (aout, "unhandled event %s", name);
    (void) s;
    (void) pl;
}

390 391
static void stream_moved_cb(pa_stream *s, void *userdata)
{
392
    audio_output_t *aout = userdata;
393
    aout_sys_t *sys = aout->sys;
394 395
    pa_operation *op;
    uint32_t idx = pa_stream_get_device_index(s);
396

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
397 398 399 400
    msg_Dbg(aout, "connected to sink %"PRIu32": %s", idx,
                  pa_stream_get_device_name(s));
    op = pa_context_get_sink_info_by_index(sys->context, idx,
                                           sink_info_cb, aout);
401 402
    if (likely(op != NULL))
        pa_operation_unref(op);
403 404 405 406

    /* Update the variable if someone else moved our stream */
    var_Change(aout, "audio-device", VLC_VAR_SETVALUE,
               &(vlc_value_t){ .i_int = idx }, NULL);
407 408 409 410 411 412 413 414 415 416

    /* Sink unknown as yet, create stub choice for it */
    if (var_GetInteger(aout, "audio-device") != idx)
    {
        var_Change(aout, "audio-device", VLC_VAR_ADDCHOICE,
                   &(vlc_value_t){ .i_int = idx },
                   &(vlc_value_t){ .psz_string = (char *)"?" });
        var_Change(aout, "audio-device", VLC_VAR_SETVALUE,
                   &(vlc_value_t){ .i_int = idx }, NULL);
    }
417 418
}

419 420
static void stream_overflow_cb(pa_stream *s, void *userdata)
{
421
    audio_output_t *aout = userdata;
422
    pa_operation *op;
423

424 425 426 427 428
    msg_Err(aout, "overflow, flushing");
    op = pa_stream_flush(s, NULL, NULL);
    if (likely(op != NULL))
        pa_operation_unref(op);
    stream_reset_sync(s, aout);
429 430 431 432
}

static void stream_started_cb(pa_stream *s, void *userdata)
{
433
    audio_output_t *aout = userdata;
434 435 436 437 438 439 440

    msg_Dbg(aout, "started");
    (void) s;
}

static void stream_suspended_cb(pa_stream *s, void *userdata)
{
441
    audio_output_t *aout = userdata;
442 443

    msg_Dbg(aout, "suspended");
444
    stream_reset_sync(s, aout);
445 446 447 448
}

static void stream_underflow_cb(pa_stream *s, void *userdata)
{
449
    audio_output_t *aout = userdata;
450

451
    msg_Warn(aout, "underflow");
452
    stream_stop(s, aout);
453
    stream_reset_sync(s, aout);
454 455
}

456
static int stream_wait(pa_stream *stream, pa_threaded_mainloop *mainloop)
457 458 459 460 461 462
{
    pa_stream_state_t state;

    while ((state = pa_stream_get_state(stream)) != PA_STREAM_READY) {
        if (state == PA_STREAM_FAILED || state == PA_STREAM_TERMINATED)
            return -1;
463
        pa_threaded_mainloop_wait(mainloop);
464 465 466 467
    }
    return 0;
}

468 469 470 471 472 473

/*** Sink input ***/
static void sink_input_info_cb(pa_context *ctx, const pa_sink_input_info *i,
                               int eol, void *userdata)
{
    audio_output_t *aout = userdata;
474
    aout_sys_t *sys = aout->sys;
475 476 477

    if (eol)
        return;
478
    (void) ctx;
479

480 481 482 483
    sys->cvolume = i->volume; /* cache volume for balance preservation */

    pa_volume_t volume = pa_cvolume_max(&i->volume);
    volume = pa_sw_volume_divide(volume, sys->base_volume);
484 485
    aout_VolumeReport(aout, (float)volume / PA_VOLUME_NORM);
    aout_MuteReport(aout, i->mute);
486 487 488 489 490
}


/*** VLC audio output callbacks ***/

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
/* Memory free callback. The block_t address is in front of the data. */
static void data_free(void *data)
{
    block_t **pp = data, *block;

    memcpy(&block, pp - 1, sizeof (block));
    block_Release(block);
}

static void *data_convert(block_t **pp)
{
    block_t *block = *pp;
    /* In most cases, there is enough head room, and this is really cheap: */
    block = block_Realloc(block, sizeof (block), block->i_buffer);
    *pp = block;
    if (unlikely(block == NULL))
        return NULL;

    memcpy(block->p_buffer, &block, sizeof (block));
    block->p_buffer += sizeof (block);
    block->i_buffer -= sizeof (block);
    return block->p_buffer;
}

515 516 517
/**
 * Queue one audio frame to the playabck stream
 */
518
static void Play(audio_output_t *aout, block_t *block, mtime_t *restrict drift)
519
{
520
    aout_sys_t *sys = aout->sys;
521 522
    pa_stream *s = sys->stream;

523 524
    assert (sys->paused == VLC_TS_INVALID);

525 526 527 528 529 530 531
    const void *ptr = data_convert(&block);
    if (unlikely(ptr == NULL))
        return;

    size_t len = block->i_buffer;
    mtime_t pts = block->i_pts + block->i_length;

532 533 534 535 536
    /* Note: The core already holds the output FIFO lock at this point.
     * Therefore we must not under any circumstances (try to) acquire the
     * output FIFO lock while the PulseAudio threaded main loop lock is held
     * (including from PulseAudio stream callbacks). Otherwise lock inversion
     * will take place, and sooner or later a deadlock. */
537
    pa_threaded_mainloop_lock(sys->mainloop);
538

539 540 541
    sys->pts = pts;
    if (pa_stream_is_corked(s) > 0)
        stream_resync(aout, s);
542

543
#if 0 /* Fault injector to test underrun recovery */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
544 545
    static volatile unsigned u = 0;
    if ((++u % 1000) == 0) {
546
        msg_Err(aout, "fault injection");
547
        pa_operation_unref(pa_stream_flush(s, NULL, NULL));
548 549 550
    }
#endif

551
    if (pa_stream_write(s, ptr, len, data_free, 0, PA_SEEK_RELATIVE) < 0) {
552
        vlc_pa_error(aout, "cannot write", sys->context);
553
        block_Release(block);
554 555
    }

556
    pa_threaded_mainloop_unlock(sys->mainloop);
557
    (void) drift;
558 559
}

560 561 562
/**
 * Cork or uncork the playback stream
 */
563
static void Pause(audio_output_t *aout, bool paused, mtime_t date)
564
{
565
    aout_sys_t *sys = aout->sys;
566
    pa_stream *s = sys->stream;
567

568
    pa_threaded_mainloop_lock(sys->mainloop);
569

570 571
    if (paused) {
        sys->paused = date;
572
        stream_stop(s, aout);
573 574 575 576 577 578 579 580
    } else {
        assert (sys->paused != VLC_TS_INVALID);
        date -= sys->paused;
        msg_Dbg(aout, "resuming after %"PRId64" us", date);
        sys->paused = VLC_TS_INVALID;
        sys->pts += date;
        stream_resync(aout, s);
    }
581

582
    pa_threaded_mainloop_unlock(sys->mainloop);
583 584
}

585 586 587 588 589 590 591 592 593
/**
 * Flush or drain the playback stream
 */
static void Flush(audio_output_t *aout, bool wait)
{
    aout_sys_t *sys = aout->sys;
    pa_stream *s = sys->stream;
    pa_operation *op;

594
    pa_threaded_mainloop_lock(sys->mainloop);
595 596 597 598 599 600 601 602

    if (wait)
        op = pa_stream_drain(s, NULL, NULL);
        /* TODO: wait for drain completion*/
    else
        op = pa_stream_flush(s, NULL, NULL);
    if (op != NULL)
        pa_operation_unref(op);
603
    pa_threaded_mainloop_unlock(sys->mainloop);
604 605
}

606
static int VolumeSet(audio_output_t *aout, float vol)
607
{
608
    aout_sys_t *sys = aout->sys;
609 610 611
    pa_operation *op;
    uint32_t idx = pa_stream_get_index(sys->stream);

612 613 614 615 616 617
    /* VLC provides the software volume so convert directly to PulseAudio
     * software volume, pa_volume_t. This is not a linear amplification factor
     * so do not use PulseAudio linear amplification! */
    vol *= PA_VOLUME_NORM;
    if (unlikely(vol >= PA_VOLUME_MAX))
        vol = PA_VOLUME_MAX;
618 619 620 621 622
    pa_volume_t volume = pa_sw_volume_multiply(lround(vol), sys->base_volume);

    /* Preserve the balance (VLC does not support it). */
    pa_cvolume cvolume = sys->cvolume;
    pa_cvolume_scale(&cvolume, PA_VOLUME_NORM);
623
    pa_sw_cvolume_multiply_scalar(&cvolume, &cvolume, volume);
624

625
    assert(pa_cvolume_valid(&cvolume));
626

627
    pa_threaded_mainloop_lock(sys->mainloop);
628
    op = pa_context_set_sink_input_volume(sys->context, idx, &cvolume, NULL, NULL);
629 630
    if (likely(op != NULL))
        pa_operation_unref(op);
631 632 633 634 635 636 637 638 639 640 641 642
    pa_threaded_mainloop_unlock(sys->mainloop);

    return 0;
}

static int MuteSet(audio_output_t *aout, bool mute)
{
    aout_sys_t *sys = aout->sys;
    pa_operation *op;
    uint32_t idx = pa_stream_get_index(sys->stream);

    pa_threaded_mainloop_lock(sys->mainloop);
643
    op = pa_context_set_sink_input_mute(sys->context, idx, mute, NULL, NULL);
644 645
    if (likely(op != NULL))
        pa_operation_unref(op);
646
    pa_threaded_mainloop_unlock(sys->mainloop);
647 648 649

    return 0;
}
650

651 652 653
static int StreamMove(vlc_object_t *obj, const char *varname, vlc_value_t old,
                      vlc_value_t val, void *userdata)
{
654
    audio_output_t *aout = (audio_output_t *)obj;
655
    aout_sys_t *sys = aout->sys;
656 657 658 659 660
    pa_stream *s = userdata;
    pa_operation *op;
    uint32_t idx = pa_stream_get_index(s);
    uint32_t sink_idx = val.i_int;

661 662
    (void) varname; (void) old;

663
    pa_threaded_mainloop_lock(sys->mainloop);
664 665
    op = pa_context_move_sink_input_by_index(sys->context, idx, sink_idx,
                                             NULL, NULL);
666 667 668 669
    if (likely(op != NULL)) {
        pa_operation_unref(op);
        msg_Dbg(aout, "moving to sink %"PRIu32, sink_idx);
    } else
670
        vlc_pa_error(obj, "cannot move sink", sys->context);
671
    pa_threaded_mainloop_unlock(sys->mainloop);
672 673

    return (op != NULL) ? VLC_SUCCESS : VLC_EGENERIC;
674 675 676
}


677 678 679
/**
 * Create a PulseAudio playback stream, a.k.a. a sink input.
 */
680
static int Open(vlc_object_t *obj)
681
{
682 683 684 685 686
#if !PA_CHECK_VERSION(0,9,22)
    if (!vlc_xlib_init(obj))
        return VLC_EGENERIC;
#endif

687
    audio_output_t *aout = (audio_output_t *)obj;
688
    pa_operation *op;
689

690 691
    /* Sample format specification */
    struct pa_sample_spec ss;
692
    vlc_fourcc_t format = aout->format.i_format;
693 694 695
#if PA_CHECK_VERSION(1,0,0)
    pa_encoding_t encoding = PA_ENCODING_INVALID;
#endif
Danny Wood's avatar
Danny Wood committed
696

697
    switch(format)
Danny Wood's avatar
Danny Wood committed
698
    {
699
        case VLC_CODEC_F64B:
700
            format = VLC_CODEC_F32B;
701 702
        case VLC_CODEC_F32B:
            ss.format = PA_SAMPLE_FLOAT32BE;
703
            break;
704
        case VLC_CODEC_F64L:
705
            format = VLC_CODEC_F32L;
706 707
        case VLC_CODEC_F32L:
            ss.format = PA_SAMPLE_FLOAT32LE;
708
            break;
709 710
        case VLC_CODEC_S32B:
            ss.format = PA_SAMPLE_S32BE;
711
            break;
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
        case VLC_CODEC_S32L:
            ss.format = PA_SAMPLE_S32LE;
            break;
        case VLC_CODEC_S24B:
            ss.format = PA_SAMPLE_S24BE;
            break;
        case VLC_CODEC_S24L:
            ss.format = PA_SAMPLE_S24LE;
            break;
        case VLC_CODEC_S16B:
            ss.format = PA_SAMPLE_S16BE;
            break;
        case VLC_CODEC_S16L:
            ss.format = PA_SAMPLE_S16LE;
            break;
        case VLC_CODEC_S8:
728
            format = VLC_CODEC_U8;
729 730
        case VLC_CODEC_U8:
            ss.format = PA_SAMPLE_U8;
731
            break;
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
#if PA_CHECK_VERSION(1,0,0)
        case VLC_CODEC_A52:
            format = VLC_CODEC_SPDIFL;
            encoding = PA_ENCODING_AC3_IEC61937;
            ss.format = HAVE_FPU ? PA_SAMPLE_FLOAT32NE : PA_SAMPLE_S16NE;
            break;
        /*case VLC_CODEC_EAC3:
            format = VLC_CODEC_SPDIFL FIXME;
            encoding = PA_ENCODING_EAC3_IEC61937;
            ss.format = HAVE_FPU ? PA_SAMPLE_FLOAT32NE : PA_SAMPLE_S16NE;
            break;
        case VLC_CODEC_MPGA:
            format = VLC_CODEC_SPDIFL FIXME;
            encoding = PA_ENCODING_MPEG_IEC61937;
            ss.format = HAVE_FPU ? PA_SAMPLE_FLOAT32NE : PA_SAMPLE_S16NE;
            break;*/
        case VLC_CODEC_DTS:
            format = VLC_CODEC_SPDIFL;
            encoding = PA_ENCODING_DTS_IEC61937;
            ss.format = HAVE_FPU ? PA_SAMPLE_FLOAT32NE : PA_SAMPLE_S16NE;
            break;
#endif
754
        default:
755 756
            if (HAVE_FPU)
            {
757
                format = VLC_CODEC_FL32;
758 759 760 761
                ss.format = PA_SAMPLE_FLOAT32NE;
            }
            else
            {
762
                format = VLC_CODEC_S16N;
763 764 765
                ss.format = PA_SAMPLE_S16NE;
            }
            break;
Danny Wood's avatar
Danny Wood committed
766 767
    }

768 769
    ss.rate = aout->format.i_rate;
    ss.channels = aout_FormatNbChannels(&aout->format);
770
    if (!pa_sample_spec_valid(&ss)) {
771
        msg_Err(aout, "unsupported sample specification");
772
        return VLC_EGENERIC;
773
    }
774

775
    /* Channel mapping (order defined in vlc_aout.h) */
776 777 778
    struct pa_channel_map map;
    map.channels = 0;

779
    if (aout->format.i_physical_channels & AOUT_CHAN_LEFT)
780
        map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_LEFT;
781
    if (aout->format.i_physical_channels & AOUT_CHAN_RIGHT)
782
        map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_RIGHT;
783
    if (aout->format.i_physical_channels & AOUT_CHAN_MIDDLELEFT)
784
        map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_LEFT;
785
    if (aout->format.i_physical_channels & AOUT_CHAN_MIDDLERIGHT)
786
        map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_RIGHT;
787
    if (aout->format.i_physical_channels & AOUT_CHAN_REARLEFT)
788
        map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_LEFT;
789
    if (aout->format.i_physical_channels & AOUT_CHAN_REARRIGHT)
790
        map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_RIGHT;
791
    if (aout->format.i_physical_channels & AOUT_CHAN_REARCENTER)
792
        map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_CENTER;
793
    if (aout->format.i_physical_channels & AOUT_CHAN_CENTER)
794 795 796 797 798 799
    {
        if (ss.channels == 1)
            map.map[map.channels++] = PA_CHANNEL_POSITION_MONO;
        else
            map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_CENTER;
    }
800
    if (aout->format.i_physical_channels & AOUT_CHAN_LFE)
801 802 803 804
        map.map[map.channels++] = PA_CHANNEL_POSITION_LFE;

    for (unsigned i = 0; map.channels < ss.channels; i++) {
        map.map[map.channels++] = PA_CHANNEL_POSITION_AUX0 + i;
805
        msg_Warn(aout, "mapping channel %"PRIu8" to AUX%u", map.channels, i);
806
    }
807

808
    if (!pa_channel_map_valid(&map)) {
809
        msg_Err(aout, "unsupported channel map");
810 811
        return VLC_EGENERIC;
    } else {
812
        const char *name = pa_channel_map_to_name(&map);
813
        msg_Dbg(aout, "using %s channel map", (name != NULL) ? name : "?");
814
    }
815

816
    /* Stream parameters */
817 818
    const pa_stream_flags_t flags = PA_STREAM_START_CORKED
                                  //| PA_STREAM_INTERPOLATE_TIMING
819 820
                                  | PA_STREAM_AUTO_TIMING_UPDATE
                                  | PA_STREAM_VARIABLE_RATE;
821 822

    struct pa_buffer_attr attr;
823
    attr.maxlength = -1;
824 825 826 827 828 829
    /* PulseAudio assumes that tlength bytes are available in the buffer. Thus
     * we need to be conservative and set the minimum value that the VLC
     * audio decoder thread warrants. Otherwise, PulseAudio buffers will
     * underrun on hardware with large buffers. VLC keeps at least
     * AOUT_MIN_PREPARE and at most AOUT_MAX_PREPARE worth of audio buffers.
     * TODO? tlength could be adaptively increased to reduce wakeups. */
830
    attr.tlength = pa_usec_to_bytes(AOUT_MIN_PREPARE_TIME, &ss);
831
    attr.prebuf = 0; /* trigger manually */
832 833
    attr.minreq = -1;
    attr.fragsize = 0; /* not used for output */
834

835
    /* Allocate structures */
836
    aout_sys_t *sys = malloc(sizeof(*sys));
837 838
    if (unlikely(sys == NULL))
        return VLC_ENOMEM;
839

840
    pa_context *ctx = vlc_pa_connect(obj, &sys->mainloop);
841 842 843 844 845 846
    if (ctx == NULL)
    {
        free (sys);
        return VLC_EGENERIC;
    }

847
    aout->sys = sys;
848
    sys->stream = NULL;
849
    sys->context = ctx;
850
    sys->trigger = NULL;
851
    sys->paused = VLC_TS_INVALID;
852 853 854
    sys->pts = VLC_TS_INVALID;
    sys->desync = 0;
    sys->rate = ss.rate;
855

856
    /* Channel volume */
857
    sys->base_volume = PA_VOLUME_NORM;
858 859
    pa_cvolume_set(&sys->cvolume, ss.channels, PA_VOLUME_NORM);

860 861 862 863 864 865 866 867 868 869
#if PA_CHECK_VERSION(1,0,0)
    pa_format_info *formatv[2];
    unsigned formatc = 0;

    /* Favor digital pass-through if available*/
    if (encoding != PA_ENCODING_INVALID) {
        formatv[formatc] = pa_format_info_new();
        formatv[formatc]->encoding = encoding;
        pa_format_info_set_rate(formatv[formatc], ss.rate);
        pa_format_info_set_channels(formatv[formatc], ss.channels);
870
        pa_format_info_set_channel_map(formatv[formatc], &map);
871 872 873 874 875 876 877 878 879
        formatc++;
    }

    /* Fallback to PCM */
    formatv[formatc] = pa_format_info_new();
    formatv[formatc]->encoding = PA_ENCODING_PCM;
    pa_format_info_set_sample_format(formatv[formatc], ss.format);
    pa_format_info_set_rate(formatv[formatc], ss.rate);
    pa_format_info_set_channels(formatv[formatc], ss.channels);
880
    pa_format_info_set_channel_map(formatv[formatc], &map);
881 882
    formatc++;

883
    /* Create a playback stream */
884 885
    pa_stream *s;

886
    pa_threaded_mainloop_lock(sys->mainloop);
887 888 889 890 891
    s = pa_stream_new_extended(ctx, "audio stream", formatv, formatc, NULL);

    for (unsigned i = 0; i < formatc; i++)
        pa_format_info_free(formatv[i]);
#else
892
    pa_threaded_mainloop_lock(sys->mainloop);
893
    pa_stream *s = pa_stream_new(ctx, "audio stream", &ss, &map);
894
#endif
895
    if (s == NULL) {
896
        vlc_pa_error(obj, "stream creation failure", ctx);
897
        goto fail;
898
    }
899
    sys->stream = s;
900
    pa_stream_set_state_callback(s, stream_state_cb, sys->mainloop);
901
    pa_stream_set_event_callback(s, stream_event_cb, aout);
902
    pa_stream_set_latency_update_callback(s, stream_latency_cb, aout);
903
    pa_stream_set_moved_callback(s, stream_moved_cb, aout);
904 905 906 907
    pa_stream_set_overflow_callback(s, stream_overflow_cb, aout);
    pa_stream_set_started_callback(s, stream_started_cb, aout);
    pa_stream_set_suspended_callback(s, stream_suspended_cb, aout);
    pa_stream_set_underflow_callback(s, stream_underflow_cb, aout);
908

909
    if (pa_stream_connect_playback(s, NULL, &attr, flags, NULL, NULL) < 0
910
     || stream_wait(s, sys->mainloop)) {
911
        vlc_pa_error(obj, "stream connection failure", ctx);
912
        goto fail;
913 914
    }

915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
#if PA_CHECK_VERSION(1,0,0)
    if (encoding != PA_ENCODING_INVALID) {
        const pa_format_info *info = pa_stream_get_format_info(s);

        assert (info != NULL);
        if (pa_format_info_is_pcm (info)) {
            msg_Dbg(aout, "digital pass-through not available");
            format = HAVE_FPU ? VLC_CODEC_FL32 : VLC_CODEC_S16N;
        } else {
            msg_Dbg(aout, "digital pass-through enabled");
            pa_stream_set_latency_update_callback(s, NULL, NULL);
        }
    }
#endif

930 931
    const struct pa_buffer_attr *pba = pa_stream_get_buffer_attr(s);
    msg_Dbg(aout, "using buffer metrics: maxlength=%u, tlength=%u, "
932 933
            "prebuf=%u, minreq=%u",
            pba->maxlength, pba->tlength, pba->prebuf, pba->minreq);
934

935 936 937 938 939 940 941 942 943
    var_Create(aout, "audio-device", VLC_VAR_INTEGER|VLC_VAR_HASCHOICE);
    var_Change(aout, "audio-device", VLC_VAR_SETTEXT,
               &(vlc_value_t){ .psz_string = (char *)_("Audio device") },
               NULL);
    var_AddCallback (aout, "audio-device", StreamMove, s);
    op = pa_context_get_sink_info_list(ctx, sink_list_cb, aout);
    /* We may need to wait for completion... once LibVLC supports this */
    if (op != NULL)
        pa_operation_unref(op);
944
    stream_moved_cb(s, aout);
945 946 947 948 949 950 951 952

    /* Context events */
    const pa_subscription_mask_t mask = PA_SUBSCRIPTION_MASK_SINK
                                      | PA_SUBSCRIPTION_MASK_SINK_INPUT;
    pa_context_set_subscribe_callback(ctx, context_cb, aout);
    op = pa_context_subscribe(ctx, mask, NULL, NULL);
    if (likely(op != NULL))
       pa_operation_unref(op);
953
    pa_threaded_mainloop_unlock(sys->mainloop);
954

955
    aout->format.i_format = format;
956 957
    aout->pf_play = Play;
    aout->pf_pause = Pause;
958
    aout->pf_flush = Flush;
959 960
    aout->volume_set = VolumeSet;
    aout->mute_set = MuteSet;
961 962 963
    return VLC_SUCCESS;

fail:
964
    pa_threaded_mainloop_unlock(sys->mainloop);
965
    Close(obj);
966 967 968
    return VLC_EGENERIC;
}

969 970 971
/**
 * Removes a PulseAudio playback stream
 */
972
static void Close (vlc_object_t *obj)
973
{
974
    audio_output_t *aout = (audio_output_t *)obj;
975
    aout_sys_t *sys = aout->sys;
976 977 978
    pa_context *ctx = sys->context;
    pa_stream *s = sys->stream;

979 980 981 982 983
    if (s != NULL) {
        /* The callback takes mainloop lock, so it CANNOT be held here! */
        var_DelCallback (aout, "audio-device", StreamMove, s);
        var_Destroy (aout, "audio-device");

984
        pa_threaded_mainloop_lock(sys->mainloop);
985
        if (unlikely(sys->trigger != NULL))
986
            vlc_pa_rttime_free(sys->mainloop, sys->trigger);
987
        pa_stream_disconnect(s);
988

989 990
        /* Clear all callbacks */
        pa_stream_set_state_callback(s, NULL, NULL);
991
        pa_stream_set_event_callback(s, NULL, NULL);
992 993 994 995 996 997
        pa_stream_set_latency_update_callback(s, NULL, NULL);
        pa_stream_set_moved_callback(s, NULL, NULL);
        pa_stream_set_overflow_callback(s, NULL, NULL);
        pa_stream_set_started_callback(s, NULL, NULL);
        pa_stream_set_suspended_callback(s, NULL, NULL);
        pa_stream_set_underflow_callback(s, NULL, NULL);
998
        pa_context_set_subscribe_callback(ctx, NULL, NULL);
999

1000
        pa_stream_unref(s);
1001
        pa_threaded_mainloop_unlock(sys->mainloop);
1002
    }
1003

1004
    vlc_pa_disconnect(obj, ctx, sys->mainloop);
1005
    free(sys);
1006
}