From d1cb19d6f92dbf9d582b929190c6588167a11029 Mon Sep 17 00:00:00 2001 From: Stuart Cameron Date: Sat, 28 Nov 2026 19:44:46 +1100 Subject: [PATCH] fix(audio): offer only containers that hold the video codec too (task #132) The Passthrough audio dialog's "Change container format" listed every container that could copy the sound, ignoring the video codec, so AV1 could be switched into MOV/AVI and v210/ProRes/HuffYUV into MP4, pairs the worker refuses. The service now filters by the video codec's verdict (offered) as well as the audio copy table, and the refusal's "save as" list does the same on both sides (Dart copyProblem, Rust audio_copy_problem take the codec). Also fixes the dialog's chips: the first container was pre-selected, and a selected ChoiceChip reports a tap as onSelected(false), so it could never be picked. Each chip now pops on any tap. Tests sweep VideoCodec x copy codec x container, pin named table cases and pump the dialog; the Rust test sweeps the message. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 6 +- .../services/audio_compatibility_service.dart | 66 ++++--- app/lib/views/audio_compatibility_dialog.dart | 30 +--- app/lib/views/main_window.dart | 1 + .../audio_compatibility_containers_test.dart | 169 ++++++++++++++++++ .../integration_output_conformance_test.dart | 3 +- app/test/output_capabilities_test.dart | 3 +- worker/src/main.rs | 8 +- worker/src/models/output_capabilities.rs | 49 ++++- 9 files changed, 280 insertions(+), 55 deletions(-) create mode 100644 app/test/audio_compatibility_containers_test.dart diff --git a/CLAUDE.md b/CLAUDE.md index dcd23feb..8883fdab 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2851,7 +2851,11 @@ table. Rules: checks too: the source model's audio codecs (`audioStreams`), refused with `audioCopyMessage` (`audio_copy_problem`, Dart `AudioCompatibilityService.copyProblem`); a stream Audio Restoration - re-encodes is not checked. + re-encodes is not checked. The Passthrough dialog's container choices + (`AudioCompatibilityService.compatibleContainers`) and the message's "save + as" list are also filtered by the video codec's verdict (`offered` only; + `audio_copy_problem(codec, container, Some(video))`), so a container switch + never lands on a pair the worker refuses (task #132). - **Checked against FFmpeg both ways** in the push gate (`output_capabilities_test.dart`): every video row muxed (hardware encoders through their software twin, `muxEncoder`), every Convert codec, every diff --git a/app/lib/services/audio_compatibility_service.dart b/app/lib/services/audio_compatibility_service.dart index 467443d2..3b2cd1d5 100644 --- a/app/lib/services/audio_compatibility_service.dart +++ b/app/lib/services/audio_compatibility_service.dart @@ -77,11 +77,15 @@ class AudioCompatibilityService { {for (final codecs in outputAudioCopy.values) ...codecs}; /// Why a copy of [codec] can't go into [container], or null when it can. - /// The same words as the worker's refusal (`audio_copy_problem`). - static String? copyProblem(String codec, ContainerFormat container) { + /// The same words as the worker's refusal (`audio_copy_problem`). With + /// [videoCodec], the "save as" list names only containers that also offer + /// that video codec (task #132), as the worker's does for the job's codec. + static String? copyProblem(String codec, ContainerFormat container, + {VideoCodec? videoCodec}) { if (container.copies(codec)) return null; final others = ContainerFormat.values .where((k) => k != container && k.copies(codec)) + .where((k) => videoCodec == null || videoCodec.supportsContainer(k)) .map((k) => k.shortName); final message = outputAudioCopyMessage .replaceAll('{codec}', codec.toUpperCase()) @@ -146,16 +150,15 @@ class AudioCompatibilityService { bool isCodecCompatible(String codec, ContainerFormat container) => container.copies(codec); - /// Get all containers that support the given audio codec. - List getCompatibleContainers(String codec) { - final result = []; - for (final container in ContainerFormat.values) { - if (isCodecCompatible(codec, container)) { - result.add(container); - } - } - return result; - } + /// The containers that can take a copy of [codec] and are offered for + /// [videoCodec] (task #132): the audio copy table and the video verdict + /// together, so a container switch never makes a pair the worker refuses + /// (AV1 in MOV/AVI, v210 or ProRes in MP4) or one the app doesn't offer. + static List compatibleContainers( + String codec, VideoCodec videoCodec) => + ContainerFormat.values + .where((k) => k.copies(codec) && videoCodec.supportsContainer(k)) + .toList(); /// Get the suggested fallback codec for a container. String getSuggestedCodec(ContainerFormat container) { @@ -165,38 +168,53 @@ class AudioCompatibilityService { /// Check audio compatibility for an export operation. /// /// Returns a result indicating whether the input audio codec is compatible - /// with the selected output container, and provides alternatives if not. + /// with the selected output container, and provides alternatives if not: + /// containers that hold both the copied sound and [videoCodec]. Future checkCompatibility({ required String inputPath, required ContainerFormat outputContainer, required AudioMode audioMode, + required VideoCodec videoCodec, }) async { final audioInfo = await getAudioInfo(inputPath); + return resultFor( + audioInfo: audioInfo, + outputContainer: outputContainer, + audioMode: audioMode, + videoCodec: videoCodec, + ); + } + /// [checkCompatibility] for an already probed [audioInfo]. + static AudioCompatibilityResult resultFor({ + required AudioInfo audioInfo, + required ContainerFormat outputContainer, + required AudioMode audioMode, + required VideoCodec videoCodec, + }) { + final suggested = _fallbackCodecs[outputContainer] ?? 'aac'; // If no audio, audio disabled, or re-encoding audio, always compatible if (!audioInfo.hasAudio || audioMode != AudioMode.passthrough) { return AudioCompatibilityResult( audioInfo: audioInfo, container: outputContainer, isCompatible: true, - compatibleContainers: ContainerFormat.values.toList(), - suggestedCodec: getSuggestedCodec(outputContainer), + compatibleContainers: ContainerFormat.values + .where(videoCodec.supportsContainer) + .toList(), + suggestedCodec: suggested, ); } final codec = audioInfo.codec!; - final isCompatible = isCodecCompatible(codec, outputContainer); - final compatibleContainers = getCompatibleContainers(codec); - - final reason = copyProblem(codec, outputContainer); - return AudioCompatibilityResult( audioInfo: audioInfo, container: outputContainer, - isCompatible: isCompatible, - incompatibilityReason: reason, - compatibleContainers: compatibleContainers, - suggestedCodec: getSuggestedCodec(outputContainer), + isCompatible: outputContainer.copies(codec), + incompatibilityReason: + copyProblem(codec, outputContainer, videoCodec: videoCodec), + compatibleContainers: compatibleContainers(codec, videoCodec), + suggestedCodec: suggested, ); } diff --git a/app/lib/views/audio_compatibility_dialog.dart b/app/lib/views/audio_compatibility_dialog.dart index e8a02273..d4a5a306 100644 --- a/app/lib/views/audio_compatibility_dialog.dart +++ b/app/lib/views/audio_compatibility_dialog.dart @@ -67,17 +67,6 @@ class AudioCompatibilityDialog extends StatefulWidget { } class _AudioCompatibilityDialogState extends State { - ContainerFormat? _selectedContainer; - - @override - void initState() { - super.initState(); - // Pre-select first compatible container if available - if (widget.compatibility.compatibleContainers.isNotEmpty) { - _selectedContainer = widget.compatibility.compatibleContainers.first; - } - } - @override Widget build(BuildContext context) { final theme = Theme.of(context); @@ -306,7 +295,7 @@ class _AudioCompatibilityDialogState extends State { style: theme.textTheme.titleSmall, ), Text( - 'Keep original audio, use a compatible container', + 'Keep the original audio and video codec, in a container that holds both', style: theme.textTheme.bodySmall?.copyWith( color: theme.colorScheme.onSurfaceVariant, ), @@ -320,19 +309,16 @@ class _AudioCompatibilityDialogState extends State { Wrap( spacing: 8, runSpacing: 8, + // Each chip is the choice itself, so none starts selected: a + // selected ChoiceChip reports a tap as onSelected(false), and the + // pre-selected first container could never be picked (task #132). children: containers.map((container) { - final isSelected = container == _selectedContainer; return ChoiceChip( label: Text(container.displayName), - selected: isSelected, - onSelected: (selected) { - if (selected) { - setState(() => _selectedContainer = container); - Navigator.of(context).pop( - AudioCompatibilityDialogResult.switchContainer(container), - ); - } - }, + selected: false, + onSelected: (_) => Navigator.of(context).pop( + AudioCompatibilityDialogResult.switchContainer(container), + ), ); }).toList(), ), diff --git a/app/lib/views/main_window.dart b/app/lib/views/main_window.dart index 2c4df96f..5a9edf61 100644 --- a/app/lib/views/main_window.dart +++ b/app/lib/views/main_window.dart @@ -1322,6 +1322,7 @@ class MainWindow extends StatelessWidget { inputPath: viewModel.decodePath!, outputContainer: viewModel.encodingSettings.container, audioMode: viewModel.encodingSettings.audioMode, + videoCodec: viewModel.encodingSettings.codec, ); // If compatible or no audio, proceed directly diff --git a/app/test/audio_compatibility_containers_test.dart b/app/test/audio_compatibility_containers_test.dart new file mode 100644 index 00000000..6d6a54bd --- /dev/null +++ b/app/test/audio_compatibility_containers_test.dart @@ -0,0 +1,169 @@ +// Task #132: the Passthrough audio dialog's "Change container format" offers +// only containers that take a copy of the sound AND are offered for the job's +// video codec, and its "save as" text names the same ones. Before, it offered +// every container that copied the sound, so AV1 could be switched into MOV or +// AVI and v210 / ProRes into MP4, pairs the worker refuses. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:vapourbox/models/encoding_settings.dart'; +import 'package:vapourbox/models/video_job.dart'; +import 'package:vapourbox/services/audio_compatibility_service.dart'; +import 'package:vapourbox/views/audio_compatibility_dialog.dart'; + +/// The dialog is laid out for a desktop window; the default 800x600 test +/// view overflows it. +void _desktopView(WidgetTester tester) { + tester.view.physicalSize = const Size(1280, 1000); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); +} + +void main() { + final copyCodecs = [ + ...(AudioCompatibilityService.knownCodecs.toList()..sort()), + 'wmav2', // copied by no container + ]; + + test('the offered containers hold both the sound and the video codec', () { + for (final video in VideoCodec.values) { + for (final audio in copyCodecs) { + final offered = + AudioCompatibilityService.compatibleContainers(audio, video); + expect( + offered, + ContainerFormat.values + .where((k) => k.copies(audio) && video.supportsContainer(k)) + .toList(), + reason: '${video.name} + $audio', + ); + for (final k in offered) { + expect(video.containerVerdict(k), ContainerVerdict.offered, + reason: '${video.name} + $audio offered ${k.shortName}'); + } + } + } + }); + + test('every result the dialog can get offers only valid pairs', () { + for (final video in VideoCodec.values) { + for (final audio in copyCodecs) { + for (final container in ContainerFormat.values) { + final r = AudioCompatibilityService.resultFor( + audioInfo: AudioInfo(codec: audio), + outputContainer: container, + audioMode: AudioMode.passthrough, + videoCodec: video, + ); + expect(r.isCompatible, container.copies(audio)); + for (final k in r.compatibleContainers) { + expect(video.containerVerdict(k), isNot(ContainerVerdict.refused), + reason: '${video.name} + $audio from ${container.shortName}'); + expect(video.supportsContainer(k), isTrue); + } + // The text names no container the chips leave out. + final reason = r.incompatibilityReason; + if (reason == null) continue; + final saveAs = reason.split(', or save as '); + if (saveAs.length < 2) continue; + for (final k in ContainerFormat.values) { + if (RegExp('\\b${k.shortName}\\b').hasMatch(saveAs[1])) { + expect(r.compatibleContainers, contains(k), + reason: '${video.name} + $audio: $reason'); + } + } + } + } + } + }); + + test('the named cases from the table', () { + expect(AudioCompatibilityService.compatibleContainers('pcm_u8', VideoCodec.av1), + [ContainerFormat.mkv]); + expect(AudioCompatibilityService.compatibleContainers('opus', VideoCodec.v210), + [ContainerFormat.mkv]); + expect(AudioCompatibilityService.compatibleContainers('pcm_u8', VideoCodec.h264), + [ContainerFormat.mov, ContainerFormat.mkv, ContainerFormat.avi]); + // Only MKV copies WavPack, and ProRes is offered only in MOV. + expect( + AudioCompatibilityService.compatibleContainers('wavpack', VideoCodec.prores422), + isEmpty); + }); + + test('the copy refusal names only containers the video codec is offered in', () { + expect( + AudioCompatibilityService.copyProblem('pcm_u8', ContainerFormat.mp4, + videoCodec: VideoCodec.av1), + 'PCM_U8 audio can\'t be copied into MP4 files. Choose Convert in ' + 'Settings → Audio, or save as MKV.'); + expect( + AudioCompatibilityService.copyProblem('opus', ContainerFormat.avi, + videoCodec: VideoCodec.v210), + 'OPUS audio can\'t be copied into AVI files. Choose Convert in ' + 'Settings → Audio, or save as MKV.'); + // Nowhere to go: the "save as" clause is dropped, as for a codec no + // container copies. + expect( + AudioCompatibilityService.copyProblem('wavpack', ContainerFormat.mov, + videoCodec: VideoCodec.prores422), + 'WAVPACK audio can\'t be copied into MOV files. Choose Convert in ' + 'Settings → Audio.'); + // Without a video codec the words are unchanged (the worker's `None`). + expect( + AudioCompatibilityService.copyProblem('pcm_u8', ContainerFormat.mp4), + 'PCM_U8 audio can\'t be copied into MP4 files. Choose Convert in ' + 'Settings → Audio, or save as MOV, MKV or AVI.'); + }); + + testWidgets('the dialog offers AV1 only MKV for PCM_U8 sound', + (tester) async { + _desktopView(tester); + final compatibility = AudioCompatibilityService.resultFor( + audioInfo: const AudioInfo(codec: 'pcm_u8'), + outputContainer: ContainerFormat.mp4, + audioMode: AudioMode.passthrough, + videoCodec: VideoCodec.av1, + ); + AudioCompatibilityDialogResult? popped; + await tester.pumpWidget(MaterialApp( + home: Builder( + builder: (context) => TextButton( + onPressed: () async { + popped = await AudioCompatibilityDialog.show( + context: context, compatibility: compatibility); + }, + child: const Text('open'), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + final chips = tester + .widgetList(find.byType(ChoiceChip)) + .map((c) => (c.label as Text).data) + .toList(); + expect(chips, [ContainerFormat.mkv.displayName]); + expect(find.textContaining('or save as MKV.'), findsOneWidget); + + await tester.tap(find.widgetWithText(ChoiceChip, ContainerFormat.mkv.displayName)); + await tester.pumpAndSettle(); + expect(popped?.choice, AudioCompatibilityChoice.changeContainer); + expect(popped?.newContainer, ContainerFormat.mkv); + }); + + testWidgets('no container option when none holds both', (tester) async { + _desktopView(tester); + final compatibility = AudioCompatibilityService.resultFor( + audioInfo: const AudioInfo(codec: 'wavpack'), + outputContainer: ContainerFormat.mov, + audioMode: AudioMode.passthrough, + videoCodec: VideoCodec.prores422, + ); + await tester.pumpWidget(MaterialApp( + home: Scaffold(body: AudioCompatibilityDialog(compatibility: compatibility)), + )); + expect(find.text('Change container format'), findsNothing); + expect(find.text('Re-encode audio'), findsOneWidget); + }); +} diff --git a/app/test/integration_output_conformance_test.dart b/app/test/integration_output_conformance_test.dart index 12adb6d2..9dd5a30a 100644 --- a/app/test/integration_output_conformance_test.dart +++ b/app/test/integration_output_conformance_test.dart @@ -565,7 +565,8 @@ void main() { ); final r = await WorkerHarness.runJob(job.toJson(), label: 'opus copy'); expect(r.success, isFalse); - expect(r.error, AudioCompatibilityService.copyProblem('opus', ContainerFormat.avi)); + expect(r.error, AudioCompatibilityService.copyProblem('opus', ContainerFormat.avi, + videoCodec: VideoCodec.ffv1)); expect(r.logs.any((l) => l.contains('Generating VapourSynth script')), isFalse); }); } diff --git a/app/test/output_capabilities_test.dart b/app/test/output_capabilities_test.dart index a1884219..0a5fd63e 100644 --- a/app/test/output_capabilities_test.dart +++ b/app/test/output_capabilities_test.dart @@ -34,7 +34,8 @@ void main() { expect(service.isCodecCompatible('mp2', container), isTrue, reason: 'mp2 must be allowed in ${container.displayName}'); } - expect(service.getCompatibleContainers('mp2'), + // H.264 is offered in every container, so only the sound decides. + expect(AudioCompatibilityService.compatibleContainers('mp2', VideoCodec.h264), unorderedEquals(ContainerFormat.values)); }); diff --git a/worker/src/main.rs b/worker/src/main.rs index 406c3f29..da491d54 100644 --- a/worker/src/main.rs +++ b/worker/src/main.rs @@ -1143,7 +1143,13 @@ fn audio_copy_problem(job: &VideoJob) -> Option { .enumerate() .filter(|(i, _)| Some(*i) != restored) .filter_map(|(_, s)| s.codec.as_deref()) - .find_map(|codec| models::audio_copy_problem(codec, job.encoding_settings.container)) + .find_map(|codec| { + models::audio_copy_problem( + codec, + job.encoding_settings.container, + Some(job.encoding_settings.codec), + ) + }) } fn run_worker( diff --git a/worker/src/models/output_capabilities.rs b/worker/src/models/output_capabilities.rs index fea85cfc..dc17e8e6 100644 --- a/worker/src/models/output_capabilities.rs +++ b/worker/src/models/output_capabilities.rs @@ -231,14 +231,21 @@ pub fn audio_copy_allowed(codec: &str, container: ContainerFormat) -> bool { } /// Why a copy of `codec` can't go into `container`, or `None` when it can. -/// The same words as Dart's `AudioCompatibilityService.copyProblem`. -pub fn audio_copy_problem(codec: &str, container: ContainerFormat) -> Option { +/// The same words as Dart's `AudioCompatibilityService.copyProblem`. With +/// `video`, the "save as" list names only containers that also offer that +/// video codec (task #132), so it never suggests a pair the worker refuses. +pub fn audio_copy_problem( + codec: &str, + container: ContainerFormat, + video: Option, +) -> Option { if audio_copy_allowed(codec, container) { return None; } let others: Vec<&str> = ContainerFormat::ALL .iter() .filter(|&&k| k != container && audio_copy_allowed(codec, k)) + .filter(|&&k| video.map_or(true, |v| v.container_verdict(k) == Verdict::Offered)) .map(|k| k.short_name()) .collect(); let mut message = OutputCapabilities::get() @@ -354,17 +361,49 @@ mod tests { fn copy_problems() { assert!(audio_copy_allowed("mp2", ContainerFormat::Avi)); assert!(audio_copy_allowed("AAC", ContainerFormat::Mp4)); - assert_eq!(audio_copy_problem("aac", ContainerFormat::Mp4), None); + assert_eq!(audio_copy_problem("aac", ContainerFormat::Mp4, None), None); assert_eq!( - audio_copy_problem("opus", ContainerFormat::Avi).as_deref(), + audio_copy_problem("opus", ContainerFormat::Avi, None).as_deref(), Some("OPUS audio can't be copied into AVI files. Choose Convert in Settings \u{2192} Audio, or save as MP4 or MKV.") ); assert_eq!( - audio_copy_problem("wmav2", ContainerFormat::Mkv).as_deref(), + audio_copy_problem("wmav2", ContainerFormat::Mkv, None).as_deref(), Some("WMAV2 audio can't be copied into MKV files. Choose Convert in Settings \u{2192} Audio.") ); } + /// The "save as" list names only containers that offer the job's video + /// codec (task #132): AV1 can't go into MOV or AVI, v210 not into MP4. + #[test] + fn copy_problems_name_only_containers_the_video_codec_is_offered_in() { + assert_eq!( + audio_copy_problem("pcm_u8", ContainerFormat::Mp4, Some(VideoCodec::Av1)).as_deref(), + Some("PCM_U8 audio can't be copied into MP4 files. Choose Convert in Settings \u{2192} Audio, or save as MKV.") + ); + assert_eq!( + audio_copy_problem("opus", ContainerFormat::Avi, Some(VideoCodec::V210)).as_deref(), + Some("OPUS audio can't be copied into AVI files. Choose Convert in Settings \u{2192} Audio, or save as MKV.") + ); + // Every codec, copy codec and container: a container the message + // names is one the video codec is offered in. + let names: Vec<&String> = OutputCapabilities::get().audio_copy.values().flatten().collect(); + for &v in VideoCodec::ALL { + for &k in ContainerFormat::ALL { + for codec in names.iter().map(|s| s.as_str()).chain(["wmav2"]) { + let Some(message) = audio_copy_problem(codec, k, Some(v)) else { continue }; + let Some((_, list)) = message.split_once(", or save as ") else { continue }; + for &other in ContainerFormat::ALL { + let name = other.short_name(); + let named = list.trim_end_matches('.').split([',', ' ']).any(|w| w == name); + if named { + assert_eq!(v.container_verdict(other), Verdict::Offered, "{v:?} {codec} {k:?}: {message}"); + } + } + } + } + } + } + /// Convert's codec x container table and its wording (task #39). #[test] fn convert_refusals_follow_the_table() {