Coverage Report

Created: 2026-11-30 06:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/mpv/player/audio.c
Line
Count
Source
1
/*
2
 * This file is part of mpv.
3
 *
4
 * mpv is free software; you can redistribute it and/or
5
 * modify it under the terms of the GNU Lesser General Public
6
 * License as published by the Free Software Foundation; either
7
 * version 2.1 of the License, or (at your option) any later version.
8
 *
9
 * mpv is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU Lesser General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU Lesser General Public
15
 * License along with mpv.  If not, see <http://www.gnu.org/licenses/>.
16
 */
17
18
#include <stddef.h>
19
#include <stdbool.h>
20
#include <inttypes.h>
21
#include <limits.h>
22
#include <math.h>
23
#include <assert.h>
24
25
#include "mpv_talloc.h"
26
27
#include "common/msg.h"
28
#include "common/encode.h"
29
#include "options/options.h"
30
#include "common/common.h"
31
#include "osdep/timer.h"
32
33
#include "audio/format.h"
34
#include "audio/out/ao.h"
35
#include "demux/demux.h"
36
#include "filters/f_async_queue.h"
37
#include "filters/f_decoder_wrapper.h"
38
#include "filters/filter_internal.h"
39
40
#include "core.h"
41
#include "command.h"
42
43
enum {
44
    AD_OK = 0,
45
    AD_EOF = -2,
46
    AD_WAIT = -4,
47
};
48
49
static void ao_process(struct mp_filter *f);
50
51
static void update_speed_filters(struct MPContext *mpctx)
52
0
{
53
0
    struct ao_chain *ao_c = mpctx->ao_chain;
54
0
    if (!ao_c)
55
0
        return;
56
57
0
    double pitch = mpctx->opts->playback_pitch;
58
0
    double speed = mpctx->opts->playback_speed;
59
0
    double resample = mpctx->speed_factor_a;
60
0
    double drop = 1.0;
61
62
0
    if (!mpctx->opts->pitch_correction) {
63
0
        resample *= speed;
64
0
        speed = 1.0;
65
0
    }
66
67
0
    int video_sync = mpctx->display_sync_active ?
68
0
        mpctx->video_out->opts->video_sync : VS_NONE;
69
0
    switch (video_sync) {
70
0
        case VS_DISP_ADROP:
71
0
            drop *= speed * resample / pitch;
72
0
            resample = pitch;
73
0
            speed = 1.0;
74
0
            break;
75
0
        case VS_DISP_TEMPO:
76
0
            speed = mpctx->audio_speed / pitch;
77
0
            resample = pitch;
78
0
            break;
79
0
        default:
80
0
            resample *= pitch;
81
0
            speed /= pitch;
82
0
            break;
83
0
    }
84
85
0
    mp_output_chain_set_audio_speed(ao_c->filter, speed, resample, drop);
86
0
}
87
88
static int recreate_audio_filters(struct MPContext *mpctx)
89
0
{
90
0
    struct ao_chain *ao_c = mpctx->ao_chain;
91
0
    mp_assert(ao_c);
92
93
0
    if (!mp_output_chain_update_filters(ao_c->filter, mpctx->opts->af_settings))
94
0
        goto fail;
95
96
0
    update_speed_filters(mpctx);
97
98
0
    mp_notify(mpctx, MPV_EVENT_AUDIO_RECONFIG, NULL);
99
100
0
    return 0;
101
102
0
fail:
103
0
    MP_ERR(mpctx, "Audio filter initialized failed!\n");
104
0
    return -1;
105
0
}
106
107
int reinit_audio_filters(struct MPContext *mpctx)
108
0
{
109
0
    struct ao_chain *ao_c = mpctx->ao_chain;
110
0
    if (!ao_c)
111
0
        return 0;
112
113
0
    double delay = mp_output_get_measured_total_delay(ao_c->filter);
114
115
0
    if (recreate_audio_filters(mpctx) < 0)
116
0
        return -1;
117
118
0
    double ndelay = mp_output_get_measured_total_delay(ao_c->filter);
119
120
    // Only force refresh if the amount of dropped buffered data is going to
121
    // cause "issues" for the A/V sync logic.
122
0
    if (mpctx->audio_status == STATUS_PLAYING && delay - ndelay >= 0.2)
123
0
        issue_refresh_seek(mpctx, MPSEEK_EXACT);
124
0
    return 1;
125
0
}
126
127
static double db_gain(double db)
128
0
{
129
0
    return pow(10.0, db/20.0);
130
0
}
131
132
static float compute_replaygain(struct MPContext *mpctx)
133
0
{
134
0
    struct MPOpts *opts = mpctx->opts;
135
136
0
    float rgain = 1.0;
137
138
0
    struct replaygain_data *rg = NULL;
139
0
    struct track *track = mpctx->current_track[0][STREAM_AUDIO];
140
0
    if (track)
141
0
        rg = track->stream->codec->replaygain_data;
142
0
    if (opts->rgain_mode && rg) {
143
0
        MP_VERBOSE(mpctx, "Replaygain: Track=%f/%f Album=%f/%f\n",
144
0
                   rg->track_gain, rg->track_peak,
145
0
                   rg->album_gain, rg->album_peak);
146
147
0
        float gain, peak;
148
0
        if (opts->rgain_mode == 1) {
149
0
            gain = rg->track_gain;
150
0
            peak = rg->track_peak;
151
0
        } else {
152
0
            gain = rg->album_gain;
153
0
            peak = rg->album_peak;
154
0
        }
155
156
0
        gain += opts->rgain_preamp;
157
0
        rgain = db_gain(gain);
158
159
0
        MP_VERBOSE(mpctx, "Applying replay-gain: %f\n", rgain);
160
161
0
        if (!opts->rgain_clip) { // clipping prevention
162
0
            rgain = MPMIN(rgain, 1.0 / peak);
163
0
            MP_VERBOSE(mpctx, "...with clipping prevention: %f\n", rgain);
164
0
        }
165
0
    } else if (opts->rgain_fallback) {
166
0
        rgain = db_gain(opts->rgain_fallback);
167
0
        MP_VERBOSE(mpctx, "Applying fallback gain: %f\n", rgain);
168
0
    }
169
170
0
    return rgain;
171
0
}
172
173
float audio_get_gain(struct MPContext *mpctx)
174
0
{
175
0
    struct MPOpts *opts = mpctx->opts;
176
0
    float gain = MPMAX(opts->softvol_volume / 100.0, 0);
177
0
    gain = pow(gain, 3);
178
0
    gain *= compute_replaygain(mpctx);
179
0
    gain *= db_gain(opts->softvol_gain);
180
0
    if (opts->softvol_mute)
181
0
        gain = 0.0;
182
0
    return gain;
183
0
}
184
185
// Called when opts->softvol_volume or opts->softvol_mute were changed.
186
void audio_update_volume(struct MPContext *mpctx)
187
11.3k
{
188
11.3k
    struct ao_chain *ao_c = mpctx->ao_chain;
189
11.3k
    if (!ao_c || !ao_c->ao)
190
11.3k
        return;
191
192
0
    float gain = audio_get_gain(mpctx);
193
0
    ao_set_gain(ao_c->ao, gain);
194
0
}
195
196
// Call this if opts->playback_speed or mpctx->speed_factor_* change.
197
void update_playback_speed(struct MPContext *mpctx)
198
0
{
199
0
    mpctx->audio_speed = mpctx->opts->playback_speed * mpctx->speed_factor_a;
200
0
    mpctx->video_speed = mpctx->opts->playback_speed * mpctx->speed_factor_v;
201
202
0
    update_speed_filters(mpctx);
203
0
}
204
205
static bool has_video_track(struct MPContext *mpctx)
206
0
{
207
0
    if (mpctx->vo_chain && mpctx->vo_chain->is_coverart)
208
0
        return false;
209
210
0
    for (int n = 0; n < mpctx->num_tracks; n++) {
211
0
        struct track *track = mpctx->tracks[n];
212
0
        if (track->type == STREAM_VIDEO && !track->attached_picture && !track->image)
213
0
            return true;
214
0
    }
215
216
0
    return false;
217
0
}
218
219
static void ao_chain_reset_state(struct ao_chain *ao_c)
220
0
{
221
0
    ao_c->last_out_pts = MP_NOPTS_VALUE;
222
0
    ao_c->out_eof = false;
223
0
    ao_c->start_pts_known = false;
224
0
    ao_c->start_pts = MP_NOPTS_VALUE;
225
0
    ao_c->untimed_throttle = false;
226
0
    ao_c->underrun = false;
227
0
    ao_c->delaying_audio_start = false;
228
0
}
229
230
void reset_audio_state(struct MPContext *mpctx)
231
0
{
232
0
    if (mpctx->ao_chain) {
233
0
        ao_chain_reset_state(mpctx->ao_chain);
234
0
        struct track *t = mpctx->ao_chain->track;
235
0
        if (t && t->dec)
236
0
            mp_decoder_wrapper_set_play_dir(t->dec, mpctx->play_dir);
237
0
    }
238
0
    mpctx->audio_status = mpctx->ao_chain ? STATUS_SYNCING : STATUS_EOF;
239
0
    mpctx->delay = 0;
240
0
}
241
242
void uninit_audio_out(struct MPContext *mpctx)
243
16.4k
{
244
16.4k
    struct ao_chain *ao_c = mpctx->ao_chain;
245
16.4k
    if (ao_c) {
246
0
        ao_c->ao_queue = NULL;
247
0
        TA_FREEP(&ao_c->queue_filter);
248
0
        ao_c->ao = NULL;
249
0
    }
250
16.4k
    if (mpctx->ao) {
251
        // Note: with gapless_audio, stop_play is not correctly set
252
0
        if ((mpctx->opts->gapless_audio || mpctx->stop_play == AT_END_OF_FILE) &&
253
0
            ao_is_playing(mpctx->ao) && !get_internal_paused(mpctx))
254
0
        {
255
0
            MP_VERBOSE(mpctx, "draining left over audio\n");
256
0
            ao_drain(mpctx->ao);
257
0
        }
258
0
        ao_uninit(mpctx->ao);
259
260
0
        mp_notify(mpctx, MPV_EVENT_AUDIO_RECONFIG, NULL);
261
0
    }
262
16.4k
    mpctx->ao = NULL;
263
16.4k
    TA_FREEP(&mpctx->ao_filter_fmt);
264
16.4k
}
265
266
static void ao_chain_uninit(struct ao_chain *ao_c)
267
0
{
268
0
    struct track *track = ao_c->track;
269
0
    if (track) {
270
0
        mp_assert(track->ao_c == ao_c);
271
0
        track->ao_c = NULL;
272
0
        if (ao_c->dec_src)
273
0
            mp_assert(track->dec->f->pins[0] == ao_c->dec_src);
274
0
        if (track->dec) {
275
0
            talloc_free(track->dec->f);
276
0
            track->dec = NULL;
277
0
        }
278
0
    }
279
280
0
    if (ao_c->filter_src)
281
0
        mp_pin_disconnect(ao_c->filter_src);
282
283
0
    talloc_free(ao_c->filter->f);
284
0
    talloc_free(ao_c->ao_filter);
285
0
    talloc_free(ao_c);
286
0
}
287
288
void uninit_audio_chain(struct MPContext *mpctx)
289
0
{
290
0
    if (mpctx->ao_chain) {
291
0
        ao_chain_uninit(mpctx->ao_chain);
292
0
        mpctx->ao_chain = NULL;
293
294
0
        mpctx->audio_status = STATUS_EOF;
295
296
0
        mp_notify(mpctx, MPV_EVENT_AUDIO_RECONFIG, NULL);
297
0
    }
298
0
}
299
300
static char *audio_config_to_str_buf(char *buf, size_t buf_sz, int rate,
301
                                     int format, struct mp_chmap channels)
