diff --git a/CLAUDE.md b/CLAUDE.md index ba1a28ff..11d66394 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -891,6 +891,19 @@ the first one's effect. The same goes for `-af`: every audio filter is chosen in `AudioPlan::new` and each ffmpeg run gets exactly one `-af`; the encode itself never filters audio (`test_real_ffmpeg_builder_delegates_audio_to_audio_restoration`). +**A source's subtitles reach the encoder through an input of their own, +never the sound's (issue #266).** Between cues a sparse subtitle stream is +the output stream FFmpeg's scheduler waits for, so sharing input 1 let the +source's sound run ahead of the picture vspipe was still making, and the +muxer wrote it up to ~38 s ahead (players dropped the sound; a remux fixed +it). `pipeline_executor::subtitle_mapping` is the one decision: a second `-i` +of the source with input 1's own seek, last of the inputs, added only when +the probe finds a subtitle stream (a failed probe keeps Matroska's old +`1:s?`). Never `-max_interleave_delta 0` instead: it buffers the sound until +the next cue. Trimmed encodes were never affected (`-shortest`'s sync +queue). `integration_subtitle_interleave_test.dart` (heavy) measures the +file order (docs/reports/issue-266-subtitle-interleave). + **Nothing of unbounded length goes on a child process's command line.** Windows caps it at 32,767 characters and refuses to start the process (os error 206). The source's `comment` tag is the case that hit it (issue #138: AI diff --git a/Tests/TestResources/generate_sparse_subtitle_test.sh b/Tests/TestResources/generate_sparse_subtitle_test.sh new file mode 100755 index 00000000..44209392 --- /dev/null +++ b/Tests/TestResources/generate_sparse_subtitle_test.sh @@ -0,0 +1,44 @@ +#!/bin/bash +# Generate sparse_subs.mkv: a source with two subtitle cues 34 s apart. +# +# Why it exists: the encode used to take a source's subtitles from the same +# input as its sound. Between cues the subtitle stream is the one FFmpeg's +# scheduler holds everything else back for, so the source's sound ran ahead +# of the picture vspipe was still making, and once the muxer's queue spanned +# 10 s it wrote the sound out ahead of it: up to ~38 s of sound before the +# matching picture, which a player with a bounded read-ahead dropped +# (issue #266). The subtitles now come from an input of their own. +# integration_subtitle_interleave_test encodes this into MKV and MP4 and +# checks how far the sound runs ahead of the picture in the file. +# See docs/reports/issue-266-subtitle-interleave. +# +# Content: +# video testsrc2, 160x120, 25 fps, 40 s, H.264 (GOP 50) +# audio 40 s mono 48 kHz 440 Hz tone, AAC 64k +# subtitle SRT, two cues: 1.0-2.0 s "first", 35.0-36.0 s "second" +# +# Usage: ./generate_sparse_subtitle_test.sh [output_dir] [ffmpeg] + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +OUTPUT_DIR="${1:-$SCRIPT_DIR}" +FFMPEG="${2:-ffmpeg}" + +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT + +printf '1\n00:00:01,000 --> 00:00:02,000\nfirst\n\n2\n00:00:35,000 --> 00:00:36,000\nsecond\n' > "$TMP/cues.srt" + +"$FFMPEG" -v error -y \ + -f lavfi -i "testsrc2=size=160x120:rate=25:duration=40" \ + -f lavfi -i "sine=frequency=440:sample_rate=48000:duration=40" \ + -i "$TMP/cues.srt" \ + -map 0:v -map 1:a -map 2:s \ + -c:v libx264 -preset veryfast -crf 30 -g 50 -pix_fmt yuv420p \ + -c:a aac -b:a 64k -ac 1 \ + -c:s srt \ + -metadata:s:s:0 language=eng \ + "$OUTPUT_DIR/sparse_subs.mkv" + +echo "Wrote $OUTPUT_DIR/sparse_subs.mkv" diff --git a/Tests/TestResources/sparse_subs.mkv b/Tests/TestResources/sparse_subs.mkv new file mode 100644 index 00000000..1323e5eb Binary files /dev/null and b/Tests/TestResources/sparse_subs.mkv differ diff --git a/app/test/integration_subtitle_interleave_test.dart b/app/test/integration_subtitle_interleave_test.dart new file mode 100644 index 00000000..ddd81b8c --- /dev/null +++ b/app/test/integration_subtitle_interleave_test.dart @@ -0,0 +1,123 @@ +// Issue #266: a source with subtitles came out of a Passthrough encode with +// its sound written far ahead of its picture (~38 s in an MKV), and players +// dropped the sound in stretches; remuxing it fixed it. The subtitles shared +// the sound's input: between cues the sparse subtitle stream is the one +// FFmpeg's scheduler waits for, so the source's sound ran ahead of the +// picture vspipe was still making and the muxer flushed it out ahead. The +// subtitles now come from an input of their own (pipeline_executor.rs, +// `subtitle_mapping`). A trimmed encode was never affected (`-shortest`'s +// sync queue holds the streams together); it stays here to check that the +// subtitle input is seeked as the sound's. See +// docs/reports/issue-266-subtitle-interleave. +@Tags(['heavy']) +@Timeout(Duration(minutes: 10)) +library; + +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'package:uuid/uuid.dart'; + +import 'package:vapourbox/models/encoding_settings.dart'; +import 'package:vapourbox/models/processing_pipeline.dart'; +import 'package:vapourbox/models/qtgmc_parameters.dart'; +import 'package:vapourbox/models/video_job.dart'; + +import 'support/av_sync.dart'; +import 'support/worker_harness.dart'; + +String get _outDir => '${WorkerHarness.outputDir}/subtitle_interleave'; + +final _source = p.join(WorkerHarness.repoRoot, 'Tests', 'TestResources', 'sparse_subs.mkv'); +const _fps = 25.0; +const _frames = 1000; +const _off = QTGMCParameters(enabled: false); + +/// The most the sound may run ahead of the picture in file order. The fixed +/// encode measures ~0.04 s (the encoder's own delay); before the fix ~34 s. +const _maxLead = 1.0; + +VideoJob _job(String name, ContainerFormat container, {int? start, int? end}) => VideoJob( + id: const Uuid().v4(), + inputPath: _source, + outputPath: '$_outDir/$name.${container.extension}', + qtgmcParameters: _off, + processingPipeline: const ProcessingPipeline(deinterlace: _off), + encodingSettings: EncodingSettings( + codec: VideoCodec.h264, + container: container, + audioMode: AudioMode.passthrough, + ), + inputWidth: 160, + inputHeight: 120, + inputPixelFormat: 'yuv420p', + inputFrameRate: _fps, + startFrame: start, + endFrame: end, + totalFrames: start != null && end != null ? end - start + 1 : _frames, + ); + +/// Each cue's start time: the subtitle packets that carry text (mov_text +/// fills the gaps between cues with empty, 2-byte samples). +Future> _cues(String path) async { + final j = await WorkerHarness.ffprobeJson([ + '-v', 'error', '-select_streams', 's:0', '-show_entries', 'packet=pts_time,size', + '-of', 'json', path, + ]); + return [ + for (final pk in j['packets'] as List) + if (int.parse('${pk['size']}') > 2) double.parse('${pk['pts_time']}'), + ]; +} + +void main() { + setUpAll(() async { + await WorkerHarness.ensureReady(); + await Directory(_outDir).create(recursive: true); + expect(await File(_source).exists(), isTrue, + reason: 'missing $_source (Tests/TestResources/generate_sparse_subtitle_test.sh)'); + expect(await _cues(_source), [1.0, 35.0], reason: 'the fixture must have two cues 34 s apart'); + }); + + for (final container in [ContainerFormat.mkv, ContainerFormat.mp4]) { + final name = container.extension; + test('$name: the sound stays with the picture and the cues keep their times', () async { + final r = await WorkerHarness.runJob(_job('passthrough_$name', container).toJson(), + label: 'subtitle_interleave_$name', timeout: const Duration(minutes: 4)); + expect(r.success, isTrue, reason: r.error); + final out = r.outputPath!; + final lead = await soundLeadInFileOrder(out); + // ignore: avoid_print + print('$name: sound ahead of the picture in file order: ${lead.toStringAsFixed(3)} s'); + expect(lead, lessThan(_maxLead), + reason: '$name: the sound is stored ${lead.toStringAsFixed(2)} s ahead of its picture'); + final cues = await _cues(out); + expect(cues.length, 2, reason: '$name: both cues copied'); + expect(cues[0], closeTo(1.0, 0.01)); + expect(cues[1], closeTo(35.0, 0.01)); + }); + } + + test('mkv trimmed from 5 s: the second cue moves with the trim', () async { + final r = await WorkerHarness.runJob( + _job('passthrough_trim', ContainerFormat.mkv, start: 125, end: 999).toJson(), + label: 'subtitle_interleave_trim', timeout: const Duration(minutes: 4)); + expect(r.success, isTrue, reason: r.error); + final out = r.outputPath!; + final lead = await soundLeadInFileOrder(out); + // ignore: avoid_print + print('trimmed: sound ahead of the picture in file order: ${lead.toStringAsFixed(3)} s'); + expect(lead, lessThan(_maxLead)); + // A trimmed copy into MKV keeps the sound from the keyframe before the + // in-point and stores the picture that much later (task #24), so the + // cue is measured from the first picture. + final cues = await _cues(out); + final first = await WorkerHarness.ffprobeJson([ + '-v', 'error', '-select_streams', 'v:0', '-read_intervals', '%+#1', + '-show_entries', 'packet=pts_time', '-of', 'json', out, + ]); + final videoStart = double.parse('${(first['packets'] as List).first['pts_time']}'); + expect(cues.last - videoStart, closeTo(30.0, 0.02), reason: 'the 35 s cue, 5 s into the trim'); + }); +} diff --git a/app/test/support/av_sync.dart b/app/test/support/av_sync.dart index 79deecbe..5c26917e 100644 --- a/app/test/support/av_sync.dart +++ b/app/test/support/av_sync.dart @@ -242,3 +242,37 @@ Future halfPacket(String video) async { return longest / 2; } +/// How far the first audio stream runs ahead of the picture in the file's +/// byte order: the largest audio DTS less the DTS of the last video packet +/// stored before it, in seconds (issue #266). A player reads a file in that +/// order with a bounded read-ahead, so a large lead starves its sound while +/// it reads the picture that catches up. Measures the layout, not playback. +Future soundLeadInFileOrder(String path) async { + final j = await WorkerHarness.ffprobeJson([ + '-v', 'error', '-show_entries', 'packet=stream_index,dts_time,pts_time,pos', + '-show_entries', 'stream=index,codec_type', '-of', 'json', path, + ]); + final types = { + for (final s in j['streams'] as List) s['index'] as int: '${s['codec_type']}', + }; + final packets = [ + for (final pk in j['packets'] as List) + if (int.tryParse('${pk['pos']}') != null && + double.tryParse('${pk['dts_time'] ?? pk['pts_time']}') != null) + ( + pos: int.parse('${pk['pos']}'), + type: types[pk['stream_index']] ?? '', + t: double.parse('${pk['dts_time'] ?? pk['pts_time']}'), + ), + ]..sort((a, b) => a.pos.compareTo(b.pos)); + double? lastVideo; + var lead = double.negativeInfinity; + for (final pk in packets) { + if (pk.type == 'video') { + lastVideo = pk.t; + } else if (pk.type == 'audio' && lastVideo != null) { + lead = pk.t - lastVideo > lead ? pk.t - lastVideo : lead; + } + } + return lead; +} diff --git a/docs/ENGINEERING_NOTES.md b/docs/ENGINEERING_NOTES.md index 2ceace15..a88d1020 100644 --- a/docs/ENGINEERING_NOTES.md +++ b/docs/ENGINEERING_NOTES.md @@ -7181,3 +7181,32 @@ What it found beyond the steps: Limits stated in the report: synthetic noise and blur, three 60-frame clips, Apple Silicon only, PSNR (checked against crops). + +### A source's subtitles let its sound run 38 s ahead of the picture (issue #266, 2026-11-28) + +The report: on a Mac, an MKV made with Audio Passthrough lost its sound in +stretches, although the sound was all there; re-muxing with MKVToolNix fixed +it. So the packets were right and their placement in the file was wrong. The +encoder took the source's subtitles from the same input as its sound +(`-map 1:a? -map 1:s?`). FFmpeg's scheduler (7.0+) only holds back an input +that doesn't feed the output stream furthest behind, and between cues that +is the sparse subtitle stream. So the source input ran freely, its sound got +ahead of the picture vspipe was still making, and once the muxer's queue +spanned `max_interleave_delta` (10 s) it wrote the sound out ahead: ~38 s of +sound before the matching picture with cues 49 s apart (0.04 s without +subtitles), in MKV and MP4 alike. A player with a bounded read-ahead runs out +of sound while it reads the picture that catches up. + +The subtitles now come from a second `-i` of the source with input 1's own +seek, last of the inputs (`pipeline_executor::subtitle_mapping`); the sound's +input is then held to the picture's pace. Through the worker on a 40 s +fixture with cues 34 s apart: 22.7 s (MKV) and 23.3 s (MP4) ahead before, +0.10 s after. `-max_interleave_delta 0` gives the same layout by buffering +every sound packet until the next cue (265 MB against 83 MB for a 7.1 PCM +minute), so it was rejected. The source is probed first, so one without +subtitles is still read once; a failed probe keeps Matroska's old `1:s?`. +Trimmed encodes were never affected: `-shortest` runs the streams through a +sync queue (0.13 s before the fix). Only the layout was measured, on macOS +arm64; no player was tested. + +Report: [docs/reports/issue-266-subtitle-interleave](reports/issue-266-subtitle-interleave/index.html). diff --git a/docs/reports/README.md b/docs/reports/README.md index 263aed5c..23fbb3cb 100644 --- a/docs/reports/README.md +++ b/docs/reports/README.md @@ -66,6 +66,7 @@ to it. | Date | Report | Outcome | |---|---|---| +| 2026-11-28 | [Issue #266: a source's subtitles let its sound run 38 s ahead of the picture](issue-266-subtitle-interleave/index.html) | Fixed in the worker: an untrimmed Passthrough of a source with subtitles stored its sound up to ~38 s ahead of its picture (MKV and MP4), and players dropped the sound in stretches; a remux fixed it. The subtitles shared the sound's input, and a sparse subtitle stream is the one FFmpeg's scheduler waits for, so the sound ran ahead and the muxer flushed it past `max_interleave_delta`. Subtitles now come from a second input of the source (added only when it has any): through the worker 22.7 / 23.3 s → 0.10 s. `-max_interleave_delta 0` also fixes the layout but buffers the sound (265 vs 83 MB for a 7.1 PCM minute). Trimmed encodes were never affected (`-shortest`). Layout measured, no player tested; macOS arm64 only | | 2026-11-28 | [Issue #253: automatic white balance compiled an expression every frame](issue-253-auto-colour-per-frame-expr/index.html) | Fixed in the template: `_auto_white` returned a new expression from a FrameEval each frame, and on akarin (every bundle but macOS x64) that is an LLVM compile under the GIL, ~17 ms a frame on an M1. Now one akarin expression reads PlaneStats' means as frame properties; the FrameEval is only macOS x64's fallback. Filter alone at 706x480: ~60 → ~8,000 fps; the whole chain unchanged (10.8 → 10.9 fps) on a heavily loaded M1, where the other passes ran far below the old filter's serial ceiling. Identical at 8-12 bits; at 16 bits 0.16% of chroma planes one step apart (akarin reads properties as 32-bit floats). Automatic levels left alone: cheap already, and akarin's fast-math division misses .5 ties against std.Levels in 2% of (min, max) pairs | | 2026-11-28 | [Task #128: the BM3D smoke encode that outgrew the 300 s job limit](task-128-bm3d-heavy-test-time/index.html) | Fixed in the test: across 40 nightlies the 79-frame BM3D encode took 222–300+ s on macos-arm64 and up to 300+ s on the x64 Macs, and hit `runJob`'s default 300 s limit 9 times, all on Mac legs; Linux ≤ 232 s, Windows ≤ 190 s. Runner speed, not the deps. It now encodes 24 frames (radius 1 still has neighbours both sides) under an explicit 5 min job limit and asserts the count | | 2026-11-28 | [Issue #177: one Strength control for Noise Reduction and Sharpen](issue-177-strength-mapping/index.html) | Built: each simple-mode method has a Strength selector (Light / Medium / Strong / Very strong), Medium = the existing defaults, the rest measured (three clips, AddGrain noise sigma 2-9 and blur 0.5-1.6 px, luma PSNR against the clean original, ordered by cost on a clean picture). Found SMDegrain doing nothing at sigma 9 at any thSAD: havsfunc's thSCD1=400 makes every noisy frame a cut; 800 recovers 29.1 -> 36.8 dB, real cuts still found, now a parameter. MCTD's Sigma is inert (task #141); QTGMC built-in's default (EZDenoise 0) did nothing, now 5. aWarpSharp2 can't be judged by PSNR (a stated effect ladder instead). Synthetic noise, Apple Silicon only | diff --git a/docs/reports/issue-266-subtitle-interleave/data/probe_macos-arm64.txt b/docs/reports/issue-266-subtitle-interleave/data/probe_macos-arm64.txt new file mode 100644 index 00000000..e02dafac --- /dev/null +++ b/docs/reports/issue-266-subtitle-interleave/data/probe_macos-arm64.txt @@ -0,0 +1,7 @@ +ffmpeg version 9.0.2-https://www.martin-riedl.de Copyright (c) 2000-2026 the FFmpeg developers +no_subtitles lead 0.04 s peak RSS 30 MB +subtitles_today lead 38.10 s peak RSS 31 MB +subtitles_today_unthrottled lead 37.66 s peak RSS 57 MB +pcm71_today lead 37.91 s peak RSS 153 MB +pcm71_own_input lead 0.04 s peak RSS 83 MB +pcm71_mid0 lead 0.04 s peak RSS 265 MB diff --git a/docs/reports/issue-266-subtitle-interleave/index.html b/docs/reports/issue-266-subtitle-interleave/index.html new file mode 100644 index 00000000..a3c30ff4 --- /dev/null +++ b/docs/reports/issue-266-subtitle-interleave/index.html @@ -0,0 +1,104 @@ + + + + + +Subtitle interleave + + + +

A source's subtitles let its sound run 38 s ahead of the picture

+

GitHub issue #266 (task #142), 2026-11-28. Measured on an Apple M1 with the bundled FFmpeg 9.0.2 (martin-riedl build, deps 1.17.0-rc1 macOS arm64). The behaviour is FFmpeg's scheduler and muxer, not macOS's, so every platform's bundle should behave the same; only macOS arm64 was measured.

+ +

Outcome

+
    +
  • The report: on a Mac, an MKV made with Audio Passthrough had its sound "cut out completely in parts of the video". The sound was all there, and separating and re-muxing the streams with MKVToolNix fixed the file. So the packets and their times were right, and their placement in the file was wrong.
  • +
  • Cause: the encoder took the source's subtitles from the same input as its sound (-map 1:a? -map 1:s? -c:s copy). Between cues a sparse subtitle stream is the output stream furthest behind, and FFmpeg's scheduler (7.0+) only holds back inputs that don't feed that stream. So the source input was never held back, and its sound ran ahead of the picture vspipe was still making. Once the muxer's interleave queue spanned max_interleave_delta (10 s), FFmpeg wrote the sound out ahead. The MKV had long runs of sound followed by long runs of picture, up to ~38 s apart. A player that reads ahead a bounded amount runs out of sound while it reads through the picture. mkvmerge interleaves by timestamp, which is why a remux fixed it.
  • +
  • Fix (worker): subtitles come from an input of their own, a second -i of the source with input 1's own seek, added after every other input (pipeline_executor.rs, subtitle_mapping). The sound's input is then held to the picture's pace, and the subtitle input reads to its end at once (a few small packets). The source is probed first, so a source with no subtitle stream adds no input and is read once, as before. If the probe fails, Matroska keeps the old mapping from input 1 rather than lose the user's subtitles.
  • +
  • Through the worker (app/test/integration_subtitle_interleave_test.dart, a 40 s fixture with cues at 1 s and 35 s): an untrimmed encode stored the sound 22.66 s ahead in MKV and 23.3–23.4 s in MP4 before the fix, and 0.099 s in both after. The cues keep their times. Trimmed encodes were never affected (0.13 s before the fix): they end with -shortest, whose sync queue already holds the streams together.
  • +
  • Rejected: -max_interleave_delta 0 also gives a correct layout, but only by holding every sound packet in memory until the next cue arrives. The memory grows with the gap between cues and the sound's bitrate: 265 MB against 83 MB for a 7.1 PCM minute, and gigabytes for a lossless film soundtrack over a long gap with no cues.
  • +
+ +

The metric and its limits

+

scripts/lead.py sorts a file's packets by byte position and reports the largest amount by which an audio packet's DTS exceeds the DTS of the last video packet stored before it: how far the sound runs ahead of the picture in the order a player reads the file. Its limits:

+
    +
  • It measures the layout, not playback. No player was tested here, and the reporter's player and source are unknown. A large lead explains a dropout in a player with a bounded read-ahead; how much lead a given player tolerates was not measured.
  • +
  • About 0.04–0.1 s is the floor: x264's own delay (lookahead and B-frames) holds the picture back that much in any encode.
  • +
  • The sources are synthetic (testsrc2, a sine tone, SRT cues). A real source would differ in its bitrates, not in the mechanism.
  • +
+ +

FFmpeg alone

+

scripts/probe.sh builds the sources and runs the encoder in the worker's shape: a Y4M pipe (the source decoded, optionally throttled to twice real time by scripts/throttle.py to stand in for vspipe), x264, sound and subtitles copied. Output: data/probe_macos-arm64.txt. Peak RSS is the encoder's, from /usr/bin/time -l.

+ + + + + + + + +
Source and mappingPipeSound ahead of pictureEncoder peak RSS
60 s, AAC, no subtitles, today's mappingthrottled0.04 s30 MB
same + 2 SRT cues (1 s, 50 s), today's mappingthrottled38.10 s31 MB
sameunthrottled, x264 medium37.66 s57 MB
7.1 PCM s32 96 kHz + the cues, today's mappingthrottled37.91 s153 MB
↳ subtitles from their own input (the fix)throttled0.04 s83 MB
↳ -max_interleave_delta 0throttled0.04 s265 MB
+

The fault needs no throttling: vspipe, or even decoding and re-encoding the picture as in the unthrottled row, is always slower than demuxing the file. Without subtitles the sound input is held to the picture's pace and the layout is right; the lead is roughly the gap to the next cue.

+

A trimmed encode was also checked in the first look (-ss 5 on both source inputs, -shortest): 0.04 s with the subtitles on their own input. That says nothing about the fix on its own: through the worker, a trimmed encode was already fine before it (next section).

+ +

Through the worker

+

Tests/TestResources/generate_sparse_subtitle_test.sh writes sparse_subs.mkv: 160x120 testsrc2 at 25 fps, 40 s, H.264, mono AAC, SRT cues at 1 s and 35 s. integration_subtitle_interleave_test.dart (heavy) encodes it with Passthrough and x264, then checks the lead (under 1 s) and the cues:

+ + + + + +
CaseWorker before (main)Worker after
MKV, untrimmed22.66 s ahead0.099 s
MP4 (mov_text), untrimmed23.34 s, 23.41 s ahead (two runs)0.099 s
MKV, trimmed from 5 s0.128 s ahead; the 35 s cue at 30.0 s from the first picture0.168 s; the cue at 30.0 s
+

"Before" was the same test run against a worker built from main (the old binary). The leads are smaller than in the FFmpeg-only table because the fixture's cues are 34 s apart, not 49. A trimmed encode ends with -shortest, and FFmpeg then runs every stream through a sync queue that keeps them within a short span of each other, so the sound could not run ahead; the untrimmed encode has no such queue. The trimmed case stays in the test to check that the subtitle input's seek matches the sound's.

+ +

A correction made during the work

+

The first version of the trimmed check expected the second cue at 30.0 s on the file's own timeline, and it read 30.968 s, on the old and the new worker alike. That isn't an error in either. A trimmed copy into MKV keeps the sound from the keyframe before the in-point, and the output stores the picture that much later (task #24, CLAUDE.md "Source Frame Size"). Here the picture starts at 0.968 s, so the check now measures the cue from the first picture.

+ +

The change

+
// before (one input, sound and subtitles)
+-ss T -i source.mkv ... -map 1:a? -map 1:s? -c:s copy
+
+// after (the source's subtitles from an input of their own, last)
+-ss T -i source.mkv ... -ss T -i source.mkv -progress ... -map 1:a? -map N:s? -c:s copy
+
    +
  • The decision is subtitle_mapping(form, embed_pending, codecs, input), a pure function that is unit-tested. It covers Matroska (copy), MP4/MOV (text codecs only, as mov_text, as before), AVI (none), no subtitle stream (no input), and a failed probe (Matroska's old 1:s?, MP4 none).
  • +
  • The subtitle input reuses the exact argument list input 1 got (source_audio_input_seek). An encoder priming changes that seek only for Convert into AVI, which takes no subtitles.
  • +
  • Chapters and global tags are unchanged: chapters still come from the first input that has them (input 1), and tags from the metadata file (input 2).
  • +
+ +

Decisions

+
    +
  • Own input, not -max_interleave_delta 0: the same layout without buffering the sound (memory above).
  • +
  • Probe first, add the input only for a source with subtitles: otherwise every Matroska encode would read its source twice, which costs on a network share. The probe is the one the MP4 path already ran.
  • +
  • A failed probe keeps the old mapping for Matroska: a layout fault is better than silently dropping the user's subtitle tracks.
  • +
  • Not added to the output conformance matrix: the matrix's sources have no subtitles. A subtitle source class there would multiply its cases for one property this standalone test covers.
  • +
+ +

Not tested

+
    +
  • Playback in any player (VLC, IINA, Infuse), and the reporter's own source.
  • +
  • Windows and Linux bundles (same FFmpeg 9.0 series, BtbN builds).
  • +
  • Image subtitles (PGS, VobSub) into Matroska through the worker; the mapping is the same N:s?.
  • +
  • The subtitle mux post-pass (an embedded transcript) is a stream copy of a finished file with no slow input, and was not re-measured.
  • +
+ +

Reproducing

+
docs/reports/issue-266-subtitle-interleave/scripts/probe.sh deps/macos-arm64
+Tests/TestResources/generate_sparse_subtitle_test.sh Tests/TestResources deps/macos-arm64/ffmpeg/ffmpeg
+(cd worker && cargo build)
+(cd app && flutter test --tags heavy test/integration_subtitle_interleave_test.dart)
+ + diff --git a/docs/reports/issue-266-subtitle-interleave/scripts/lead.py b/docs/reports/issue-266-subtitle-interleave/scripts/lead.py new file mode 100755 index 00000000..5d5b12ee --- /dev/null +++ b/docs/reports/issue-266-subtitle-interleave/scripts/lead.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +"""How far the first audio stream runs ahead of the picture in a file's byte +order: the largest audio DTS less the DTS of the last video packet stored +before it (issue #266). Usage: lead.py """ +import json +import subprocess +import sys + +ffprobe, path = sys.argv[1], sys.argv[2] +j = json.loads(subprocess.check_output([ + ffprobe, '-v', 'error', + '-show_entries', 'packet=stream_index,pts_time,dts_time,pos', + '-show_entries', 'stream=index,codec_type', '-of', 'json', path])) +types = {s['index']: s['codec_type'] for s in j['streams']} +packets = sorted((p for p in j['packets'] if 'pos' in p), key=lambda p: int(p['pos'])) +last_video, lead = None, float('-inf') +for p in packets: + t = float(p.get('dts_time') or p.get('pts_time')) + kind = types[p['stream_index']] + if kind == 'video': + last_video = t + elif kind == 'audio' and last_video is not None: + lead = max(lead, t - last_video) +print(f'{lead:.2f}') diff --git a/docs/reports/issue-266-subtitle-interleave/scripts/probe.sh b/docs/reports/issue-266-subtitle-interleave/scripts/probe.sh new file mode 100755 index 00000000..6517e12f --- /dev/null +++ b/docs/reports/issue-266-subtitle-interleave/scripts/probe.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# The encoder's subtitle mapping, measured with the bundle's FFmpeg alone +# (issue #266): how far the sound runs ahead of the picture in file order, +# and the encoder's peak memory, for today's mapping and two fixes. +# +# Usage: scripts/probe.sh [deps/ dir] +# Scratch files go to $ISSUE266_SCRATCH (default: a new temporary directory). +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +REPO="$(cd "$HERE/../../../.." && pwd)" +DEPS="${1:-$REPO/deps/macos-arm64}" +FF="$DEPS/ffmpeg/ffmpeg" +FP="$DEPS/ffmpeg/ffprobe" +W="${ISSUE266_SCRATCH:-$(mktemp -d)}" +mkdir -p "$W" +cd "$W" +"$FF" -version | head -1 + +printf '1\n00:00:01,000 --> 00:00:02,000\nhello\n\n2\n00:00:50,000 --> 00:00:51,000\nbye\n' > s.srt +"$FF" -v error -f lavfi -i testsrc2=s=320x240:r=25:d=60 -f lavfi -i "sine=f=440:d=60:sample_rate=48000" \ + -c:v libx264 -preset ultrafast -c:a aac -y src_nosub.mkv +"$FF" -v error -i src_nosub.mkv -i s.srt -map 0 -map 1 -c copy -y src_sub.mkv +# 7.1 PCM s32 96 kHz: a sound heavy enough for buffering to show in memory. +"$FF" -v error -i src_sub.mkv -f lavfi -i "sine=f=440:d=60:sample_rate=96000" \ + -filter_complex "[1:a]pan=7.1|c0=c0|c1=c0|c2=c0|c3=c0|c4=c0|c5=c0|c6=c0|c7=c0[a]" \ + -map 0:v -map "[a]" -map 0:s -c:v copy -c:s copy -c:a pcm_s32le -y src_fat.mkv + +# Bytes per second of 320x240 4:2:0 at 50 fps: a pipe at twice real time. +RATE=5760000 + +# encode +encode() { + local name=$1 src=$2 throttle=$3 preset=$4; shift 4 + local rss + if [ "$throttle" = yes ]; then + rss=$( { "$FF" -v error -i "$src" -map 0:v -f yuv4mpegpipe - | python3 "$HERE/throttle.py" $RATE | + /usr/bin/time -l "$FF" -v error -f yuv4mpegpipe -i - "$@" -c:a copy -c:s copy \ + -c:v libx264 -preset "$preset" -y "$name.mkv"; } 2>&1 | awk '/maximum resident/ {print $1}') + else + rss=$( { "$FF" -v error -i "$src" -map 0:v -f yuv4mpegpipe - | + /usr/bin/time -l "$FF" -v error -f yuv4mpegpipe -i - "$@" -c:a copy -c:s copy \ + -c:v libx264 -preset "$preset" -y "$name.mkv"; } 2>&1 | awk '/maximum resident/ {print $1}') + fi + printf '%-28s lead %6s s peak RSS %4d MB\n' "$name" "$(python3 "$HERE/lead.py" "$FP" "$name.mkv")" $((rss / 1048576)) +} + +encode no_subtitles src_nosub.mkv yes ultrafast -i src_nosub.mkv -map 0:v -map '1:a?' -map '1:s?' +encode subtitles_today src_sub.mkv yes ultrafast -i src_sub.mkv -map 0:v -map '1:a?' -map '1:s?' +encode subtitles_today_unthrottled src_sub.mkv no medium -i src_sub.mkv -map 0:v -map '1:a?' -map '1:s?' +encode pcm71_today src_fat.mkv yes ultrafast -i src_fat.mkv -map 0:v -map '1:a?' -map '1:s?' +encode pcm71_own_input src_fat.mkv yes ultrafast -i src_fat.mkv -i src_fat.mkv -map 0:v -map '1:a?' -map '2:s?' +encode pcm71_mid0 src_fat.mkv yes ultrafast -i src_fat.mkv -map 0:v -map '1:a?' -map '1:s?' -max_interleave_delta 0 diff --git a/docs/reports/issue-266-subtitle-interleave/scripts/throttle.py b/docs/reports/issue-266-subtitle-interleave/scripts/throttle.py new file mode 100755 index 00000000..f877f3f9 --- /dev/null +++ b/docs/reports/issue-266-subtitle-interleave/scripts/throttle.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +"""Copy stdin to stdout at no more than , standing in for +a vspipe slower than the decoder. Usage: throttle.py """ +import sys +import time + +rate = float(sys.argv[1]) +src, dst = sys.stdin.buffer, sys.stdout.buffer +t0, n = time.time(), 0 +try: + while True: + b = src.read(65536) + if not b: + break + dst.write(b) + n += len(b) + ahead = n / rate - (time.time() - t0) + if ahead > 0: + time.sleep(ahead) +except BrokenPipeError: + pass diff --git a/worker/src/pipeline_executor.rs b/worker/src/pipeline_executor.rs index 09e0fdd7..c12a2602 100644 --- a/worker/src/pipeline_executor.rs +++ b/worker/src/pipeline_executor.rs @@ -1358,7 +1358,8 @@ impl PipelineExecutor { // doesn't read the entire audio track (which hangs for small segments of // large files). One decision with the video delay below and Audio // Restoration's window: `VideoJob::source_audio_start`. - args.extend(source_audio_input_seek(job, self.encoder_priming.as_ref())); + let source_seek = source_audio_input_seek(job, self.encoder_priming.as_ref()); + args.extend(source_seek.iter().cloned()); args.extend(["-i".to_string(), job.input_path.clone()]); // Input 2: the output's comment, as an FFMETADATA file (issue #138) @@ -1378,47 +1379,41 @@ impl PipelineExecutor { let cut = sound_cut_input(self.sound_cut.as_ref(), self.sound_copy.as_ref(), self.restored_audio.is_some()); args.extend(sound_cut_input_args(job, self.sound_copy.as_ref(), self.sound_cut.as_ref())); + // Last input: the source again, for its subtitle streams only, seeked + // exactly as input 1 (issue #266). A sparse subtitle stream sharing + // the sound's input let the sound run ahead of the encoded picture + // and be written up to ~40 s ahead of it (see `subtitle_mapping`). + let subtitle_embed_pending = job.subtitle_settings.as_ref() + .is_some_and(|s| s.enabled && !matches!(s.output, SubtitleOutput::SrtFile)); + let subtitle_form = settings.container.traits().subtitles; + let subtitle_codecs = if subtitle_mapping_probes(subtitle_form, subtitle_embed_pending) { + self.probe_subtitle_codecs(&job.input_path) + } else { + None + }; + let subtitles = subtitle_mapping( + subtitle_form, + subtitle_embed_pending, + subtitle_codecs.as_deref(), + input_count(&args), + ); + if subtitles.own_input { + args.extend(subtitle_input_args(job, &source_seek)); + } + // Progress output to a temp file (avoids Windows pipe buffering delay) args.extend(["-progress".to_string(), progress_file.to_string_lossy().to_string()]); - // Map streams: video from input 0 (processed), audio and subtitles from input 1 (original) + // Map streams: video from input 0 (processed), audio from input 1 + // (original), subtitles from their own input of the source args.extend(["-map".to_string(), "0:v".to_string()]); // Video from Y4M pipe // Audio from the original (every stream, `1:a?`), or — when audio // restoration rendered a track — that track (input 3) first, then the // source's other audio streams. One decision site: audio_restoration. args.extend(audio_restoration::encode_map_args(settings, self.restored_audio.as_ref(), 3, sound, cut)); - // Preserve existing subtitle streams from source (? = optional, no error if none) - let subtitle_embed_pending = job.subtitle_settings.as_ref() - .is_some_and(|s| s.enabled && !matches!(s.output, SubtitleOutput::SrtFile)); - match settings.container.traits().subtitles { - SubtitleForm::Copy => { - args.extend(["-map".to_string(), "1:s?".to_string()]); - args.extend(["-c:s".to_string(), "copy".to_string()]); - } - SubtitleForm::MovText if !subtitle_embed_pending => { - // mov_text only holds text subtitles. Image-based subs (PGS/VobSub - // from DVD/Blu-ray rips) cannot be transcoded to mov_text — ffmpeg - // does NOT skip them, it aborts the whole encode with - // "Subtitle encoding currently only possible from text to text..." - // (exit -22). So probe the source and map only text-based streams. - if let Some(codecs) = self.probe_subtitle_codecs(&job.input_path) { - let mut mapped_any = false; - for (rel_idx, codec) in codecs.iter().enumerate() { - if Self::is_text_subtitle(codec) { - args.extend(["-map".to_string(), format!("1:s:{}", rel_idx)]); - mapped_any = true; - } - } - if mapped_any { - args.extend(["-c:s".to_string(), "mov_text".to_string()]); - } - } - // If probing fails, map no subtitles — a missing subtitle track must - // never fail the encode. - } - _ => {} // AVI: no subtitle stream - } + // Subtitles: from their own input (above), or none. + args.extend(subtitles.args); // Video codec args.extend(["-c:v".to_string(), settings.codec.ffmpeg_codec().to_string()]); @@ -2387,6 +2382,95 @@ pub fn sound_copy_input_args(job: &VideoJob, copy: Option<&SoundCopy>, priming: args } +/// The number of inputs an ffmpeg argument list declares so far: the index +/// the next `-i` will have. +fn input_count(args: &[String]) -> usize { + args.iter().filter(|a| *a == "-i").count() +} + +/// The output's subtitle streams, and whether they need an input of their own. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SubtitleMapping { + /// The maps read a second input of the source, added after every other + /// input ([`subtitle_input_args`]). + pub own_input: bool, + /// `-map …` and `-c:s …`. + pub args: Vec, +} + +/// Whether [`subtitle_mapping`] needs the source's subtitle codecs probed. +pub fn subtitle_mapping_probes(form: SubtitleForm, embed_pending: bool) -> bool { + match form { + SubtitleForm::Copy => true, + SubtitleForm::MovText => !embed_pending, + SubtitleForm::None => false, + } +} + +/// Which subtitle streams the encode copies, and from where (issue #266). +/// +/// **Never from the input the sound comes from.** FFmpeg's scheduler lets an +/// input run only while it feeds the output stream furthest behind, and a +/// sparse subtitle stream is that stream between cues. Sharing input 1 with +/// the sound let the source's sound run ahead of the picture (which vspipe +/// makes far slower than the file demuxes), and once the muxer's queue +/// spanned `max_interleave_delta` (10 s) it wrote the sound out ahead: an +/// MKV with ~38 s of sound clusters before the matching picture, whose sound +/// a player with a bounded read-ahead dropped. From an input of their own +/// the sound is held to the picture's pace and the subtitle input reads to +/// its end at once. Never `-max_interleave_delta 0` instead: it buffers the +/// sound until the next cue (docs/reports/issue-266-subtitle-interleave). +/// +/// `codecs` is the source's subtitle codecs (`s:N` order), `None` when the +/// probe failed; `input` is the index the subtitle input would take. No +/// subtitle stream adds no input, so the source is read twice only when it +/// has one. A failed probe keeps Matroska's old copy from input 1 (losing +/// the user's subtitles to a probe is worse) and maps none into MP4/MOV, as +/// before: mov_text can't take image subtitles and the encode would fail. +pub fn subtitle_mapping(form: SubtitleForm, embed_pending: bool, codecs: Option<&[String]>, input: usize) -> SubtitleMapping { + let none = SubtitleMapping { own_input: false, args: Vec::new() }; + if !subtitle_mapping_probes(form, embed_pending) { + return none; + } + match (form, codecs) { + (SubtitleForm::Copy, None) => SubtitleMapping { + own_input: false, + args: vec!["-map".into(), "1:s?".into(), "-c:s".into(), "copy".into()], + }, + (SubtitleForm::Copy, Some(c)) if !c.is_empty() => SubtitleMapping { + own_input: true, + args: vec!["-map".into(), format!("{input}:s?"), "-c:s".into(), "copy".into()], + }, + (SubtitleForm::MovText, Some(c)) => { + // mov_text only holds text subtitles. Image-based subs (PGS/VobSub + // from DVD/Blu-ray rips) cannot be transcoded to mov_text: ffmpeg + // does NOT skip them, it aborts the whole encode with "Subtitle + // encoding currently only possible from text to text..." (exit + // -22). So only text-based streams are mapped. + let mut args = Vec::new(); + for (k, codec) in c.iter().enumerate() { + if PipelineExecutor::is_text_subtitle(codec) { + args.extend(["-map".to_string(), format!("{input}:s:{k}")]); + } + } + if args.is_empty() { + return none; + } + args.extend(["-c:s".to_string(), "mov_text".to_string()]); + SubtitleMapping { own_input: true, args } + } + _ => none, + } +} + +/// The subtitle input of [`subtitle_mapping`]: the source, with input 1's own +/// seek (`source_seek`), so every cue keeps its time against the sound. +pub fn subtitle_input_args(job: &VideoJob, source_seek: &[String]) -> Vec { + let mut args = source_seek.to_vec(); + args.extend(["-i".to_string(), job.input_path.clone()]); + args +} + #[cfg(test)] mod tests { use super::*; @@ -3348,7 +3432,7 @@ mod tests { let body = &src[start..]; let body = &body[..body.find("\n }\n").expect("end of builder")]; let seek = body - .find("args.extend(source_audio_input_seek(job, self.encoder_priming.as_ref()));") + .find("let source_seek = source_audio_input_seek(job, self.encoder_priming.as_ref());\n args.extend(source_seek.iter().cloned());") .expect("audio seek"); let input = body.find(r#"args.extend(["-i".to_string(), job.input_path.clone()]);"#).unwrap(); assert!(seek < input, "the sound's seek is an input option of the source"); @@ -4995,4 +5079,103 @@ mod tests { let sw_idx = sw_args.iter().position(|a| a == "-preset").unwrap(); assert_eq!(sw_args[sw_idx + 1], "veryslow"); } + + fn codecs(c: &[&str]) -> Vec { + c.iter().map(|s| s.to_string()).collect() + } + + /// Issue #266: a Matroska output takes a source's subtitles from an input + /// of their own, never the sound's input 1. + #[test] + fn matroska_subtitles_come_from_their_own_input() { + let c = codecs(&["subrip", "hdmv_pgs_subtitle"]); + let m = subtitle_mapping(SubtitleForm::Copy, false, Some(&c), 4); + assert!(m.own_input); + assert_eq!(m.args, ["-map", "4:s?", "-c:s", "copy"]); + // A transcript to embed later doesn't change what Matroska copies. + assert_eq!(subtitle_mapping(SubtitleForm::Copy, true, Some(&c), 4), m); + // The index is whatever the caller counted: it moves with the + // restored track, the sound copy and the sound cut. + for input in [3, 5, 6] { + assert_eq!(subtitle_mapping(SubtitleForm::Copy, false, Some(&c), input).args[1], format!("{input}:s?")); + } + } + + /// No subtitle stream adds no input: the source is read twice only when + /// it has subtitles. + #[test] + fn a_source_without_subtitles_adds_no_input() { + for form in [SubtitleForm::Copy, SubtitleForm::MovText, SubtitleForm::None] { + let m = subtitle_mapping(form, false, Some(&[]), 3); + assert_eq!(m, SubtitleMapping { own_input: false, args: vec![] }, "{form:?}"); + } + } + + /// A failed probe keeps Matroska's old copy from input 1 (a probe must + /// not cost the user their subtitles) and maps none into MP4/MOV. + #[test] + fn a_failed_subtitle_probe_keeps_the_old_mapping() { + let mkv = subtitle_mapping(SubtitleForm::Copy, false, None, 3); + assert_eq!(mkv, SubtitleMapping { own_input: false, args: codecs(&["-map", "1:s?", "-c:s", "copy"]) }); + assert_eq!(subtitle_mapping(SubtitleForm::MovText, false, None, 3).args, Vec::::new()); + } + + /// MP4/MOV take text subtitles only, as mov_text, from their own input; + /// image subtitles alone map nothing and add no input; nothing is + /// mapped while a transcript waits to be embedded, and AVI takes none. + #[test] + fn mov_text_subtitles_come_from_their_own_input() { + let c = codecs(&["hdmv_pgs_subtitle", "subrip", "ass"]); + let m = subtitle_mapping(SubtitleForm::MovText, false, Some(&c), 3); + assert!(m.own_input); + assert_eq!(m.args, ["-map", "3:s:1", "-map", "3:s:2", "-c:s", "mov_text"]); + let images = codecs(&["dvd_subtitle"]); + assert!(!subtitle_mapping(SubtitleForm::MovText, false, Some(&images), 3).own_input); + assert!(!subtitle_mapping_probes(SubtitleForm::MovText, true)); + assert!(subtitle_mapping(SubtitleForm::MovText, true, Some(&c), 3).args.is_empty()); + assert!(!subtitle_mapping_probes(SubtitleForm::None, false)); + assert!(subtitle_mapping(SubtitleForm::None, false, Some(&c), 3).args.is_empty()); + } + + /// The subtitle input is seeked exactly as input 1, so every cue keeps + /// its time against the sound in a trimmed encode. + #[test] + fn the_subtitle_input_is_seeked_as_the_sound_input() { + let mut job = create_test_job("/tmp/out.mkv"); + job.input_frame_rate = Some(25.0); + job.start_frame = Some(125); + job.end_frame = Some(500); + let seek = source_audio_input_seek(&job, None); + assert_eq!(seek, ["-ss", "5.000000"]); + assert_eq!(subtitle_input_args(&job, &seek), ["-ss", "5.000000", "-i", "input.mp4"]); + let untrimmed = create_test_job("/tmp/out.mkv"); + let seek = source_audio_input_seek(&untrimmed, None); + assert_eq!(subtitle_input_args(&untrimmed, &seek), ["-i", "input.mp4"]); + } + + #[test] + fn input_count_counts_inputs() { + let args = codecs(&["-f", "yuv4mpegpipe", "-i", "-", "-ss", "1", "-i", "a.mkv", "-map", "0:v"]); + assert_eq!(input_count(&args), 2); + } + + /// The real builder adds the subtitle input last, after every other + /// input and before any output option, with input 1's own seek, and maps + /// subtitles only through `subtitle_mapping`. And never + /// `-max_interleave_delta 0`, which buffers the sound instead. + #[test] + fn the_builder_wires_the_subtitle_input_last() { + let src = include_str!("pipeline_executor.rs").replace("\r\n", "\n"); + let start = src.find("fn build_ffmpeg_args(\n").expect("real builder"); + let end = start + src[start..].find("\n }\n").expect("builder end"); + let body = &src[start..end]; + let cut = body.find("sound_cut_input_args(job").expect("cut input"); + let sub = body.find("subtitle_input_args(job, &source_seek)").expect("subtitle input"); + let progress = body.find("\"-progress\"").expect("progress"); + assert!(cut < sub && sub < progress); + assert!(body.contains("args.extend(source_seek.iter().cloned());")); + assert!(body.contains("args.extend(subtitles.args);")); + assert!(!body.contains(":s?\""), "subtitles mapped outside subtitle_mapping"); + assert!(!src.contains(concat!("\"-max_", "interleave_delta\""))); + } }