diff --git a/CLAUDE.md b/CLAUDE.md index dcd23feb..f2aef8c2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2086,6 +2086,29 @@ download. recreated; `setOverride` verifies writability with a probe file before accepting a path. +### Output Settings Persist Across Launches (issue #264) + +`EncodingSettings` (codec, container, quality, audio, colour format, output +folder, filename pattern, ProRes options, cache override, custom FFmpeg +arguments and custom VapourSynth: every field) is saved by +`EncodingSettingsStore` (`app/lib/services/encoding_settings_store.dart`) as +JSON under the shared_preferences key `encodingSettings`. Rules, asserted in +`encoding_settings_store_test.dart`: + +- **Loaded once, in `main()`, before the view model exists**; `MainViewModel` + starts from `EncodingSettingsStore.instance.initial`. Unreadable or + unrecognised JSON (a codec a newer version saved) falls back to the + defaults and never stops the app starting. +- **Saved from the two places settings change**: `updateEncodingSettings` + (every Settings control) and `loadPreset`. Anything that sets + `_encodingSettings` another way must save too, or it is lost on restart. + Tests inject `initialEncodingSettings` / `saveEncodingSettings`. +- **A preset that names no output folder keeps the current one.** Built-in + presets name none, and loading one used to reset the folder to "same as + input". A preset with its own folder still sets it. +- Restored as saved: an unavailable codec or a refused container pairing is + handled by the same checks as a preset carrying it, never swapped silently. + ### Existing Output Files (issue #85) Before a job starts, `_getConflictingItems` (`main_window.dart`) checks whether diff --git a/README.md b/README.md index b1d99275..fc63dda0 100644 --- a/README.md +++ b/README.md @@ -204,6 +204,8 @@ Every button with a shortcut shows it in its tooltip, and **?** lists them all. Your own presets are saved alongside these, and can be **exported and imported** to share a setup that works for a particular camcorder or capture card. Because a preset can contain custom VapourSynth code and FFmpeg arguments, VapourBox shows you any it contains before importing, and lets you import the preset without them. +Your output settings (folder, filename pattern, codec, container, audio and the rest) are remembered between launches. Picking a preset that doesn't name an output folder keeps the folder you chose. +
diff --git a/app/lib/main.dart b/app/lib/main.dart index 4c414465..b217d944 100644 --- a/app/lib/main.dart +++ b/app/lib/main.dart @@ -6,6 +6,7 @@ import 'package:window_manager/window_manager.dart'; import 'models/filter_registry.dart'; import 'services/advanced_mode_service.dart'; import 'services/dependency_manager.dart'; +import 'services/encoding_settings_store.dart'; import 'services/hardware_encoder_detector.dart'; import 'services/overwrite_behavior_service.dart'; import 'services/preset_service.dart'; @@ -46,6 +47,10 @@ void main() async { // first job can be started. await OverwriteBehaviorService.instance.initialize(); + // Load the output and encoding settings the last session saved (issue + // #264) before the view model is created, so it starts from them. + await EncodingSettingsStore.instance.initialize(); + // Initialize window manager for desktop await windowManager.ensureInitialized(); diff --git a/app/lib/services/encoding_settings_store.dart b/app/lib/services/encoding_settings_store.dart new file mode 100644 index 00000000..fe5d2607 --- /dev/null +++ b/app/lib/services/encoding_settings_store.dart @@ -0,0 +1,84 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../models/encoding_settings.dart'; + +/// The output and encoding settings (codec, container, quality, audio, colour +/// format, output folder, filename pattern, custom arguments …), remembered +/// between launches (issue #264). +/// +/// They used to live only in `MainViewModel`'s memory, so every launch +/// started from `const EncodingSettings()` and a chosen folder or codec was +/// lost on restart. Stored as `EncodingSettings.toJson()` in +/// shared_preferences under `encodingSettings`, written by the view model on +/// every change (`updateEncodingSettings`, `loadPreset`). Every field is kept, +/// custom FFmpeg arguments and custom VapourSynth included (the user's +/// decision in task #135). +/// +/// Call [initialize] once at startup, before the view model is created, so it +/// starts from the saved settings. +class EncodingSettingsStore { + static final EncodingSettingsStore instance = EncodingSettingsStore._(); + EncodingSettingsStore._(); + + static const String prefsKey = 'encodingSettings'; + + EncodingSettings _initial = const EncodingSettings(); + bool _loaded = false; + + /// The settings saved by the last session, or the defaults when there are + /// none, they can't be read, or [initialize] hasn't run. + EncodingSettings get initial => _initial; + + /// Load the saved settings. Safe to call again; only the first call reads + /// storage. Never throws: unreadable or unrecognised settings (corrupt + /// JSON, a codec a newer version saved) fall back to the defaults rather + /// than stop the app starting. + Future initialize() async { + if (_loaded) return; + _initial = const EncodingSettings(); + try { + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString(prefsKey); + if (raw != null) _initial = decode(raw); + } catch (_) { + // Defaults. + } + _loaded = true; + } + + /// [raw] as settings, or the defaults if it is not a valid saved value. + static EncodingSettings decode(String raw) { + try { + final json = jsonDecode(raw); + if (json is Map) return EncodingSettings.fromJson(json); + } catch (_) { + // Fall through to the defaults. + } + return const EncodingSettings(); + } + + /// Remember [settings] for the next launch. A failure to write keeps the + /// in-memory settings for this session and is otherwise ignored. + /// + /// [initial] is left alone: it is what this session started from, read + /// once at startup. + Future save(EncodingSettings settings) async { + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(prefsKey, jsonEncode(settings.toJson())); + } catch (_) { + // Keep the in-memory settings for this session. + } + } + + /// Reset to the unloaded default. Tests only — the singleton outlives a + /// single test case otherwise. + @visibleForTesting + void resetForTesting() { + _initial = const EncodingSettings(); + _loaded = false; + } +} diff --git a/app/lib/viewmodels/main_viewmodel.dart b/app/lib/viewmodels/main_viewmodel.dart index d8e3bc77..1c05836b 100644 --- a/app/lib/viewmodels/main_viewmodel.dart +++ b/app/lib/viewmodels/main_viewmodel.dart @@ -22,6 +22,7 @@ import '../models/subtitle_parameters.dart'; import '../models/video_job.dart'; import '../models/processing_preset.dart'; import '../services/disc_detector.dart'; +import '../services/encoding_settings_store.dart'; import '../services/dvd_service.dart'; import '../services/field_order_detector.dart'; import '../services/frame_math.dart'; @@ -78,7 +79,10 @@ class MainViewModel extends ChangeNotifier { // Settings QTGMCParameters _qtgmcParams = const QTGMCParameters(); - EncodingSettings _encodingSettings = const EncodingSettings(); + // Starts from the settings the last session saved (issue #264). + EncodingSettings _encodingSettings; + // Remembers the settings for the next launch on every change. + final void Function(EncodingSettings settings) _saveEncodingSettings; bool _autoFieldOrder = true; FieldOrder _manualFieldOrder = FieldOrder.topFieldFirst; @@ -903,7 +907,13 @@ class MainViewModel extends ChangeNotifier { TimestampContinuityService? continuityService, PreviewGenerator? previewGenerator, FieldOrderDetector? fieldOrderDetector, - }) : _workerManager = runner ?? WorkerManager(), + EncodingSettings? initialEncodingSettings, + void Function(EncodingSettings settings)? saveEncodingSettings, + }) : _encodingSettings = + initialEncodingSettings ?? EncodingSettingsStore.instance.initial, + _saveEncodingSettings = + saveEncodingSettings ?? EncodingSettingsStore.instance.save, + _workerManager = runner ?? WorkerManager(), _previewGenerator = previewGenerator ?? PreviewGenerator(), _fieldOrderDetector = fieldOrderDetector ?? FieldOrderDetector(), _continuity = continuityService ?? const TimestampContinuityService(), @@ -1916,6 +1926,7 @@ class MainViewModel extends ChangeNotifier { void updateEncodingSettings(EncodingSettings settings) { final previous = _encodingSettings; _encodingSettings = settings; + _saveEncodingSettings(settings); // Log audio setting changes so a recurrence of the "audio reverted to copy" // class of bug (issue #12) is diagnosable from a user's log. if (previous.audioMode != settings.audioMode || @@ -2807,7 +2818,14 @@ class MainViewModel extends ChangeNotifier { void loadPreset(ProcessingPreset preset) { _processingPipeline = preset.pipeline; _qtgmcParams = preset.pipeline.deinterlace; - _encodingSettings = preset.encodingSettings; + // A preset that names no output folder keeps the one the user chose: + // built-in presets name none, and loading one used to reset the folder + // to "same as input" (issue #264). A preset with a folder still sets it. + _encodingSettings = preset.encodingSettings.outputDirectory == null + ? preset.encodingSettings + .copyWith(outputDirectory: _encodingSettings.outputDirectory) + : preset.encodingSettings; + _saveEncodingSettings(_encodingSettings); _selectedPass = null; // Clear dynamic params cache to force refresh diff --git a/app/test/encoding_settings_store_test.dart b/app/test/encoding_settings_store_test.dart new file mode 100644 index 00000000..7aaca752 --- /dev/null +++ b/app/test/encoding_settings_store_test.dart @@ -0,0 +1,167 @@ +// Output and encoding settings survive a restart (issue #264). +// +// They used to live only in MainViewModel's memory, so a chosen output +// folder, codec or container was back at its default on every launch. +// EncodingSettingsStore keeps them in shared_preferences; a "restart" here is +// resetForTesting() + initialize(), which reads storage again, and a new view +// model built from the store. +// +// Run with: flutter test test/encoding_settings_store_test.dart + +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:vapourbox/models/encoding_settings.dart'; +import 'package:vapourbox/models/processing_preset.dart'; +import 'package:vapourbox/models/video_job.dart'; +import 'package:vapourbox/services/encoding_settings_store.dart'; +import 'package:vapourbox/viewmodels/main_viewmodel.dart'; + +import 'fakes/fake_job_runner.dart'; +import 'fakes/no_source_model_continuity.dart'; + +/// Settings with every field moved off its default. +EncodingSettings _changed() => const EncodingSettings( + codec: VideoCodec.proresHQ, + encoderPreset: 'slow', + quality: 23, + videoBitrateKbps: 12000, + audioMode: AudioMode.convert, + audioCodec: AudioCodec.flac, + audioQuality: AudioQuality.veryHigh, + chromaSubsampling: ChromaSubsampling.yuv422p10, + proresVendorApl0: true, + proresBitsPerMb: 4000, + proresQuantMat: ProResQuantMat.hq, + customFfmpegArgs: '-metadata title=x', + customVapoursynth: 'clip = clip', + maxCacheSizeMb: 2048, + container: ContainerFormat.mov, + outputDirectory: '/Volumes/Archive/out', + filenamePattern: '{input_filename}_{date}', + ); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final store = EncodingSettingsStore.instance; + + Future restart() async { + store.resetForTesting(); + await store.initialize(); + } + + setUp(() { + SharedPreferences.setMockInitialValues({}); + store.resetForTesting(); + }); + + group('EncodingSettingsStore', () { + test('starts from the defaults when nothing is saved', () async { + await store.initialize(); + expect(store.initial.toJson(), const EncodingSettings().toJson()); + }); + + test('every field, custom code included, comes back after a restart', + () async { + await store.initialize(); + final settings = _changed(); + // Guard the fixture: each field really is off its default, or the + // round trip would prove nothing about it. + final defaults = const EncodingSettings().toJson(); + settings.toJson().forEach((key, value) { + expect(value, isNot(defaults[key]), reason: '$key is at its default'); + }); + + await store.save(settings); + await restart(); + + expect(store.initial.toJson(), settings.toJson()); + expect(store.initial.customFfmpegArgs, '-metadata title=x'); + expect(store.initial.customVapoursynth, 'clip = clip'); + }); + + test('save leaves this session\'s starting point alone', () async { + await store.initialize(); + await store.save(_changed()); + expect(store.initial.toJson(), const EncodingSettings().toJson()); + }); + + for (final (name, raw) in [ + ('corrupt JSON', '{not json'), + ('a JSON value that is not an object', '[1, 2]'), + ( + 'a codec this build does not know', + jsonEncode({...const EncodingSettings().toJson(), 'codec': 'h267'}) + ), + ]) { + test('$name falls back to the defaults', () async { + SharedPreferences.setMockInitialValues( + {EncodingSettingsStore.prefsKey: raw}); + await store.initialize(); + expect(store.initial.toJson(), const EncodingSettings().toJson()); + }); + } + }); + + group('MainViewModel', () { + MainViewModel newViewModel() => MainViewModel( + runner: FakeJobRunner(), + continuityService: const NoSourceModelContinuity()); + + test('a change in Settings is there after a restart (issue #264)', + () async { + await store.initialize(); + final vm = newViewModel(); + vm.updateEncodingSettings(_changed()); + await pumpEventQueue(); + vm.dispose(); + + await restart(); + final next = newViewModel(); + addTearDown(next.dispose); + expect(next.encodingSettings.toJson(), _changed().toJson()); + }); + + test('loading a preset with no folder keeps the chosen folder', () async { + final saved = []; + final vm = MainViewModel( + runner: FakeJobRunner(), + continuityService: const NoSourceModelContinuity(), + initialEncodingSettings: + const EncodingSettings(outputDirectory: '/Volumes/Archive/out'), + saveEncodingSettings: saved.add, + ); + addTearDown(vm.dispose); + + final preset = ProcessingPreset.builtInBalanced(); + expect(preset.encodingSettings.outputDirectory, isNull); + vm.loadPreset(preset); + + expect(vm.encodingSettings.outputDirectory, '/Volumes/Archive/out'); + expect(vm.encodingSettings.codec, preset.encodingSettings.codec); + // What the preset applied is what the next launch starts from. + expect(saved.last.toJson(), vm.encodingSettings.toJson()); + }); + + test('a preset that names a folder still sets it', () async { + final vm = MainViewModel( + runner: FakeJobRunner(), + continuityService: const NoSourceModelContinuity(), + initialEncodingSettings: + const EncodingSettings(outputDirectory: '/Volumes/Archive/out'), + saveEncodingSettings: (_) {}, + ); + addTearDown(vm.dispose); + + vm.loadPreset(ProcessingPreset( + name: 'Mine', + pipeline: ProcessingPreset.builtInBalanced().pipeline, + encodingSettings: const EncodingSettings(outputDirectory: '/elsewhere'), + )); + + expect(vm.encodingSettings.outputDirectory, '/elsewhere'); + }); + }); +}