The raw AC-4 demuxer set only codec type/id, leaving sample_rate and channels at 0 with no packet timestamps. That made the generic mux layer reject every stream copy (EINVAL) and made generic index seeks fail (EPERM).
Peek at the first sync frame in read_header and run the shared TOC walk over it (libavcodec/ac4_toc.h, the same reader the frame parser uses per packet): frame_rate_index/fs_index yield the output sample rate (base sample frequency x sf_mult per TS 103 190-2 section 5.11/Table 70 and Table E.1, never the internal spf x fps block grid), and channel_mode yields the channel count/layout. Timestamps are synthesized in read_packet from a frame counter times the exact per-frame output sample count (av_rescale, absolute per frame, so 1001-rate rows get exact 1601/1602-style alternation with no drift); the counter rebases from the generic index after seeks, and emits NOPTS (duration 0) on rebase misses until the next hit, so seeks to unvisited positions never stamp plausible-but-wrong pts. Whole sync frames are flagged KEY and the frame parser (need_parsing HEADERS) clears the flag on non-iframe packets from b_iframe_global, so seeks clamp to decodable keyframes. The peek is two-stage and bounded: a 4096-byte fast path covers every real sample with zero extra IO, and a truncated walk re-peeks once up to a 64 KiB hard cap (semantic rejects never re-peek). Oversize TOCs warn naming the bound and leave params unset instead of being chased. Any unsupported shape (reserved rate rows 14/15, multi-group, no-bed AJOC/object-only, unmapped channel modes) or any walk overrun bails to previous behavior: params stay unset and decode is unaffected, since the decoder parses the TOC itself. Non-seekable inputs use a seekback window for the peek. codecpar bit_rate is estimated from the first-frame size so generic code derives duration. read_packet validates the sync word and rejects size-0 payloads (INVALIDDATA) instead of emitting confidently-stamped garbage; clean EOF still returns AVERROR_EOF silently, and a failed peek rewind fails read_header (EIO) instead of succeeding desynced. FATE: fate-ac4-demux / fate-ac4-demux-51 pin the latched params plus monotonic pts and packet crcs over stereo and 5.1 clips, and fate-seek-extra-ac4 pins exact rebase pts over mixed seeks. Samples (clip-stereo.ac4, clip-51-real.ac4) reach fate-suite ac4/ through a separate samples request. The framecrc F suffixes and last-keyframe seek clamps take effect once Series D lands the parser (refs refreshed there). A presentation_version unary past 8 is definitively malformed, so it skips the TOC re-peek (single-probe) with one verbose note. Signed-off-by: Michael Rowlinson <[email protected]> --- libavcodec/ac4_toc.h | 678 ++++++++++++++++++++++++++++++++++++ libavformat/ac4dec.c | 290 +++++++++++++++ tests/fate/demux.mak | 4 + tests/fate/seek.mak | 2 + tests/ref/fate/ac4-demux | 8 + tests/ref/fate/ac4-demux-51 | 8 + tests/ref/seek/extra-ac4 | 40 +++ 7 files changed, 1030 insertions(+) create mode 100644 libavcodec/ac4_toc.h create mode 100644 tests/ref/fate/ac4-demux create mode 100644 tests/ref/fate/ac4-demux-51 create mode 100644 tests/ref/seek/extra-ac4 diff --git a/libavcodec/ac4_toc.h b/libavcodec/ac4_toc.h new file mode 100644 index 0000000..28b952d --- /dev/null +++ b/libavcodec/ac4_toc.h @@ -0,0 +1,678 @@ +/* + * AC-4 TOC walk shared by the raw demuxer and the frame parser + * Copyright (c) 2026 Michael Rowlinson + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file + * The single AC-4 table-of-contents reader for libavformat/libavcodec. + * + * Both the raw demuxer (libavformat/ac4dec.c, first-frame params plus + * timestamps) and the frame parser (libavcodec/ac4_parser.c, per-frame + * keyflags plus params) walk the TOC through this header, so the two + * can never drift apart. Rates are exact output-domain rationals + * (base sample frequency x sf_mult over the Table E.1 row rate, i.e. + * the N5 decoder output, never the internal spf x fps block grid). + * + * Return-code contract: 0 once the head is fully read (bed_ok reports + * whether the bed walk completed); AVERROR_INVALIDDATA on bit + * exhaustion, which may mean a truncated window; AVERROR_PATCHWELCOME + * for definitively-read unsupported shapes; AVERROR(EINVAL) for + * definitively-read malformed fields. Only INVALIDDATA may retry + * with a wider window. + */ + +#ifndef AVCODEC_AC4_TOC_H +#define AVCODEC_AC4_TOC_H + +#include <stdint.h> + +#include "libavutil/error.h" +#include "libavutil/mathematics.h" + +#include "get_bits.h" + +/* Frame-rate rows 0-12 as exact frame rates, num/den fps (Table E.1 + * frame_rate). Row 13 is free-running (no fixed rate). */ +static const int ff_ac4_toc_fps_num[13] = { + 24000, 24, 25, 30000, 30, 48000, 48, + 50, 60000, 60, 100, 120000, 120, +}; +static const int ff_ac4_toc_fps_den[13] = { + 1001, 1, 1, 1001, 1, 1001, 1, + 1, 1001, 1, 1, 1001, 1, +}; + +/* Exact output samples per frame as num/den (Table E.1 sample_delta; + * row 13 free-runs 2048 x sf_mult). fri is 0-13, fs 0/1, sf 1/2/4. */ +static inline void ff_ac4_toc_frame_len(int fri, int fs, int sf_mult, + int *num, int *den) +{ + if (fri == 13) { + *num = 2048 * sf_mult; + *den = 1; + } else { + int base = fs ? 48000 : 44100; + + *num = base * sf_mult * ff_ac4_toc_fps_den[fri]; + *den = ff_ac4_toc_fps_num[fri]; + } +} + +/* Nominal output pts (in output samples) of frame number f: absolute + * per-frame rounding, so period sums stay exact and no drift + * accumulates. This is the nominal (unlocked) phase, not the + * sequence_counter-locked Table 70 pattern, so single 1001-row frame + * counts may differ by one sample from a locked decoder on some + * frames of each period. */ +static inline int64_t ff_ac4_toc_frame_pts(int num, int den, int64_t f) +{ + return av_rescale(f, num, den); +} + +static inline int ff_ac4_toc_frame_dur(int num, int den, int64_t f) +{ + return (int) (ff_ac4_toc_frame_pts(num, den, f + 1) - + ff_ac4_toc_frame_pts(num, den, f)); +} + +typedef struct FFAC4TOC { + int head_ok; /* head parsed and gated */ + int bed_ok; /* bed walk completed */ + int ig; /* b_iframe_global */ + int rate; /* frame_rate_index 0-13 */ + int fs; /* fs_index: 0 = 44.1 kHz base, 1 = 48 kHz base */ + int sf_mult; /* substream sample-rate multiplier 1/2/4 */ + int channels; /* bed channel count (IMS presented, see below) */ + int tentative; /* cm >= 511 tentative 24-channel layout */ +} FFAC4TOC; + +typedef struct FFAC4TocReader { + GetBitContext gb; + int err; +} FFAC4TocReader; + +static inline int ff_ac4_toc_get(FFAC4TocReader *r, int n, unsigned *val) +{ + if (r->err) + return r->err; + if (n < 1 || n > 25 || get_bits_left(&r->gb) < n) { + r->err = AVERROR_INVALIDDATA; + return r->err; + } + *val = get_bits(&r->gb, n); + return 0; +} + +static inline int ff_ac4_toc_skip(FFAC4TocReader *r, int n) +{ + unsigned val; + + if (r->err) + return r->err; + if (n < 0) { + r->err = AVERROR(EINVAL); + return r->err; + } + while (n > 0) { + int k = n > 25 ? 25 : n; + + if (ff_ac4_toc_get(r, k, &val) < 0) + return r->err; + n -= k; + } + return 0; +} + +/* variable_bits(n): n-bit groups plus a more bit; each continuation + * maps value to (value + 1) << n before adding the next group. */ +static inline int ff_ac4_toc_varbits(FFAC4TocReader *r, int n, unsigned *val) +{ + unsigned v = 0; + + for (int i = 0; i < 8 && !r->err; i++) { + unsigned more; + + if (ff_ac4_toc_get(r, n, &more) < 0) + return r->err; + v += more; + if (v > 0xFFFFFF) { + r->err = AVERROR(EINVAL); + return r->err; + } + if (ff_ac4_toc_get(r, 1, &more) < 0) + return r->err; + if (!more) { + *val = v; + return 0; + } + v = (v + 1) << n; + } + if (!r->err) + r->err = AVERROR(EINVAL); + return r->err; +} + +/* presentation_version: count of leading one bits. Versions past 8 + * are definitively malformed (9 one-bits already read). */ +static inline int ff_ac4_toc_unary(FFAC4TocReader *r, unsigned *val) +{ + unsigned v = 0; + + for (;;) { + unsigned b; + + if (ff_ac4_toc_get(r, 1, &b) < 0) + return r->err; + if (!b) { + *val = v; + return 0; + } + if (++v > 8) { + r->err = AVERROR(EINVAL); + return r->err; + } + } +} + +static inline int ff_ac4_toc_substream_index(FFAC4TocReader *r) +{ + unsigned si, t; + + if (ff_ac4_toc_get(r, 2, &si) < 0) + return r->err; + if (si == 3 && ff_ac4_toc_varbits(r, 2, &t) < 0) + return r->err; + return 0; +} + +static inline int ff_ac4_toc_emdf(FFAC4TocReader *r) +{ + unsigned v, k, b_si, lp, ls, t, skip = 0; + + if (ff_ac4_toc_get(r, 2, &v) < 0) + return r->err; + if (v == 3 && ff_ac4_toc_varbits(r, 2, &t) < 0) + return r->err; + if (ff_ac4_toc_get(r, 3, &k) < 0) + return r->err; + if (k == 7 && ff_ac4_toc_varbits(r, 3, &t) < 0) + return r->err; + if (ff_ac4_toc_get(r, 1, &b_si) < 0) + return r->err; + if (b_si && ff_ac4_toc_substream_index(r) < 0) + return r->err; + if (ff_ac4_toc_get(r, 2, &lp) < 0 || + ff_ac4_toc_get(r, 2, &ls) < 0) + return r->err; + if (lp > 0) + skip += 1u << (2 * (lp - 1)); + if (ls > 0) + skip += 1u << (2 * (ls - 1)); + return ff_ac4_toc_skip(r, skip * 8); +} + +/* frame_rate_multiply_info: bit shape depends on the rate row. The + * factor value only keeps the walk aligned (frame_rate_fractions + * below reads it); nothing params need follows from it. */ +static inline int ff_ac4_toc_factor(FFAC4TocReader *r, int rate, + unsigned *factor) +{ + unsigned bm, mb; + + *factor = 1; + if (rate == 2 || rate == 3 || rate == 4) { + if (ff_ac4_toc_get(r, 1, &bm) < 0) + return r->err; + if (bm) { + if (ff_ac4_toc_get(r, 1, &mb) < 0) + return r->err; + *factor = mb ? 4 : 2; + } + } else if (rate <= 1 || (rate >= 7 && rate <= 9)) { + if (ff_ac4_toc_get(r, 1, &bm) < 0) + return r->err; + if (bm) + *factor = 2; + } + return 0; +} + +static inline int ff_ac4_toc_fractions(FFAC4TocReader *r, int rate, + unsigned factor) +{ + unsigned t; + + if (rate >= 5 && rate <= 9 && factor == 1) { + return ff_ac4_toc_get(r, 1, &t); + } else if (rate >= 10 && rate <= 12) { + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + if (t && ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + } + return 0; +} + +/* channel_mode prefix walk 1/2/4/7/8/9 bits with the all-ones escape. + * The 7-bit values 126/127 continue into 8 bits, 254/255 into 9; only + * 511 escapes into varbits. Value 510 is terminal but unmapped. */ +static inline int ff_ac4_toc_channel_mode(FFAC4TocReader *r, unsigned *cm) +{ + unsigned v, t; + + if (ff_ac4_toc_get(r, 1, &v) < 0) + return r->err; + if (!v) { + *cm = 0; + return 0; + } + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + v = (v << 1) | t; + if (v == 2) { + *cm = 2; + return 0; + } + if (ff_ac4_toc_get(r, 2, &t) < 0) + return r->err; + v = (v << 2) | t; + if (v >= 12 && v <= 14) { + *cm = v; + return 0; + } + if (ff_ac4_toc_get(r, 3, &t) < 0) + return r->err; + v = (v << 3) | t; + if (v < 126 || v > 127) { + *cm = v; + return 0; + } + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + v = (v << 1) | t; + if (v < 254 || v > 255) { + *cm = v; + return 0; + } + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + v = (v << 1) | t; + if (v != 511) { + *cm = v; + return 0; + } + if (ff_ac4_toc_varbits(r, 2, &t) < 0) + return r->err; + *cm = v + t; + return 0; +} + +typedef struct FFAC4TocHead { + int bv; /* bitstream_version */ + int fs; /* fs_index */ + int rate; /* frame_rate_index */ + int ig; /* b_iframe_global */ + int n_pres; /* presentation count */ +} FFAC4TocHead; + +/* TOC head through the program-id block. */ +static inline int ff_ac4_toc_head(FFAC4TocReader *r, FFAC4TocHead *h) +{ + unsigned bv, t, br; + + if (ff_ac4_toc_get(r, 2, &bv) < 0) + return r->err; + if (bv == 3) { + if (ff_ac4_toc_varbits(r, 2, &t) < 0) + return r->err; + bv += t; + } + if (bv > 2) { + r->err = AVERROR_PATCHWELCOME; + return r->err; + } + if (ff_ac4_toc_skip(r, 10) < 0) /* sequence_counter: ignored */ + return r->err; + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + if (t) { + if (ff_ac4_toc_get(r, 3, &br) < 0) + return r->err; + if (br > 0 && ff_ac4_toc_skip(r, 2) < 0) /* br_code/reserved */ + return r->err; + } + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + h->fs = t; + if (ff_ac4_toc_get(r, 4, &t) < 0) + return r->err; + if (t >= 14) { + r->err = AVERROR(EINVAL); + return r->err; + } + h->rate = t; + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + h->ig = t; + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + if (t) { + h->n_pres = 1; + } else if (ff_ac4_toc_get(r, 1, &t) < 0) { + return r->err; + } else if (t) { + if (ff_ac4_toc_varbits(r, 2, &t) < 0) + return r->err; + if (t + 2 > 64) { + r->err = AVERROR(EINVAL); + return r->err; + } + h->n_pres = t + 2; + } else { + h->n_pres = 0; + } + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + if (t) { + if (ff_ac4_toc_get(r, 5, &t) < 0) + return r->err; + if (t == 31 && ff_ac4_toc_varbits(r, 3, &t) < 0) + return r->err; + } + h->bv = bv; + if (bv == 2) { + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + if (t) { + if (ff_ac4_toc_skip(r, 16) < 0) + return r->err; + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + if (t && ff_ac4_toc_skip(r, 128) < 0) + return r->err; + } + } + return 0; +} + +/* One v1 presentation record. Records version/group for presentation 0 + * and skips the rest. Multi-group records bail: resolving them needs + * skip walks with no wire validation. */ +static inline int ff_ac4_toc_pres_v1(FFAC4TocReader *r, + const FFAC4TocHead *h, + unsigned *pver_out, unsigned *gi_out) +{ + unsigned single, pver, t, factor, gi, b_filter, add_emdf, n; + + if (ff_ac4_toc_get(r, 1, &single) < 0) + return r->err; + if (!single) { + r->err = AVERROR_PATCHWELCOME; + return r->err; + } + if (ff_ac4_toc_unary(r, &pver) < 0) + return r->err; + if (ff_ac4_toc_skip(r, 3) < 0) /* md_compat */ + return r->err; + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + if (t && ff_ac4_toc_varbits(r, 2, &t) < 0) + return r->err; + if (ff_ac4_toc_factor(r, h->rate, &factor) < 0) + return r->err; + if (ff_ac4_toc_fractions(r, h->rate, factor) < 0) + return r->err; + if (ff_ac4_toc_emdf(r) < 0) + return r->err; + if (ff_ac4_toc_get(r, 1, &b_filter) < 0) + return r->err; + if (b_filter && ff_ac4_toc_skip(r, 1) < 0) + return r->err; + if (ff_ac4_toc_get(r, 3, &gi) < 0) + return r->err; + if (gi == 7) { + if (ff_ac4_toc_varbits(r, 2, &t) < 0) + return r->err; + gi += t; + } + if (ff_ac4_toc_skip(r, 1) < 0) /* b_pre_virtualized */ + return r->err; + if (ff_ac4_toc_get(r, 1, &add_emdf) < 0) + return r->err; + if (ff_ac4_toc_skip(r, 2) < 0) /* b_alternative + b_pres_ndot */ + return r->err; + if (ff_ac4_toc_substream_index(r) < 0) + return r->err; + if (add_emdf) { + if (ff_ac4_toc_get(r, 2, &n) < 0) + return r->err; + if (!n) { + if (ff_ac4_toc_varbits(r, 2, &t) < 0) + return r->err; + n = t + 4; + } + for (unsigned k = 0; k < n; k++) + if (ff_ac4_toc_emdf(r) < 0) + return r->err; + } + *pver_out = pver; + *gi_out = gi; + return 0; +} + +/* Bitstream version 2: presentation 0 selects group 0, whose first + * channel-coded element carries the bed mode. A group without a bed + * (AJOC/object only) stops the walk with params untouched. */ +static inline int ff_ac4_toc_bed_v2(FFAC4TocReader *r, + const FFAC4TocHead *h, + unsigned *cm_out, unsigned *sf_out, + unsigned *pver_out) +{ + unsigned pver = 0, gi = 0, dummy_p, dummy_g, t; + + if (h->n_pres < 1) { + r->err = AVERROR(EINVAL); + return r->err; + } + for (int i = 0; i < h->n_pres; i++) { + if (!i) { + if (ff_ac4_toc_pres_v1(r, h, &pver, &gi) < 0) + return r->err; + } else if (ff_ac4_toc_pres_v1(r, h, &dummy_p, &dummy_g) < 0) { + return r->err; + } + } + if (gi) { + r->err = AVERROR_PATCHWELCOME; + return r->err; + } + /* b_substreams_present + b_hsf_ext */ + if (ff_ac4_toc_skip(r, 2) < 0) + return r->err; + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + if (!t) { + if (ff_ac4_toc_get(r, 2, &t) < 0) + return r->err; + if (t == 3 && ff_ac4_toc_varbits(r, 2, &t) < 0) + return r->err; + } + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + if (!t) { + r->err = AVERROR_PATCHWELCOME; /* no bed in this group */ + return r->err; + } + if (ff_ac4_toc_channel_mode(r, cm_out) < 0) + return r->err; + if (*cm_out == 252 || *cm_out == 253 || + *cm_out == 508 || *cm_out == 509) + if (ff_ac4_toc_skip(r, 4) < 0) /* immersive presence bits */ + return r->err; + *sf_out = 1; + if (h->fs) { + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + if (t) { + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + *sf_out = t ? 4 : 2; + } + } + *pver_out = pver; + return 0; +} + +/* Bitstream versions 0/1: presentation 0 carries an inline channel + * element, and nothing params need follows it, so later presentations + * need no walk. Zero wire vectors: spec positions, bail-safe. */ +static inline int ff_ac4_toc_bed_p1(FFAC4TocReader *r, + const FFAC4TocHead *h, + unsigned *cm_out, unsigned *sf_out, + unsigned *pver_out) +{ + unsigned single, config = 0, pver, t, factor; + + if (h->n_pres < 1) { + r->err = AVERROR(EINVAL); + return r->err; + } + if (ff_ac4_toc_get(r, 1, &single) < 0) + return r->err; + if (!single) { + if (ff_ac4_toc_get(r, 3, &config) < 0) + return r->err; + if (config == 7) { + if (ff_ac4_toc_varbits(r, 2, &t) < 0) + return r->err; + config += t; + } + if (config >= 6) { + r->err = AVERROR_PATCHWELCOME; + return r->err; + } + } + if (ff_ac4_toc_unary(r, &pver) < 0) + return r->err; + if (ff_ac4_toc_skip(r, 3) < 0) /* md_compat */ + return r->err; + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + if (t && ff_ac4_toc_varbits(r, 2, &t) < 0) + return r->err; + if (ff_ac4_toc_factor(r, h->rate, &factor) < 0) + return r->err; + if (ff_ac4_toc_emdf(r) < 0) + return r->err; + if (!single && ff_ac4_toc_skip(r, 1) < 0) /* b_hsf_ext */ + return r->err; + if (ff_ac4_toc_channel_mode(r, cm_out) < 0) + return r->err; + *sf_out = 1; + if (h->fs) { + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + if (t) { + if (ff_ac4_toc_get(r, 1, &t) < 0) + return r->err; + *sf_out = t ? 4 : 2; + } + } + *pver_out = pver; + return 0; +} + +/* channel_mode value to bed channel count; IMS pres_ver 2 reports the + * presented counts for cm 120/121 (5.1 IMS render / stereo core). + * Returns -1 for the unmapped 510 class. */ +static inline int ff_ac4_toc_channels(unsigned cm, unsigned pres_ver, + int *tentative) +{ + *tentative = 0; + if (pres_ver == 2 && (cm == 120 || cm == 121)) + return cm == 120 ? 6 : 2; + switch (cm) { + case 0: return 1; + case 2: return 2; + case 12: return 3; + case 13: return 5; + case 14: return 6; + case 120: + case 122: + case 124: return 7; + case 121: + case 123: + case 125: return 8; + case 252: return 11; + case 253: return 12; + case 508: return 13; + case 509: return 14; + } + if (cm >= 511) { + *tentative = 1; + return 24; + } + return -1; +} + +static inline int ff_ac4_toc_parse(const uint8_t *raw, int raw_len, + FFAC4TOC *toc) +{ + FFAC4TocReader r; + FFAC4TocHead h; + unsigned cm, sf, pver; + int nch, tentative = 0; + + toc->head_ok = 0; + toc->bed_ok = 0; + toc->ig = 0; + toc->rate = 0; + toc->fs = 0; + toc->channels = 0; + toc->sf_mult = 1; + toc->tentative = 0; + if (raw_len <= 0) + return AVERROR_INVALIDDATA; + if (init_get_bits8(&r.gb, raw, raw_len) < 0) + return AVERROR_INVALIDDATA; + r.err = 0; + if (ff_ac4_toc_head(&r, &h) < 0) + return r.err; + toc->head_ok = 1; + toc->ig = h.ig; + toc->rate = h.rate; + toc->fs = h.fs; + if (h.bv <= 1) { + if (ff_ac4_toc_bed_p1(&r, &h, &cm, &sf, &pver) < 0) + return r.err; + } else if (ff_ac4_toc_bed_v2(&r, &h, &cm, &sf, &pver) < 0) { + return r.err; + } + nch = ff_ac4_toc_channels(cm, pver, &tentative); + if (nch <= 0) + return AVERROR_PATCHWELCOME; + toc->bed_ok = 1; + toc->channels = nch; + toc->sf_mult = sf; + toc->tentative = tentative; + return 0; +} + +#endif /* AVCODEC_AC4_TOC_H */ diff --git a/libavformat/ac4dec.c b/libavformat/ac4dec.c index dc6638d..0da90d2 100644 --- a/libavformat/ac4dec.c +++ b/libavformat/ac4dec.c @@ -20,11 +20,219 @@ */ #include "libavutil/avassert.h" +#include "libavutil/channel_layout.h" #include "libavutil/crc.h" +#include "libavutil/mem.h" +#include "libavcodec/ac4_toc.h" #include "avformat.h" +#include "avio_internal.h" #include "demux.h" +#include "internal.h" #include "rawdec.h" +typedef struct AC4DemuxContext { + int64_t frame; /* emitted packet counter for timestamps */ + int frame_valid;/* frame counter known-good (0 after rebase miss) */ + int sample_rate;/* latched from first-frame TOC, 0 = unknown */ + int frame_dur_num;/* output samples per frame, exact rational */ + int frame_dur_den;/* (num/den; den != 1 on 1001-rate rows) */ + int64_t next_pos; /* expected offset of next sequential packet */ +} AC4DemuxContext; + +/* First-frame TOC peek: two stages, hard-bounded. D12 requires the peek + * stay bounded (never a full-frame read: raw frames run to 16 MB, and a + * slow-reject scan of such input is a known 120 s sink), while a valid + * 64-presentation TOC must never be truncated (the old 4096-byte window + * cut such TOCs, leaving params unset). + * + * Stage 1 reads up to AC4_TOC_PEEK_INIT bytes. Ordinary TOCs are tens of + * bytes, so every real sample parses here with zero extra IO. When the + * TOC walk exhausts a truncated stage-1 window, stage 2 re-peeks once up + * to AC4_TOC_PEEK_MAX bytes; semantic rejects never re-peek. + * + * Bound derivation: a minimal single-group presentation record is ~4 + * bytes, so 64 of them (the walker's enforced npres cap) fit in ~256 + * bytes. The only large per-record growth is additional EMDF info: each + * emdf_info carries at most 32 payload bytes (each 2-bit length field + * contributes at most 1 << (2 * (3 - 1)) = 16 bytes) plus an ~8-byte + * header, and valid presentations carry a handful. 64 KiB covers 64 + * presentations averaging 1 KiB each (~25 max-size EMDF records per + * presentation), far past any valid content, while staying 256x below + * the largest frame. Deliberately not covered: variable_bits abuse + * (n_add_emdf_substreams up to 1367 per presentation, ~3.5 MB across + * 64) fails loud at the cap instead of being chased. + * + * Truncation is impossible for 16-bit-sized frames (size <= 0xFFFE < + * 64 KiB, so stage 2 always covers the whole frame). Only 24-bit + * extended frames can overrun the cap; the walk then fails loud (a + * warning naming the bound, params unset), never silently truncated. */ +#define AC4_TOC_PEEK_INIT 4096 +#define AC4_TOC_PEEK_MAX (64 * 1024) + +/* Peek at the first sync frame, run the shared TOC walk over it, and + * latch sample_rate / frame duration / channel layout. Soft failures + * leave params unset; the decoder parses the TOC itself, so decode is + * unaffected. A hard failure (peek consumed bytes but the rewind + * failed) sets *desynced, and the caller must fail the open: mid-frame + * reads would emit garbage. The peek runs in two stages (see + * AC4_TOC_PEEK_INIT/MAX above): a small probe first, then one bounded + * re-peek when the walk exhausts a truncated window. Returns 0 with + * ctx + ch_layout filled, <0 otherwise. */ +static int ac4_parse_first_params(AVFormatContext *s, AVStream *st, + int *desynced) +{ + AC4DemuxContext *ctx = s->priv_data; + AVIOContext *pb = s->pb; + FFAC4TOC toc; + uint8_t *buf = NULL; + int64_t pos0 = avio_tell(pb); + unsigned sync, size, toread, hdr_len = 4, frame_bytes; + unsigned base_fs; + int ret; + int retried = 0; + + if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) && + ffio_ensure_seekback(pb, AC4_TOC_PEEK_INIT + 16) < 0) { + av_log(s, AV_LOG_VERBOSE, "ac4: no seekback for TOC peek\n"); + return AVERROR(ENOMEM); + } + + sync = avio_rb16(pb); + size = avio_rb16(pb); + if (size == 0xFFFF) { + size = avio_rb24(pb); + hdr_len = 7; + } + if (pb->error) + goto bail_io; + if (sync != 0xAC40 && sync != 0xAC41) { + av_log(s, AV_LOG_VERBOSE, "ac4: first frame has no sync word\n"); + goto bail_io; + } + if (!size) { + av_log(s, AV_LOG_VERBOSE, "ac4: bogus first-frame size\n"); + goto bail_io; + } + + toread = FFMIN(size, AC4_TOC_PEEK_INIT); + goto peek; + +retry: + /* The stage-1 window truncated the TOC: one bounded re-peek. The + * stage-1 read rewound to pos0, so skip the frame header and read + * the wider window from the same start. */ + av_freep(&buf); + toread = FFMIN(size, AC4_TOC_PEEK_MAX); + if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) && + ffio_ensure_seekback(pb, toread + 16) < 0) { + av_log(s, AV_LOG_WARNING, + "ac4: no seekback for %u-byte TOC re-peek\n", toread); + ret = AVERROR(ENOMEM); + goto out; + } + if (avio_skip(pb, hdr_len) != (int64_t)hdr_len) + goto bail_io; + +peek: + buf = av_malloc(toread + AV_INPUT_BUFFER_PADDING_SIZE); + if (!buf) + goto bail_io; + if (avio_read(pb, buf, toread) != (int)toread) + goto bail_io; + memset(buf + toread, 0, AV_INPUT_BUFFER_PADDING_SIZE); + if (avio_seek(pb, pos0, SEEK_SET) < 0) { + av_log(s, AV_LOG_WARNING, "ac4: TOC peek seek-back failed\n"); + *desynced = 1; + ret = AVERROR(EIO); + goto out; + } + /* TOC walk: the single shared reader (libavcodec/ac4_toc.h), + * the same walk the frame parser runs per packet. Bit exhaustion + * may mean a truncated window (re-peek below); any other failure + * read definitive bits, so no wider window can help. */ + ret = ff_ac4_toc_parse(buf, toread, &toc); + if (ret == AVERROR_INVALIDDATA) + goto bail_bits; + if (ret < 0) { + av_log(s, AV_LOG_VERBOSE, "ac4: first-frame TOC unsupported\n"); + goto out; + } + + /* Output rate is base_samp_freq x sf_mult on every row: the decoder + * resamples its internal blocks (spf x fps grid, e.g. 1536 @29.97) + * to base-fs PCM (1601/1602 @48 kHz; TS 103 190-2 Sec. 5.11 Table 70), + * so the grid is not the output rate. Timestamps advance by exact + * output samples per frame (Table E.1 sample_delta); row 13 + * free-runs 2048-sample frames. Table E.1 reserves 44.1 kHz rows + * 0-12 (MP4 context) and Table 70/E.4 cover only the 48 kHz base, + * so raw-stream 44.1 kHz fixed-rate legality is unconfirmed in the + * 190-2 extract (needs 190-1); accepted here as the natural + * generalization. sf_mult is pres-0/group-0 only: mixed-sf_mult + * multi-group files would be misdescribed by the single rate. */ + base_fs = toc.fs ? 48000 : 44100; + ctx->sample_rate = base_fs * toc.sf_mult; + ff_ac4_toc_frame_len(toc.rate, toc.fs, toc.sf_mult, + &ctx->frame_dur_num, &ctx->frame_dur_den); + + switch (toc.channels) { + case 1: + st->codecpar->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_MONO; + break; + case 2: + st->codecpar->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_STEREO; + break; + case 6: + /* cm 14 assumed side-surround 5.1 (190-1 confirm pending). */ + st->codecpar->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_5POINT1; + break; + case 8: + st->codecpar->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_7POINT1; + break; + default: + /* Every other count stays unspecified with the count set. */ + st->codecpar->ch_layout.order = AV_CHANNEL_ORDER_UNSPEC; + st->codecpar->ch_layout.nb_channels = toc.channels; + break; + } + /* First-frame bitrate estimate (frames vary a little, so this is + * approximate) lets generic code derive duration; ffprobe showed + * N/A duration without it. */ + frame_bytes = hdr_len + size + (sync == 0xAC41 ? 2 : 0); + st->codecpar->bit_rate = av_rescale((int64_t)frame_bytes * 8 * + ctx->frame_dur_den, + ctx->sample_rate, + ctx->frame_dur_num); + ret = 0; + goto out; + +bail_bits: + /* The walk exhausted the window. Retry once with the wider window + * when this peek was truncated; a fully-read frame (toread == + * size) holds no more bits, so the TOC itself is short. */ + if (!retried && toread < size && toread < AC4_TOC_PEEK_MAX) { + retried = 1; + goto retry; + } + if (toread < size) + av_log(s, AV_LOG_WARNING, + "ac4: TOC exceeds %u-byte peek bound, params unset\n", + AC4_TOC_PEEK_MAX); + else + av_log(s, AV_LOG_VERBOSE, "ac4: first-frame TOC walk overran\n"); + ret = AVERROR_INVALIDDATA; + goto out; + +bail_io: + if (avio_tell(pb) != pos0 && avio_seek(pb, pos0, SEEK_SET) < 0) + *desynced = 1; + av_log(s, AV_LOG_VERBOSE, "ac4: first-frame peek failed\n"); + ret = AVERROR_INVALIDDATA; + +out: + av_free(buf); + return ret; +} + static int ac4_probe(const AVProbeData *p) { const uint8_t *buf = p->buf; @@ -58,7 +266,9 @@ static int ac4_probe(const AVProbeData *p) static int ac4_read_header(AVFormatContext *s) { + AC4DemuxContext *ctx = s->priv_data; AVStream *st; + int desynced = 0; st = avformat_new_stream(s, NULL); if (!st) @@ -66,12 +276,50 @@ static int ac4_read_header(AVFormatContext *s) st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_id = AV_CODEC_ID_AC4; + /* Bare packets, one raw frame each: the parser probes the TOC + * without rescanning (COMPLETE_FRAMES) for per-frame keyflags, + * durations, and params. Without it the packets still carry the + * demuxer-stamped timing. */ + ffstream(st)->need_parsing = AVSTREAM_PARSE_HEADERS; + + if (!ac4_parse_first_params(s, st, &desynced)) { + st->codecpar->sample_rate = ctx->sample_rate; + /* ch_layout set inside ac4_parse_first_params on success */ + avpriv_set_pts_info(st, 64, 1, ctx->sample_rate); + st->start_time = 0; + } else if (desynced) { + return AVERROR(EIO); + } + + /* The peek rewound to the first frame; reads start sequential. */ + ctx->next_pos = avio_tell(s->pb); + ctx->frame_valid = 1; return 0; } +/* Frame number for a packet position: 0 at BOF, otherwise from the + * generic index; -1 when the position was never visited. NOPTS index + * entries (added unconditionally by the generic layer) carry no + * timestamp and are skipped. */ +static int64_t ac4_frame_at_pos(AVFormatContext *s, int64_t pos) +{ + AC4DemuxContext *ctx = s->priv_data; + FFStream *sti = ffstream(s->streams[0]); + + if (!pos) + return 0; + for (int i = 0; i < sti->nb_index_entries; i++) { + int64_t ts = sti->index_entries[i].timestamp; + if (ts != AV_NOPTS_VALUE && sti->index_entries[i].pos == pos) + return av_rescale(ts, ctx->frame_dur_den, ctx->frame_dur_num); + } + return -1; +} + static int ac4_read_packet(AVFormatContext *s, AVPacket *pkt) { + AC4DemuxContext *ctx = s->priv_data; AVIOContext *pb = s->pb; int64_t pos; uint16_t sync; @@ -85,14 +333,55 @@ static int ac4_read_packet(AVFormatContext *s, AVPacket *pkt) size = avio_rb16(pb); if (size == 0xffff) size = avio_rb24(pb); + if (pb->eof_reached) + return AVERROR_EOF; + if (sync != 0xAC40 && sync != 0xAC41) + return AVERROR_INVALIDDATA; + if (!size) + return AVERROR_INVALIDDATA; + + if (ctx->sample_rate && pos != ctx->next_pos) { + /* Non-sequential read after a seek: rebase the frame counter + * so timestamps stay correct. On a rebase miss the position + * is unvisited and the counter is meaningless: flag unknown + * rather than stamping plausible-but-wrong timestamps. */ + int64_t f = ac4_frame_at_pos(s, pos); + if (f < 0) { + ctx->frame_valid = 0; + } else { + ctx->frame = f; + ctx->frame_valid = 1; + } + } ret = av_get_packet(pb, pkt, size); pkt->pos = pos; pkt->stream_index = 0; + if (ret >= 0) { + /* Whole sync frames; the frame parser clears this flag on + * non-iframe packets from b_iframe_global. */ + pkt->flags |= AV_PKT_FLAG_KEY; + if (ctx->sample_rate && ctx->frame_valid) { + pkt->pts = pkt->dts = + ff_ac4_toc_frame_pts(ctx->frame_dur_num, ctx->frame_dur_den, + ctx->frame); + pkt->duration = + ff_ac4_toc_frame_pts(ctx->frame_dur_num, ctx->frame_dur_den, + ctx->frame + 1) - pkt->pts; + ctx->frame++; + } else if (ctx->sample_rate) { + pkt->pts = pkt->dts = AV_NOPTS_VALUE; + pkt->duration = 0; + } + } + if (sync == 0xAC41) avio_skip(pb, 2); + if (ret >= 0) + ctx->next_pos = avio_tell(pb); + return ret; } @@ -104,4 +393,5 @@ const FFInputFormat ff_ac4_demuxer = { .read_probe = ac4_probe, .read_header = ac4_read_header, .read_packet = ac4_read_packet, + .priv_data_size = sizeof(AC4DemuxContext), }; diff --git a/tests/fate/demux.mak b/tests/fate/demux.mak index 44d9ab5..0da24db 100644 --- a/tests/fate/demux.mak +++ b/tests/fate/demux.mak @@ -13,6 +13,10 @@ fate-adts-noparse-demux: CMD = ffprobe_demux $(TARGET_SAMPLES)/aac/id3v1.aac -f FATE_SAMPLES_DEMUX-$(call FRAMECRC, AA,, SIPR_PARSER) += fate-aa-demux fate-aa-demux: CMD = framecrc -i $(TARGET_SAMPLES)/aa/bush.aa -c:a copy +FATE_SAMPLES_DEMUX-$(call FRAMECRC, AC4) += fate-ac4-demux fate-ac4-demux-51 +fate-ac4-demux: CMD = framecrc -i $(TARGET_SAMPLES)/ac4/clip-stereo.ac4 -c:a copy +fate-ac4-demux-51: CMD = framecrc -i $(TARGET_SAMPLES)/ac4/clip-51-real.ac4 -c:a copy + FATE_SAMPLES_DEMUX-$(call CRC, AEA) += fate-aea-demux fate-aea-demux: CMD = crc -i $(TARGET_SAMPLES)/aea/chirp.aea -c:a copy diff --git a/tests/fate/seek.mak b/tests/fate/seek.mak index fa57d60..45fa419 100644 --- a/tests/fate/seek.mak +++ b/tests/fate/seek.mak @@ -189,6 +189,7 @@ FATE_SEEK_EXTRA-$(call ALLYES, MOV_DEMUXER) += fate-seek-empty-edit-mp4 FATE_SEEK_EXTRA-$(call ALLYES, MOV_DEMUXER) += fate-seek-test-iibbibb-mp4 FATE_SEEK_EXTRA-$(call ALLYES, MOV_DEMUXER) += fate-seek-test-iibbibb-neg-ctts-mp4 FATE_SEEK_EXTRA-$(CONFIG_WAV_DEMUXER) += fate-seek-bad-avg-byterate +FATE_SEEK_EXTRA-$(CONFIG_AC4_DEMUXER) += fate-seek-extra-ac4 fate-seek-extra-mp3: CMD = run libavformat/tests/seek$(EXESUF) $(TARGET_SAMPLES)/gapless/gapless.mp3 -fastseek 1 fate-seek-bad-avg-byterate: CMD = run libavformat/tests/seek$(EXESUF) $(TARGET_SAMPLES)/wav/wrong-avg-byterate.wav -seekback 500 -stream_id 0 @@ -198,6 +199,7 @@ fate-seek-test-iibbibb-mp4: CMD = run libavformat/tests/seek$(EXESUF) $(TARGET_ fate-seek-test-iibbibb-neg-ctts-mp4: CMD = run libavformat/tests/seek$(EXESUF) $(TARGET_SAMPLES)/mov/test_iibbibb_neg_ctts.mp4 -duration 13 -frames 4 fate-seek-cache-pipe: CMD = cat $(SAMPLES)/gapless/gapless.mp3 | run libavformat/tests/seek$(EXESUF) cache:pipe:0 -read_ahead_limit -1 fate-seek-mkv-codec-delay: CMD = run libavformat/tests/seek$(EXESUF) $(TARGET_SAMPLES)/mkv/codec_delay_opus.mkv +fate-seek-extra-ac4: CMD = run libavformat/tests/seek$(EXESUF) $(TARGET_SAMPLES)/ac4/clip-stereo.ac4 # A master playlist with separate audio and video media playlists with different DTS. tests/data/hls-seek.m3u8: ffmpeg$(PROGSSUF)$(EXESUF) | tests/data diff --git a/tests/ref/fate/ac4-demux b/tests/ref/fate/ac4-demux new file mode 100644 index 0000000..530102b --- /dev/null +++ b/tests/ref/fate/ac4-demux @@ -0,0 +1,8 @@ +#tb 0: 1/48000 +#media_type 0: audio +#codec_id 0: ac4 +#sample_rate 0: 48000 +#channel_layout_name 0: stereo +0, 0, 0, 2048, 342, 0x23081287 +0, 2048, 2048, 2048, 341, 0xbad70aae +0, 4096, 4096, 2048, 341, 0x27346f7e diff --git a/tests/ref/fate/ac4-demux-51 b/tests/ref/fate/ac4-demux-51 new file mode 100644 index 0000000..c744cba --- /dev/null +++ b/tests/ref/fate/ac4-demux-51 @@ -0,0 +1,8 @@ +#tb 0: 1/48000 +#media_type 0: audio +#codec_id 0: ac4 +#sample_rate 0: 48000 +#channel_layout_name 0: 5.1(side) +0, 0, 0, 2048, 683, 0x9c591a26 +0, 2048, 2048, 2048, 682, 0x469a1126 +0, 4096, 4096, 2048, 683, 0xada5fdc8 diff --git a/tests/ref/seek/extra-ac4 b/tests/ref/seek/extra-ac4 new file mode 100644 index 0000000..08c9d1e --- /dev/null +++ b/tests/ref/seek/extra-ac4 @@ -0,0 +1,40 @@ +ret: 0 st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos: 0 size: 342 +ret: 0 st:-1 flags:0 ts:-1.000000 +ret: 0 st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos: 0 size: 342 +ret: 0 st:-1 flags:1 ts: 1.894167 +ret: 0 st: 0 flags:1 dts: 0.085333 pts: 0.085333 pos: 695 size: 341 +ret:-1 st: 0 flags:0 ts: 0.788333 +ret:-1 st: 0 flags:1 ts:-0.317500 +ret:-1 st:-1 flags:0 ts: 2.576668 +ret: 0 st:-1 flags:1 ts: 1.470835 +ret: 0 st: 0 flags:1 dts: 0.085333 pts: 0.085333 pos: 695 size: 341 +ret:-1 st: 0 flags:0 ts: 0.365000 +ret:-1 st: 0 flags:1 ts:-0.740833 +ret:-1 st:-1 flags:0 ts: 2.153336 +ret: 0 st:-1 flags:1 ts: 1.047503 +ret: 0 st: 0 flags:1 dts: 0.085333 pts: 0.085333 pos: 695 size: 341 +ret: 0 st: 0 flags:0 ts:-0.058333 +ret: 0 st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos: 0 size: 342 +ret: 0 st: 0 flags:1 ts: 2.835833 +ret: 0 st: 0 flags:1 dts: 0.085333 pts: 0.085333 pos: 695 size: 341 +ret:-1 st:-1 flags:0 ts: 1.730004 +ret: 0 st:-1 flags:1 ts: 0.624171 +ret: 0 st: 0 flags:1 dts: 0.085333 pts: 0.085333 pos: 695 size: 341 +ret: 0 st: 0 flags:0 ts:-0.481667 +ret: 0 st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos: 0 size: 342 +ret: 0 st: 0 flags:1 ts: 2.412500 +ret: 0 st: 0 flags:1 dts: 0.085333 pts: 0.085333 pos: 695 size: 341 +ret:-1 st:-1 flags:0 ts: 1.306672 +ret: 0 st:-1 flags:1 ts: 0.200839 +ret: 0 st: 0 flags:1 dts: 0.085333 pts: 0.085333 pos: 695 size: 341 +ret: 0 st: 0 flags:0 ts:-0.905000 +ret: 0 st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos: 0 size: 342 +ret: 0 st: 0 flags:1 ts: 1.989167 +ret: 0 st: 0 flags:1 dts: 0.085333 pts: 0.085333 pos: 695 size: 341 +ret:-1 st:-1 flags:0 ts: 0.883340 +ret:-1 st:-1 flags:1 ts:-0.222493 +ret:-1 st: 0 flags:0 ts: 2.671667 +ret: 0 st: 0 flags:1 ts: 1.565833 +ret: 0 st: 0 flags:1 dts: 0.085333 pts: 0.085333 pos: 695 size: 341 +ret:-1 st:-1 flags:0 ts: 0.460008 +ret:-1 st:-1 flags:1 ts:-0.645825 -- 2.56.0 _______________________________________________ ffmpeg-devel mailing list -- [email protected] To unsubscribe send an email to [email protected]