302
0
{
303
0
    char ch[128];
304
0
    mp_chmap_to_str_buf(ch, sizeof(ch), &channels);
305
0
    char *hr_ch = mp_chmap_to_str_hr(&channels);
306
0
    if (strcmp(hr_ch, ch) != 0)
307
0
        mp_snprintf_cat(ch, sizeof(ch), " (%s)", hr_ch);
308
0
    snprintf(buf, buf_sz, "%dHz %s %dch %s", rate,
309
0
             ch, channels.num, af_fmt_to_str(format));
310
0
    return buf;
311
0
}
312
313
// Decide whether on a format change, we should reinit the AO.
314
static bool keep_weak_gapless_format(struct mp_aframe *old, struct mp_aframe* new)
315
0
{
316
0
    bool res = false;
317
0
    struct mp_aframe *new_mod = mp_aframe_new_ref(new);
318
0
    MP_HANDLE_OOM(new_mod);
319
320
    // If the sample formats are compatible (== libswresample generally can
321
    // convert them), keep the AO. On other changes, recreate it.
322
323
0
    int old_fmt = mp_aframe_get_format(old);
324
0
    int new_fmt = mp_aframe_get_format(new);
325
326
0
    if (af_format_conversion_score(old_fmt, new_fmt) == INT_MIN)
327
0
        goto done; // completely incompatible formats
328
329
0
    if (!mp_aframe_set_format(new_mod, old_fmt))
330
0
        goto done;
331
332
0
    res = mp_aframe_config_equals(old, new_mod);
333
334
0
done:
335
0
    talloc_free(new_mod);
336
0
    return res;
337
0
}
338
339
static void ao_chain_set_ao(struct ao_chain *ao_c, struct ao *ao)
340
0
{
341
0
    if (ao_c->ao != ao) {
342
0
        mp_assert(!ao_c->ao);
343
0
        ao_c->ao = ao;
344
0
        ao_c->ao_queue = ao_get_queue(ao_c->ao);
345
0
        ao_c->queue_filter = mp_async_queue_create_filter(ao_c->ao_filter,
346
0
                                                          MP_PIN_IN, ao_c->ao_queue);
347
0
        mp_async_queue_set_notifier(ao_c->queue_filter, ao_c->ao_filter);
348
        // Make sure filtering never stops with frames stuck in access filter.
349
0
        mp_filter_set_high_priority(ao_c->queue_filter, true);
350
0
        audio_update_volume(ao_c->mpctx);
351
0
    }
352
353
0
    if (ao_c->filter->ao_needs_update)
354
0
        mp_output_chain_set_ao(ao_c->filter, ao_c->ao);
355
356
0
    mp_filter_wakeup(ao_c->ao_filter);
357
0
}
358
359
static int reinit_audio_filters_and_output(struct MPContext *mpctx)
360
0
{
361
0
    struct MPOpts *opts = mpctx->opts;
362
0
    struct ao_chain *ao_c = mpctx->ao_chain;
363
0
    mp_assert(ao_c);
364
0
    struct track *track = ao_c->track;
365
366
0
    mp_assert(ao_c->filter->ao_needs_update);
367
368
    // The "ideal" filter output format
369
0
    struct mp_aframe *out_fmt = mp_aframe_new_ref(ao_c->filter->output_aformat);
370
0
    MP_HANDLE_OOM(out_fmt);
371
372
0
    if (!mp_aframe_config_is_valid(out_fmt)) {
373
0
        talloc_free(out_fmt);
374
0
        goto init_error;
375
0
    }
376
377
0
    if (af_fmt_is_pcm(mp_aframe_get_format(out_fmt))) {
378
0
        if (opts->force_srate)
379
0
            mp_aframe_set_rate(out_fmt, opts->force_srate);
380
0
        if (opts->audio_output_format)
381
0
            mp_aframe_set_format(out_fmt, opts->audio_output_format);
382
0
        if (opts->audio_output_channels.num_chmaps == 1)
383
0
            mp_aframe_set_chmap(out_fmt, &opts->audio_output_channels.chmaps[0]);
384
0
    }
385
386
    // Weak gapless audio: if the filter output format is the same as the
387
    // previous one, keep the AO and don't reinit anything.
388
    // Strong gapless: always keep the AO
389
0
    if ((mpctx->ao_filter_fmt && mpctx->ao && opts->gapless_audio < 0 &&
390
0
         keep_weak_gapless_format(mpctx->ao_filter_fmt, out_fmt)) ||
391
0
        (mpctx->ao && opts->gapless_audio > 0))
392
0
    {
393
0
        ao_chain_set_ao(ao_c, mpctx->ao);
394
0
        talloc_free(out_fmt);
395
0
        return 0;
396
0
    }
397
398
    // Format change during syncing. Force playback start early, then wait.
399
0
    if (ao_c->ao_queue && mp_async_queue_get_frames(ao_c->ao_queue) &&
400
0
        mpctx->audio_status == STATUS_SYNCING)
401
0
    {
402
0
        mpctx->audio_status = STATUS_READY;
403
0
        mp_wakeup_core(mpctx);
404
0
        talloc_free(out_fmt);
405
0
        return 0;
406
0
    }
407
0
    if (mpctx->audio_status == STATUS_READY) {
408
0
        talloc_free(out_fmt);
409
0
        return 0;
410
0
    }
411
412
0
    uninit_audio_out(mpctx);
413
414
0
    int out_rate = mp_aframe_get_rate(out_fmt);
415
0
    int out_format = mp_aframe_get_format(out_fmt);
416
0
    struct mp_chmap out_channels = {0};
417
0
    mp_aframe_get_chmap(out_fmt, &out_channels);
418
419
0
    int ao_flags = 0;
420
0
    bool spdif_fallback = !af_fmt_is_pcm(out_format) &&
421
0
                          ao_c->spdif_passthrough;
422
423
0
    if (opts->ao_null_fallback && !spdif_fallback)
424
0
        ao_flags |= AO_INIT_NULL_FALLBACK;
425
426
0
    if (opts->audio_stream_silence)
427
0
        ao_flags |= AO_INIT_STREAM_SILENCE;
428
429
0
    if (opts->audio_exclusive)
430
0
        ao_flags |= AO_INIT_EXCLUSIVE;
431
432
0
    if (af_fmt_is_pcm(out_format)) {
433
0
        if (!opts->audio_output_channels.set ||
434
0
            opts->audio_output_channels.auto_safe)
435
0
            ao_flags |= AO_INIT_SAFE_MULTICHANNEL_ONLY;
436
437
0
        mp_chmap_sel_list(&out_channels,
438
0
                          opts->audio_output_channels.chmaps,
439
0
                          opts->audio_output_channels.num_chmaps);
440
0
    }
441
442
0
    if (!has_video_track(mpctx))
443
0
        ao_flags |= AO_INIT_MEDIA_ROLE_MUSIC;
444
445
0
    mpctx->ao_filter_fmt = out_fmt;
446
447
0
    mpctx->ao = ao_init_best(mpctx->global, ao_flags, mp_wakeup_core_cb,
448
0
                             mpctx, mpctx->encode_lavc_ctx, out_rate,
449
0
                             out_format, out_channels);
450
451
0
    int ao_rate = 0;
452
0
    int ao_format = 0;
453
0
    struct mp_chmap ao_channels = {0};
454
0
    if (mpctx->ao)
455
0
        ao_get_format(mpctx->ao, &ao_rate, &ao_format, &ao_channels);
456
457
    // Verify passthrough format was not changed.
458
0
    if (mpctx->ao && !af_fmt_is_pcm(out_format)) {
459
0
        if (out_rate != ao_rate || out_format != ao_format ||
460
0
            !mp_chmap_equals(&out_channels, &ao_channels))
461
0
        {
462
0
            MP_ERR(mpctx, "Passthrough format unsupported.\n");
463
0
            ao_uninit(mpctx->ao);
464
0
            mpctx->ao = NULL;
465
0
        }
466
0
    }
467
468
0
    if (!mpctx->ao) {
469
        // If spdif was used, try to fallback to PCM.
470
0
        if (spdif_fallback && ao_c->track && ao_c->track->dec) {
471
0
            MP_VERBOSE(mpctx, "Falling back to PCM output.\n");
472
0
            ao_c->spdif_passthrough = false;
473
0
            ao_c->spdif_failed = true;
474
0
            mp_decoder_wrapper_set_spdif_flag(ao_c->track->dec, false);
475
0
            if (!mp_decoder_wrapper_reinit(ao_c->track->dec))
476
0
                goto init_error;
477
0
            reset_audio_state(mpctx);
478
0
            mp_output_chain_reset_harder(ao_c->filter);
479
0
            mp_wakeup_core(mpctx); // reinit with new format next time
480
0
            return 0;
481
0
        }
482
483
0
        MP_ERR(mpctx, "Could not open/initialize audio device -> no sound.\n");
484
0
        mpctx->error_playing = MPV_ERROR_AO_INIT_FAILED;
485
0
        goto init_error;
486
0
    }
487
488
0
    char tmp[192];
489
0
    MP_INFO(mpctx, "AO: [%s] %s\n", ao_get_name(mpctx->ao),
490
0
            audio_config_to_str_buf(tmp, sizeof(tmp), ao_rate, ao_format,
491
0
                                    ao_channels));
492
0
    MP_VERBOSE(mpctx, "AO: Description: %s\n", ao_get_description(mpctx->ao));
493
0
    update_window_title(mpctx, true);
494
495
0
    ao_c->ao_resume_time =
496
0
        opts->audio_wait_open > 0 ? mp_time_sec() + opts->audio_wait_open : 0;
497
498
0
    bool eof = mpctx->audio_status == STATUS_EOF;
499
0
    ao_set_paused(mpctx->ao, get_internal_paused(mpctx), eof);
500
501
0
    ao_chain_set_ao(ao_c, mpctx->ao);
502
503
0
    audio_update_volume(mpctx);
504
505
    // Almost nonsensical hack to deal with certain format change scenarios.
506
0
    if (mpctx->audio_status == STATUS_PLAYING)
507
0
        ao_start(mpctx->ao);
508
509
0
    mp_wakeup_core(mpctx);
510
0
    mp_notify(mpctx, MPV_EVENT_AUDIO_RECONFIG, NULL);
511
512
0
    return 0;
513
514
0
init_error:
515
0
    uninit_audio_chain(mpctx);
516
0
    uninit_audio_out(mpctx);
517
0
    error_on_track(mpctx, track);
518
0
    return -1;
519
0
}
520
521
int init_audio_decoder(struct MPContext *mpctx, struct track *track)
522
0
{
523
0
    mp_assert(!track->dec);
524
0
    if (!track->stream)
525
0
        goto init_error;
526
527
0
    track->dec = mp_decoder_wrapper_create(mpctx->filter_root, track->stream);
528
0
    if (!track->dec)
529
0
        goto init_error;
530
531
0
    if (track->ao_c)
532
0
        mp_decoder_wrapper_set_spdif_flag(track->dec, true);
533
534
0
    if (!mp_decoder_wrapper_reinit(track->dec))
535
0
        goto init_error;
536
537
0
    return 1;
538
539
0
init_error:
540
0
    if (track->sink)
541
0
        mp_pin_disconnect(track->sink);
542
0
    track->sink = NULL;
543
0
    track->dec_failed = true;
544
0
    return 0;
545
0
}
546
547
void reinit_audio_chain(struct MPContext *mpctx)
548
0
{
549
0
    struct track *track = NULL;
550
0
    track = mpctx->current_track[0][STREAM_AUDIO];
551
0
    if (!track || !track->stream) {
552
0
        if (!mpctx->encode_lavc_ctx)
553
0
            uninit_audio_out(mpctx);
554
0
        error_on_track(mpctx, track);
555
0
        return;
556
0
    }
557
0
    reinit_audio_chain_src(mpctx, track);
558
0
}
559
560
static const struct mp_filter_info ao_filter = {
561
    .name = "ao",
562
    .process = ao_process,
563
};
564
565
// Create the track's decoder and connect it to the filter chain.
566
static bool ao_chain_init_decoder(struct MPContext *mpctx, struct ao_chain *ao_c)
567
0
{
568
0
    struct track *track = ao_c->track;
569
0
    if (!init_audio_decoder(mpctx, track))
570
0
        return false;
571
0
    ao_c->dec_src = track->dec->f->pins[0];
572
0
    mp_pin_connect(ao_c->filter->f->pins[0], ao_c->dec_src);
573
0
    return true;
574
0
}
575
576
// Destroy the track's decoder, keeping the filter chain and the AO. The chain
577
// stays at EOF until reinit_audio_decoder().
578
void uninit_audio_decoder(struct MPContext *mpctx)
579
0
{
580
0
    struct ao_chain *ao_c = mpctx->ao_chain;
581
0
    struct track *track = ao_c->track;
582
0
    mp_assert(track && track->dec);
583
0
    talloc_free(track->dec->f);
584
0
    track->dec = NULL;
585
0
    ao_c->dec_src = NULL;
586
0
}
587
588
// Create a new decoder for the track and restart the chain with it.
589
void reinit_audio_decoder(struct MPContext *mpctx)
590
0
{
591
0
    struct ao_chain *ao_c = mpctx->ao_chain;
592
0
    mp_assert(ao_c->track && !ao_c->track->dec);
593
    // init_audio_decoder() deselects the track and destroys the chain on failure.
594
0
    if (!ao_chain_init_decoder(mpctx, ao_c))
595
0
        return;
596
    // The filter chain still holds the old decoder's EOF.
597
0
    mp_filter_reset(ao_c->filter->f);
598
0
    reset_audio_state(mpctx);
599
0
}
600
601
// (track=NULL creates a blank chain, used for lavfi-complex)
602
void reinit_audio_chain_src(struct MPContext *mpctx, struct track *track)
603
0
{
604
0
    mp_assert(!mpctx->ao_chain);
605
606
0
    mp_notify(mpctx, MPV_EVENT_AUDIO_RECONFIG, NULL);
607
608
0
    struct ao_chain *ao_c = talloc_zero(NULL, struct ao_chain);
609
0
    mpctx->ao_chain = ao_c;
610
0
    ao_c->mpctx = mpctx;
611
0
    ao_c->log = mpctx->log;
612
0
    ao_c->filter =
613
0
        mp_output_chain_create(mpctx->filter_root, MP_OUTPUT_CHAIN_AUDIO);
614
0
    ao_c->spdif_passthrough = true;
615
0
    ao_c->last_out_pts = MP_NOPTS_VALUE;
616
0
    ao_c->delay = mpctx->opts->audio_delay;
617
618
0
    ao_c->ao_filter = mp_filter_create(mpctx->filter_root, &ao_filter);
619
0
    if (!ao_c->filter || !ao_c->ao_filter)
620
0
        goto init_error;
621
0
    ao_c->ao_filter->priv = ao_c;
622
623
0
    mp_filter_add_pin(ao_c->ao_filter, MP_PIN_IN, "in");
624
0
    mp_pin_connect(ao_c->ao_filter->pins[0], ao_c->filter->f->pins[1]);
625
626
0
    if (track) {
627
0
        ao_c->track = track;
628
0
        track->ao_c = ao_c;
629
0
        if (!ao_chain_init_decoder(mpctx, ao_c))
630
0
            goto init_error;
631
0
    }
632
633
0
    reset_audio_state(mpctx);
634
635
0
    if (recreate_audio_filters(mpctx) < 0)
636
0
        goto init_error;
637
638
0
    if (mpctx->ao)
639
0
        audio_update_volume(mpctx);
640
641
0
    mp_wakeup_core(mpctx);
642
0
    return;
643
644
0
init_error:
645
0
    uninit_audio_chain(mpctx);
646
0
    uninit_audio_out(mpctx);
647
0
    error_on_track(mpctx, track);
648
0
}
649
650
// Return pts value corresponding to the start point of audio written to the
651
// ao queue so far.
652
double written_audio_pts(struct MPContext *mpctx)
653
0
{
654
0
    return mpctx->ao_chain ? mpctx->ao_chain->last_out_pts : MP_NOPTS_VALUE;
655
0
}
656
657
// Return pts value corresponding to currently playing audio adjusted for AO delay
658
// and playback speed.
659
double playing_audio_pts(struct MPContext *mpctx)
660
0
{
661
0
    double pts = written_audio_pts(mpctx);
662
0
    if (pts == MP_NOPTS_VALUE || !mpctx->ao)
663
0
        return pts;
664
0
    return pts - mpctx->audio_speed * ao_get_delay(mpctx->ao);
665
0
}
666
667
// This garbage is needed for untimed AOs. These consume audio infinitely fast,
668
// so try keeping approximate A/V sync by blocking audio transfer as needed.
669
static void update_throttle(struct MPContext *mpctx)
670
0
{
671
0
    struct ao_chain *ao_c = mpctx->ao_chain;
672
0
    bool new_throttle = mpctx->audio_status == STATUS_PLAYING &&
673
0
                        mpctx->delay > 0 && ao_c && ao_c->ao &&
674
0
                        ao_untimed(ao_c->ao) &&
675
0
                        mpctx->video_status != STATUS_EOF;
676
0
    if (ao_c && new_throttle != ao_c->untimed_throttle) {
677
0
        ao_c->untimed_throttle = new_throttle;
678
0
        mp_wakeup_core(mpctx);
679
0
        mp_filter_wakeup(ao_c->ao_filter);
680
0
    }
681
0
}
682
683
static void ao_process(struct mp_filter *f)
684
0
{
685
0
    struct ao_chain *ao_c = f->priv;
686
0
    struct MPContext *mpctx = ao_c->mpctx;
687
688
    // Once the chain reached EOF nothing is read from it again.
689
0
    if (ao_c->out_eof)
690
0
        return;
691
692
0
    if (!ao_c->queue_filter) {
693
        // This will eventually lead to the creation of the AO + queue, due
694
        // to how f_output_chain and AO management works.
695
0
        mp_pin_out_request_data(f->ppins[0]);
696
        // Check for EOF with no data case, which is a mess because everything
697
        // hates us.
698
0
        struct mp_frame frame = mp_pin_out_read(f->ppins[0]);
699
0
        if (frame.type == MP_FRAME_EOF) {
700
0
            MP_VERBOSE(mpctx, "got EOF with no data before it\n");
701
0
            ao_c->out_eof = true;
702
0
            mpctx->audio_status = STATUS_DRAINING;
703
0
            mp_wakeup_core(mpctx);
704
0
        } else if (frame.type) {
705
0
            mp_pin_out_unread(f->ppins[0], frame);
706
0
        }
707
0
        return;
708
0
    }
709
710
    // Due to mp_async_queue_set_notifier() this function is called when the
711
    // queue becomes full. This affects state changes in the normal playloop,
712
    // so wake it up. But avoid redundant wakeups during normal playback.
713
0
    if (mpctx->audio_status != STATUS_PLAYING &&
714
0
        mp_async_queue_is_full(ao_c->ao_queue))
715
0
        mp_wakeup_core(mpctx);
716
717
0
    if (mpctx->audio_status == STATUS_SYNCING && !ao_c->start_pts_known)
718
0
        return;
719
720
0
    if (ao_c->untimed_throttle)
721
0
        return;
722
723
0
    if (!mp_pin_can_transfer_data(ao_c->queue_filter->pins[0], f->ppins[0]))
724
0
        return;
725
726
0
    struct mp_frame frame = mp_pin_out_read(f->ppins[0]);
727
0
    if (frame.type == MP_FRAME_AUDIO) {
728
0
        struct mp_aframe *af = frame.data;
729
730
0
        double endpts = get_play_end_pts(mpctx);
731
0
        if (endpts != MP_NOPTS_VALUE) {
732
0
            endpts *= mpctx->play_dir;
733
            // Avoid decoding and discarding the entire rest of the file.
734
0
            if (mp_aframe_get_pts(af) >= endpts) {
735
0
                mp_pin_out_unread(f->ppins[0], frame);
736
0
                if (!ao_c->out_eof) {
737
0
                    ao_c->out_eof = true;
738
0
                    mp_pin_in_write(ao_c->queue_filter->pins[0], MP_EOF_FRAME);
739
0
                }
740
0
                return;
741
0
            }
742
0
        }
743
0
        double startpts = mpctx->audio_status == STATUS_SYNCING ?
744
0
                                            ao_c->start_pts : MP_NOPTS_VALUE;
745
0
        mp_aframe_clip_timestamps(af, startpts, endpts);
746
747
0
        int samples = mp_aframe_get_size(af);
748
0
        if (!samples) {
749
0
            mp_filter_internal_mark_progress(f);
750
0
            mp_frame_unref(&frame);
751
0
            return;
752
0
        }
753
754
0
        mpctx->shown_aframes += samples;
755
0
        double real_samplerate = mp_aframe_get_rate(af) / mpctx->audio_speed;
756
0
        if (mpctx->video_status != STATUS_EOF)
757
0
            mpctx->delay += samples / real_samplerate;
758
0
        ao_c->last_out_pts = mp_aframe_end_pts(af);
759
0
        update_throttle(mpctx);
760
761
        // Gapless case: the AO is still playing from previous file. It makes
762
        // no sense to wait, and in fact the "full queue" event we're waiting
763
        // for may never happen, so start immediately.
764
        // If the new audio starts "later" (big video sync offset), transfer
765
        // of data is stopped somewhere else.
766
0
        if (mpctx->audio_status == STATUS_SYNCING && ao_is_playing(ao_c->ao)) {
767
0
            mpctx->audio_status = STATUS_READY;
768
0
            mp_wakeup_core(mpctx);
769
0
            MP_VERBOSE(mpctx, "previous audio still playing; continuing\n");
770
0
        }
771
772
0
        mp_pin_in_write(ao_c->queue_filter->pins[0], frame);
773
0
    } else if (frame.type == MP_FRAME_EOF) {
774
0
        MP_VERBOSE(mpctx, "audio filter EOF\n");
775
776
0
        ao_c->out_eof = true;
777
0
        mp_wakeup_core(mpctx);
778
779
0
        mp_pin_in_write(ao_c->queue_filter->pins[0], frame);
780
0
        mp_filter_internal_mark_progress(f);
781
0
    } else {
782
0
        mp_frame_unref(&frame);
783
0
    }
784
0
}
785
786
void reload_audio_output(struct MPContext *mpctx)
787
11.3k
{
788
11.3k
    if (!mpctx->ao)
789
11.3k
        return;
790
791
0
    ao_reset(mpctx->ao);
792
0
    uninit_audio_out(mpctx);
793
0
    reinit_audio_filters(mpctx); // mostly to issue refresh seek
794
795
0
    struct ao_chain *ao_c = mpctx->ao_chain;
796
797
0
    if (ao_c) {
798
0
        reset_audio_state(mpctx);
799
0
        mp_output_chain_reset_harder(ao_c->filter);
800
0
    }
801
802
    // Whether we can use spdif might have changed. If we failed to use spdif
803
    // in the previous initialization, try it with spdif again (we'll fallback
804
    // to PCM again if necessary).
805
0
    if (ao_c && ao_c->track) {
806
0
        struct mp_decoder_wrapper *dec = ao_c->track->dec;
807
0
        if (dec && ao_c->spdif_failed) {
808
0
            ao_c->spdif_passthrough = true;
809
0
            ao_c->spdif_failed = false;
810
0
            mp_decoder_wrapper_set_spdif_flag(ao_c->track->dec, true);
811
0
            if (!mp_decoder_wrapper_reinit(dec)) {
812
0
                MP_ERR(mpctx, "Error reinitializing audio.\n");
813
0
                error_on_track(mpctx, ao_c->track);
814
0
            }
815
0
        }
816
0
    }
817
818
0
    mp_wakeup_core(mpctx);
819
0
}
820
821
// Returns audio start pts for seeking or video sync.
822
// Returns false if PTS is not known yet.
823
static bool get_sync_pts(struct MPContext *mpctx, double *pts)
824
0
{
825
0
    struct MPOpts *opts = mpctx->opts;
826
827
0
    *pts = MP_NOPTS_VALUE;
828
829
0
    if (!opts->initial_audio_sync)
830
0
        return true;
831
832
0
    bool sync_to_video = mpctx->vo_chain && mpctx->video_status != STATUS_EOF &&
833
0
                         !mpctx->vo_chain->is_sparse;
834
835
0
    if (sync_to_video) {
836
0
        if (mpctx->video_status < STATUS_READY)
837
0
            return false; // wait until we know a video PTS
838
0
        if (mpctx->video_pts != MP_NOPTS_VALUE)
839
0
            *pts = mpctx->video_pts - opts->audio_delay;
840
0
    } else if (mpctx->hrseek_active) {
841
0
        *pts = mpctx->hrseek_pts;
842
0
    } else {
843
        // If audio-only is enabled mid-stream during playback, sync accordingly.
844
0
        *pts = mpctx->playback_pts;
845
0
    }
846
847
0
    return true;
848
0
}
849
850
// Look whether audio can be started yet - if audio has to start some time
851
// after video.
852
// Caller needs to ensure mpctx->restart_complete is OK
853
void audio_start_ao(struct MPContext *mpctx)
854
0
{
855
0
    struct ao_chain *ao_c = mpctx->ao_chain;
856
0
    if (!ao_c || !ao_c->ao || mpctx->audio_status != STATUS_READY)
857
0
        return;
858
0
    double pts = MP_NOPTS_VALUE;
859
0
    if (!get_sync_pts(mpctx, &pts))
860
0
        return;
861
0
    double apts = playing_audio_pts(mpctx);
862
0
    if (mpctx->video_status != STATUS_EOF) {
863
0
        double speed = mpctx->opts->playback_speed;
864
0
        if (!ao_c->delaying_audio_start && pts != MP_NOPTS_VALUE &&
865
0
            apts != MP_NOPTS_VALUE && pts < apts)
866
0
        {
867
0
            MP_VERBOSE(mpctx, "delaying audio start %f vs. %f, diff=%f\n",
868
0
                       apts, pts, (apts - pts) / speed);
869
0
            ao_c->delaying_audio_start = true;
870
0
            ao_c->delayed_start_gap = apts - pts;
871
0
            mpctx->delay += apts - pts;
872
0
            ao_c->delayed_start_speed = 0;
873
0
        }
874
0
        if (ao_c->delaying_audio_start) {
875
            // Start audio once the video has played the gap to it. The video
876
            // pts moves in frame steps and ahead of the display, so the gap
877
            // is counted down in playback time from the first check on, every
878
            // interval at the speed it was played with.
879
0
            int64_t now = mp_time_ns();
880
0
            double passed = MP_TIME_NS_TO_S(now - ao_c->delayed_start_last);
881
0
            ao_c->delayed_start_gap -= passed * ao_c->delayed_start_speed;
882
0
            ao_c->delayed_start_last = now;
883
0
            ao_c->delayed_start_speed = get_internal_paused(mpctx) ? 0 : speed;
884
0
            if (ao_c->delayed_start_gap > 0) {
885
0
                if (ao_c->delayed_start_speed > 0)
886
0
                    mp_set_timeout(mpctx, ao_c->delayed_start_gap / speed);
887
0
                return;
888
0
            }
889
0
        }
890
0
    }
891
892
0
    MP_VERBOSE(mpctx, "starting audio playback\n");
893
0
    ao_c->delaying_audio_start = false;
894
0
    ao_start(ao_c->ao);
895
0
    mpctx->audio_status = STATUS_PLAYING;
896
0
    if (ao_c->out_eof) {
897
0
        mpctx->audio_status = STATUS_DRAINING;
898
0
        MP_VERBOSE(mpctx, "audio draining\n");
899
0
    }
900
0
    ao_c->underrun = false;
901
0
    mp_wakeup_core(mpctx);
902
0
}
903
904
void fill_audio_out_buffers(struct MPContext *mpctx)
905
0
{
906
0
    struct MPOpts *opts = mpctx->opts;
907
908
0
    if (mpctx->ao && ao_query_and_reset_events(mpctx->ao, AO_EVENT_RELOAD))
909
0
        reload_audio_output(mpctx);
910
911
0
    update_throttle(mpctx);
912
913
0
    struct ao_chain *ao_c = mpctx->ao_chain;
914
0
    if (!ao_c)
915
0
        return;
916
917
0
    if (ao_c->filter->failed_output_conversion) {
918
0
        error_on_track(mpctx, ao_c->track);
919
0
        return;
920
0
    }
921
922
0
    if (ao_c->filter->ao_needs_update) {
923
0
        if (reinit_audio_filters_and_output(mpctx) < 0)
924
0
            return;
925
0
    }
926
927
0
    if (mpctx->vo_chain && ao_c->track && ao_c->track->dec &&
928
0
        mp_decoder_wrapper_get_pts_reset(ao_c->track->dec))
929
0
    {
930
0
        MP_WARN(mpctx, "Reset playback due to audio timestamp reset.\n");
931
0
        reset_playback_state(mpctx);
932
0
        mp_wakeup_core(mpctx);
933
0
    }
934
935
0
    if (mpctx->audio_status == STATUS_SYNCING) {
936
0
        double pts;
937
0
        bool ok = get_sync_pts(mpctx, &pts);
938
939
        // If the AO is still playing from the previous file (due to gapless),
940
        // but if video is active, this may not work if audio starts later than
941
        // video, and gapless has no advantages anyway. So block doing anything
942
        // until the old audio is fully played.
943
        // (Buggy if AO underruns.)
944
0
        if (mpctx->ao && ao_is_playing(mpctx->ao) &&
945
0
            mpctx->video_status != STATUS_EOF) {
946
0
            MP_VERBOSE(mpctx, "blocked, waiting for old audio to play\n");
947
0
            ok = false;
948
0
        }
949
950
0
        if (ao_c->start_pts_known != ok || ao_c->start_pts != pts) {
951
0
            ao_c->start_pts_known = ok;
952
0
            ao_c->start_pts = pts;
953
0
            mp_filter_wakeup(ao_c->ao_filter);
954
0
        }
955
956
0
        if (ao_c->ao && mp_async_queue_is_full(ao_c->ao_queue)) {
957
0
            mpctx->audio_status = STATUS_READY;
958
0
            mp_wakeup_core(mpctx);
959
0
            MP_VERBOSE(mpctx, "audio ready\n");
960
0
        } else if (ao_c->out_eof) {
961
            // Force playback start early.
962
0
            mpctx->audio_status = STATUS_READY;
963
0
            mp_wakeup_core(mpctx);
964
0
            MP_VERBOSE(mpctx, "audio ready (and EOF)\n");
965
0
        }
966
0
    }
967
968
0
    if (ao_c->ao && !ao_is_playing(ao_c->ao) && !ao_c->underrun &&
969
0
        (mpctx->audio_status == STATUS_PLAYING ||
970
0
         mpctx->audio_status == STATUS_DRAINING))
971
0
    {
972
        // Should be playing, but somehow isn't.
973
974
0
        if (ao_c->out_eof && !mp_async_queue_get_frames(ao_c->ao_queue)) {
975
0
            MP_VERBOSE(mpctx, "AO signaled EOF (while in state %s)\n",
976
0
                       mp_status_str(mpctx->audio_status));
977
0
            mpctx->audio_status = STATUS_EOF;
978
0
            mp_wakeup_core(mpctx);
979
            // stops untimed AOs, stops pull AOs from streaming silence
980
0
            ao_reset(ao_c->ao);
981
0
        } else {
982
0
            if (!ao_c->ao_underrun) {
983
0
                MP_WARN(mpctx, "Audio device underrun detected.\n");
984
0
                ao_c->ao_underrun = true;
985
0
                mp_wakeup_core(mpctx);
986
0
                ao_c->underrun = true;
987
0
            }
988
989
            // Wait until buffers are filled before recovering underrun.
990
0
            if (ao_c->out_eof || mp_async_queue_is_full(ao_c->ao_queue)) {
991
0
                MP_VERBOSE(mpctx, "restarting audio after underrun\n");
992
0
                ao_start(mpctx->ao_chain->ao);
993
0
                ao_c->ao_underrun = false;
994
0
                ao_c->underrun = false;
995
0
                mp_wakeup_core(mpctx);
996
0
            }
997
0
        }
998
0
    }
999
1000
0
    if (mpctx->audio_status == STATUS_PLAYING && ao_c->out_eof) {
1001
0
        mpctx->audio_status = STATUS_DRAINING;
1002
0
        MP_VERBOSE(mpctx, "audio draining\n");
1003
0
        mp_wakeup_core(mpctx);
1004
0
    }
1005
1006
0
    if (mpctx->audio_status == STATUS_DRAINING) {
1007
        // Wait until the AO has played all queued data. In the gapless case,
1008
        // we trigger EOF immediately, and let it play asynchronously.
1009
0
        if (!ao_c->ao || (!ao_is_playing(ao_c->ao) || opts->gapless_audio))
1010
0
        {
1011
0
            MP_VERBOSE(mpctx, "audio EOF reached\n");
1012
0
            mpctx->audio_status = STATUS_EOF;
1013
0
            mp_wakeup_core(mpctx);
1014
0
        }
1015
0
    }
1016
1017
0
    if (mpctx->restart_complete)
1018
0
        audio_start_ao(mpctx); // in case it got delayed
1019
0
}
1020
1021
// Drop data queued for output, or which the AO is currently outputting.
1022
void clear_audio_output_buffers(struct MPContext *mpctx)
1023
0
{
1024
0
    if (mpctx->ao)
1025
0
        ao_reset(mpctx->ao);
1026
0
}