Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
44 changes: 44 additions & 0 deletions Tests/TestResources/generate_sparse_subtitle_test.sh
Original file line number Diff line number Diff line change
@@ -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"
Binary file added Tests/TestResources/sparse_subs.mkv
Binary file not shown.
123 changes: 123 additions & 0 deletions app/test/integration_subtitle_interleave_test.dart
Original file line number Diff line number Diff line change
@@ -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<List<double>> _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');
});
}
34 changes: 34 additions & 0 deletions app/test/support/av_sync.dart
Original file line number Diff line number Diff line change
Expand Up @@ -242,3 +242,37 @@ Future<double> 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<double> 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;
}
29 changes: 29 additions & 0 deletions docs/ENGINEERING_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
1 change: 1 addition & 0 deletions docs/reports/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading