From 80f0395230a3c461a7ff9ca13d5c77e249e63f28 Mon Sep 17 00:00:00 2001 From: maghofer <327971135+maghofer@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:25:09 +0100 Subject: [PATCH 1/7] Address file handling, playback, pillarbox and HCenc issues --- .github/workflows/ci.yml | 7 + README.md | 12 +- THIRD_PARTY.md | 5 +- cmd/easydvd-navcheck/main_windows.go | 22 ++- docs/ENCODERS.md | 62 ++++++- docs/RELEASING.md | 5 + internal/app/cli.go | 28 ++- internal/engine/engine.go | 152 +++++++++++++++- internal/engine/engine_test.go | 93 ++++++++++ internal/integration/issues_test.go | 232 +++++++++++++++++++++++++ internal/integration/pipeline_test.go | 12 ++ internal/media/author.go | 22 ++- internal/media/discover.go | 3 + internal/media/discover_test.go | 38 ++++ internal/media/encode.go | 61 ++++--- internal/media/encode_test.go | 14 ++ internal/media/ffmpeg.go | 2 +- internal/media/ffmpeg_test.go | 6 +- internal/media/hcenc.go | 207 ++++++++++++++++++++++ internal/media/hcenc_test.go | 53 ++++++ internal/media/pillarbox.go | 95 ++++++++++ internal/media/pillarbox_test.go | 42 +++++ internal/media/probe.go | 5 +- internal/model/model.go | 46 ++++- internal/store/store.go | 3 +- internal/ui/drop.go | 64 +++++++ internal/ui/drop_test.go | 36 ++++ internal/ui/files.go | 32 ++++ internal/ui/files_test.go | 27 +++ internal/ui/playback_test.go | 66 +++++++ internal/ui/ui.go | 33 +++- scripts/package.ps1 | 2 + scripts/prepare-hcenc.ps1 | 44 +++++ validation/GITHUB-ISSUES-2026-10-29.md | 68 ++++++++ 34 files changed, 1535 insertions(+), 64 deletions(-) create mode 100644 internal/integration/issues_test.go create mode 100644 internal/media/discover_test.go create mode 100644 internal/media/hcenc.go create mode 100644 internal/media/hcenc_test.go create mode 100644 internal/media/pillarbox.go create mode 100644 internal/media/pillarbox_test.go create mode 100644 internal/ui/drop.go create mode 100644 internal/ui/drop_test.go create mode 100644 internal/ui/playback_test.go create mode 100644 scripts/prepare-hcenc.ps1 create mode 100644 validation/GITHUB-ISSUES-2026-10-29.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9398661..e9106dd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,13 @@ jobs: - name: Prepare pinned development and media tools shell: pwsh run: ./scripts/bootstrap.ps1 + - uses: actions/cache@v4 + with: + path: .tools/hcenc + key: ${{ runner.os }}-hcenc-${{ hashFiles('scripts/prepare-hcenc.ps1') }} + - name: Prepare pinned HCenc runtime + shell: pwsh + run: ./scripts/prepare-hcenc.ps1 -CacheDir .tools/hcenc/setup - name: Build and validate DVD pipeline shell: pwsh run: ./scripts/build.ps1 -Test -Integration diff --git a/README.md b/README.md index 1361e63..b0709aa 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ the separate sources ZIP is not needed to run the app. - **Batch processing:** queue several folders at once. Each added folder becomes its own DVD set, including its subfolders. Each video file becomes a DVD title. + Drop individual videos too; multiple files can share a set or become separate jobs. - **Automatic disc layout:** spread videos across as many discs as needed. Keep filename order, or choose space efficiency to make better use of disc space. Videos stay whole; a file that cannot fit on one disc is reported. @@ -22,7 +23,8 @@ the separate sources ZIP is not needed to run the app. fonts and colors, and save presets. Menus include title selection, page navigation and Play All. - **DVD format choices:** PAL or NTSC, DVD-5 or DVD-9, with 4:3 and 16:9 video - handled automatically. + handled automatically. Confirmed 4:3 footage inside black 16:9 side borders is + cropped without stretching. Single-title jobs can start playback without a menu. - **Pause and resume:** save the queue and continue later, reusing completed encodes. Errors are shown against the affected folder so other sets can continue. @@ -45,10 +47,16 @@ using easyDVD. 1. Extract the complete Windows ZIP and open **easyDVD.exe**. Keep the `tools` folder beside it. 2. Drag folders into the window or use **Add folders**. Review the videos and - choose an output folder and a local work folder with enough free space. + choose an output folder and a local work folder with enough free space. You can + also drop video files. Hold Shift while selecting files to select a range. 3. Choose your TV standard, disc capacity and menu style, then select **Start / resume**. Finished ISO files appear in your output folder. +New jobs use HCenc for two-pass MPEG-2 video. Set up its private runtime as +described in [Encoder setup](docs/ENCODERS.md), or choose **FFmpeg** under +**Settings → Video encoder**. For a single included video, **Job settings → +Playback → No menu** creates a disc that starts automatically and stops at the end. + For more on menu appearance and presets, see [Menu settings](docs/MENUS.md). Report problems or suggest changes through [GitHub Issues](https://github.com/maghofer/easyDVD/issues). diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index a6b1d83..9a51582 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -36,6 +36,9 @@ files used by older candidates. The current helper source recipe is in `scripts/toolchain/README.md`. No bit-identical reproduction claim is made; the matching source and all our build changes are supplied. -HCenc, AviSynth, FFMS2, and mpeg2enc are optional benchmark inputs and are not +HCenc is the default video backend for new jobs; its private AviSynth/FFMS2 +runtime is installed separately. The setup helper preserves upstream notices and +records pinned download hashes. These binaries are not part of the normal app +package. mpeg2enc remains an optional benchmark input. These components are not distributed by easyDVD. No encoder superiority claim is made without a completed comparison on representative material. diff --git a/cmd/easydvd-navcheck/main_windows.go b/cmd/easydvd-navcheck/main_windows.go index 048fa0d..e6e9fc3 100644 --- a/cmd/easydvd-navcheck/main_windows.go +++ b/cmd/easydvd-navcheck/main_windows.go @@ -14,8 +14,8 @@ import ( ) func main() { - if len(os.Args) != 3 { - fmt.Fprintln(os.Stderr, "Usage: easydvd-navcheck VLC_DIRECTORY FIXTURE.iso (3 titles, 2 menu entries per page)") + if len(os.Args) != 3 && !(len(os.Args) == 4 && os.Args[3] == "--autoplay") { + fmt.Fprintln(os.Stderr, "Usage: easydvd-navcheck VLC_DIRECTORY FIXTURE.iso [--autoplay] (otherwise: 3 titles, 2 menu entries per page)") os.Exit(2) } root, _ := filepath.Abs(os.Args[1]) @@ -24,7 +24,7 @@ func main() { os.Setenv("VLC_PLUGIN_PATH", filepath.Join(root, "plugins")) dll := windows.NewLazyDLL(filepath.Join(root, "libvlc.dll")) call := func(name string, args ...uintptr) uintptr { r, _, _ := dll.NewProc(name).Call(args...); return r } - strings := []string{"--intf=dummy", "--vout=dummy", "--aout=dummy", "--ignore-config", "--no-media-library", "--no-video-title-show", "--quiet", "--file-caching=100", "--disc-caching=100"} + strings := []string{"--intf=dummy", "--vout=dummy", "--aout=dummy", "--avcodec-hw=none", "--ignore-config", "--no-media-library", "--no-video-title-show", "--quiet", "--file-caching=100", "--disc-caching=100"} var ptrs []*byte for _, s := range strings { b, _ := windows.BytePtrFromString(s) @@ -42,6 +42,9 @@ func main() { media := call("libvlc_media_new_location", instance, uintptr(unsafe.Pointer(b))) runtime.KeepAlive(b) defer call("libvlc_media_release", media) + option, _ := windows.BytePtrFromString(":avcodec-hw=none") + call("libvlc_media_add_option", media, uintptr(unsafe.Pointer(option))) + runtime.KeepAlive(option) player := call("libvlc_media_player_new_from_media", media) defer call("libvlc_media_player_release", player) defer call("libvlc_media_player_stop", player) @@ -62,6 +65,19 @@ func main() { time.Sleep(120 * time.Millisecond) } call("libvlc_media_player_play", player) + if len(os.Args) == 4 { + waitTitle(1, 5*time.Second) + fmt.Println("Automatic first play: title", title()) + end := time.Now().Add(15 * time.Second) + for time.Now().Before(end) { + if state() == 6 { + fmt.Println("Playback ended without a menu; PASS") + return + } + time.Sleep(30 * time.Millisecond) + } + panic(fmt.Sprintf("autoplay did not finish, title %d state %d", title(), state())) + } waitTitle(0, 5*time.Second) time.Sleep(500 * time.Millisecond) fmt.Println("Initial menu: title", title(), "chapter", int32(call("libvlc_media_player_get_chapter", player))) diff --git a/docs/ENCODERS.md b/docs/ENCODERS.md index 4ecc5ab..0f79d46 100644 --- a/docs/ENCODERS.md +++ b/docs/ENCODERS.md @@ -1,8 +1,53 @@ # MPEG-2 encoder comparison -FFmpeg software `mpeg2video` is the implemented production default. It is not -declared the universal quality winner. Final choice should be based on actual -film scans, especially moving grain and fine texture. +HCenc is the default video encoder for new jobs. It uses the BEST profile and +two-pass VBR at 8 Mbps average / 9 Mbps maximum. FFmpeg remains available in +Settings / Video encoder. Existing started jobs retain their previous encoder +and compatible saved encodes. Neither encoder is declared a universal quality +winner; review actual film scans, especially moving grain and fine texture. + +## HCenc setup + +HCenc 0.28 requires **32-bit** AviSynth and FFMS2 even though easyDVD itself is +64-bit. These components are installed separately from the normal portable app. +The pinned setup helper downloads and verifies all three components, preserves +their notices and creates a private runtime without changing system AviSynth: + +```powershell +./scripts/prepare-hcenc.ps1 -OutputDir C:\Tools\easyDVD-HCenc +``` + +7-Zip is required for setup. Choose the resulting directory in Settings / HCenc +folder, or put it at `tools/hcenc` beside easyDVD.exe. Developers can run the +script without `-OutputDir` to use the detected `.tools/hcenc/bin` directory. +The runtime ZIP includes the same setup script; running it without `-OutputDir` +there installs into `tools/hcenc`, which the app detects automatically. +`EASYDVD_HCENC` and CLI `-hcenc-dir` are also supported. The directory contains +`HCenc_028.exe`, `AviSynth.dll` and `ffms2.dll`; mismatched 64-bit components are +rejected. Windows may need the Microsoft Visual C++ x86 runtime used by these +upstream components. A missing HCenc setup is reported explicitly; choose +FFmpeg in Settings to use the existing encoder instead. + +FFmpeg prepares DVD-resolution frames in a lossless FFV1 intermediate, preserving +the chosen crop, aspect, cadence and interlacing. HCenc performs both VBR passes +in one invocation. Its log must confirm both passes and the full prepared frame +count. FFmpeg encodes AC-3 audio (or silence for silent sources), muxes the DVD +stream and fully decodes it before checkpointing. Temporary lossless files are +removed after each encode attempt; the space estimate includes simultaneous +lossless intermediates. HCenc's progress advances at preparation and encoding +boundaries, so the displayed percentage can remain steady during either pass. + +## Automatic pillarbox removal + +For 16:9 input, easyDVD checks every decoded frame before resizing. It removes +only symmetric black side borders that leave the full centered 4:3 picture. +A single frame with picture content outside that area prevents cropping. +The check uses per-pixel luminance with a two-level tolerance above nominal +8-bit black for compression residue, retaining 16-bit analysis precision. +Uncertain or noisier borders keep the original frame. Letterbox bars are retained. +The cropped picture's actual display aspect controls scaling and DVD aspect; +rounding differences are padded rather than stretched. The border check adds a +decoding pass for new 16:9 encodes; completed compatible checkpoints are reused. ## Repeatable harness @@ -18,16 +63,15 @@ represented by fabricated results. ./bin/easydvd-benchmark.exe -input C:\Scans\sample.mov -output C:\Benchmarks\trial-02 -mpeg2enc C:\Tools\mpeg2enc.exe -hcenc C:\Tools\HCenc.exe -ffms2 C:\Tools\ffms2.dll ``` -HCenc requires a working, matching-bitness AviSynth installation and FFMS2 plugin. -These are optional benchmark tools and are not bundled into the app. Candidate -backends must be validated with the user's installed versions before using their -results. The harness does not switch the app's production encoder automatically. +The benchmark's optional `-hcenc` / `-ffms2` paths are independent of the app's +encoder setting and require the same matching-bitness AviSynth runtime. The +harness does not switch the app's encoder automatically. | Candidate | Initial settings | Integration considerations | |---|---|---| -| FFmpeg software MPEG-2 | Two-pass, 8 Mbps average, 9 Mbps peak, DVD VBV/GOP | Native current toolchain; implemented and tested | +| FFmpeg software MPEG-2 | Two-pass, 8 Mbps average, 9 Mbps peak, DVD VBV/GOP | Available alternative; implemented and tested | | mpeg2enc | DVD preset, quality 2, 8 Mbps maximum, progressive reference | Direct Y4M input; compare actual sizes because its rate-control target differs | -| HCenc | BEST profile, 8 Mbps average, 9 Mbps maximum | DVD-focused; AviSynth/FFMS2 dependency and bitness requirements | +| HCenc | BEST profile, two-pass, 8 Mbps average, 9 Mbps maximum | Default for new jobs; private x86 AviSynth/FFMS2 runtime | ## Evaluation diff --git a/docs/RELEASING.md b/docs/RELEASING.md index f21e24d..7b385d2 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -88,6 +88,11 @@ a compatible external installation or offers an explicit private download. No system-wide installation or PATH change is required. Packaging refuses to overwrite existing output directories. Close the app before rebuilding its exe. +HCenc is the default encoder for new jobs. Its HCenc/AviSynth/FFMS2 binaries +remain separate from the runtime ZIP; the included `scripts/prepare-hcenc.ps1` +downloads the pinned private x86 runtime into `tools/hcenc`. It requires 7-Zip. +See [encoder setup](ENCODERS.md) for manual location and the FFmpeg alternative. + The authoring toolchain is built once into a reusable local/CI cache. A valid cache is verified and reused on subsequent app builds and pushes. To rebuild the helpers explicitly, run `scripts/build-authoring.ps1` with an isolated scratch diff --git a/internal/app/cli.go b/internal/app/cli.go index 390b948..d10cf9c 100644 --- a/internal/app/cli.go +++ b/internal/app/cli.go @@ -65,6 +65,8 @@ func CLI(args []string) error { direct := fs.Bool("direct", false, "Read original sources directly") keep := fs.Bool("keep-work", false, "Retain intermediate media") thumbs := fs.Bool("thumbnails", false, "Thumbnail menus") + noMenu := fs.Bool("no-menu", false, "Start playback automatically; requires one included video per job") + combine := fs.Bool("combine-files", false, "Combine explicit video files into one DVD set") perPage := fs.Int("titles", 10, "Titles per page (1–12 text, 1–6 thumbnails)") tools := fs.Bool("check-tools", false, "Print tool diagnostics and exit") authoringOnly := fs.Bool("check-authoring-tools", false, "Check bundled authoring tools without requiring FFmpeg") @@ -72,6 +74,8 @@ func CLI(args []string) error { downloadFFmpeg := fs.Bool("download-ffmpeg", false, "Download and remember the recommended private FFmpeg installation") resume := fs.Bool("resume", false, "Resume saved queue") workers := fs.Int("encoders", 2, "Parallel encoders (1–2)") + encoder := fs.String("video-encoder", defaults.Encoder(), "Video encoder: HCenc or FFmpeg") + hcencDir := fs.String("hcenc-dir", "", "HCenc folder with 32-bit AviSynth.dll and ffms2.dll") if err := fs.Parse(args); err != nil { return err } @@ -121,9 +125,15 @@ func CLI(args []string) error { if *tools { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - b, _ := json.MarshalIndent(t.Check(ctx), "", " ") + selected := defaults + selected.VideoEncoder, selected.HCencDir = *encoder, strings.TrimSpace(*hcencDir) + statuses := append(t.Check(ctx), t.EncoderStatus(selected)) + b, _ := json.MarshalIndent(statuses, "", " ") fmt.Println(string(b)) - return t.Require() + if err := t.Require(); err != nil { + return err + } + return t.RequireEncoder(selected) } if *downloadFFmpeg && fs.NArg() == 0 && !*resume { return t.Require() @@ -142,7 +152,10 @@ func CLI(args []string) error { defaults.Media = *medium defaults.StageLocally = !*direct defaults.KeepWork = *keep + defaults.NoMenu = *noMenu defaults.Encoders = *workers + defaults.VideoEncoder = *encoder + defaults.HCencDir = strings.TrimSpace(*hcencDir) defaults.TitlesPerPage = *perPage if *efficient { defaults.Packing = "Space efficiency" @@ -185,10 +198,17 @@ func CLI(args []string) error { } } } - for _, folder := range fs.Args() { - if err = e.Add(folder); err != nil { + if *combine { + err = e.AddFiles(fs.Args()) + if err != nil { return err } + } else { + for _, folder := range fs.Args() { + if err = e.Add(folder); err != nil { + return err + } + } } e.Start() ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 90ce7a5..d9653a0 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -76,6 +76,10 @@ func New(st *store.Store, defaults model.Settings, t media.Tools, options ...Opt } for i := range e.jobs { j := &e.jobs[i] + if !j.Locked && j.Settings.VideoEncoder == "" { + j.Settings.VideoEncoder = settings.VideoEncoder + j.Settings.HCencDir = settings.HCencDir + } if len(j.ID) != 24 || strings.Trim(j.ID, "0123456789abcdef") != "" { cancel() return nil, fmt.Errorf("invalid saved job identifier") @@ -152,10 +156,17 @@ func (e *Engine) Add(folder string) error { return err } absolute = filepath.Clean(absolute) + info, err := fsops.Stat(e.ctx, absolute) + if err != nil { + return err + } + if info.Exists && !info.Directory { + return e.AddFiles([]string{absolute}) + } e.mu.Lock() defer e.mu.Unlock() for _, j := range e.jobs { - if strings.EqualFold(j.Folder, absolute) && j.State != model.Complete && j.State != model.Canceled { + if len(j.Sources) == 0 && strings.EqualFold(j.Folder, absolute) && j.State != model.Complete && j.State != model.Canceled { return fmt.Errorf("folder is already in the queue") } } @@ -166,10 +177,64 @@ func (e *Engine) Add(folder string) error { return nil } +// AddFiles records an explicit selection so rescans never pick up sibling files. +func (e *Engine) AddFiles(paths []string) error { + if len(paths) == 0 { + return fmt.Errorf("select at least one video file") + } + var sources []string + seen := map[string]bool{} + for _, path := range paths { + absolute, err := filepath.Abs(path) + if err != nil { + return err + } + absolute = filepath.Clean(absolute) + if !media.IsVideo(absolute) { + return fmt.Errorf("unsupported video file: %s", path) + } + key := strings.ToLower(absolute) + if !seen[key] { + sources = append(sources, absolute) + seen[key] = true + } + } + e.mu.Lock() + defer e.mu.Unlock() + for _, j := range e.jobs { + if j.State == model.Complete || j.State == model.Canceled { + continue + } + for _, path := range j.Sources { + if seen[strings.ToLower(path)] { + return fmt.Errorf("file is already in the queue: %s", path) + } + } + } + title := strings.TrimSuffix(filepath.Base(sources[0]), filepath.Ext(sources[0])) + if len(sources) > 1 { + title = filepath.Base(filepath.Dir(sources[0])) + } + j := model.Job{ID: model.ID(), Folder: filepath.Dir(sources[0]), Sources: sources, Title: title, State: model.Scanning, Stage: "Inspecting selected videos", Settings: e.settings, Created: time.Now()} + e.jobs = append(e.jobs, j) + e.persistLocked() + e.scanLocked(j.ID) + return nil +} + func (e *Engine) scanLocked(id string) { if _, ok := e.scans[id]; ok { return } + // Publish the pending scan before waking the queue loop. Otherwise a + // resumed scan can look idle and cause Start to disable processing. + i := e.index(id) + if i < 0 { + return + } + e.jobs[i].State = model.Scanning + e.jobs[i].ScanComplete = false + e.jobs[i].Stage = "Discovering videos" ctx, cancel := context.WithCancel(e.ctx) e.scans[id] = cancel e.wg.Add(1) @@ -212,7 +277,11 @@ func (e *Engine) scanLocked(id string) { case <-ctx.Done(): return } - v, err := e.tools.Probe(ctx, filepath.Join(job.Folder, relative), relative) + path := relative + if !filepath.IsAbs(path) { + path = filepath.Join(job.Folder, relative) + } + v, err := e.tools.Probe(ctx, path, relative) <-e.probeSlots if ctx.Err() != nil { return @@ -224,6 +293,7 @@ func (e *Engine) scanLocked(id string) { v.Label = previous.Label v.Excluded = previous.Excluded if previous.Fingerprint() == v.Fingerprint() { + v.CropLeft, v.CropRight, v.CropChecked = previous.CropLeft, previous.CropRight, previous.CropChecked v.Encoded = previous.Encoded v.EncodedSize = previous.EncodedSize v.EncodedHash = previous.EncodedHash @@ -247,7 +317,7 @@ func (e *Engine) scanLocked(id string) { } }() } - err := media.Discover(ctx, job.Folder, []string{job.Settings.WorkDir, job.Settings.OutputDir}, func(path string) { + found := func(path string) { e.mu.Lock() if i := e.index(id); i >= 0 { e.jobs[i].Discovered++ @@ -258,7 +328,19 @@ func (e *Engine) scanLocked(id string) { case paths <- path: case <-ctx.Done(): } - }) + } + var err error + if len(job.Sources) > 0 { + for _, path := range job.Sources { + relative, relErr := filepath.Rel(job.Folder, path) + if relErr != nil { + relative = path + } + found(relative) + } + } else { + err = media.Discover(ctx, job.Folder, []string{job.Settings.WorkDir, job.Settings.OutputDir}, found) + } close(paths) workers.Wait() e.mu.Lock() @@ -525,6 +607,9 @@ func (e *Engine) Edit(id, title, videoID, label string, excluded *bool) error { } } } + if excluded != nil { + e.refreshReadinessLocked(j) + } e.estimateLocked(j) e.persistLocked() return nil @@ -563,11 +648,34 @@ func (e *Engine) SetExcluded(id string, videoIDs []string, excluded bool) error j.Videos[k].Excluded = excluded } } + e.refreshReadinessLocked(j) e.estimateLocked(j) e.persistLocked() return nil } +func (e *Engine) refreshReadinessLocked(j *model.Job) { + if !j.ScanComplete || (j.State != model.Ready && j.State != model.Blocked) { + return + } + active := j.ActiveVideos() + if len(active) == 0 { + j.State, j.Error = model.Blocked, "No included video files" + return + } + for _, v := range active { + if v.Error != "" { + j.State, j.Error = model.Blocked, "One or more videos need attention; retry or exclude them" + return + } + } + if j.Settings.NoMenu && len(active) != 1 { + j.State, j.Error = model.Blocked, "No menu requires exactly one included video; enable menus or exclude the other files" + return + } + j.State, j.Stage, j.Error = model.Ready, "Ready", "" +} + func (e *Engine) SetSettings(id string, s model.Settings) error { if err := s.Validate(); err != nil { return err @@ -582,6 +690,7 @@ func (e *Engine) SetSettings(id string, s model.Settings) error { for i := range e.jobs { if !e.jobs[i].Locked && e.jobs[i].State != model.Complete { e.jobs[i].Settings = s + e.refreshReadinessLocked(&e.jobs[i]) e.estimateLocked(&e.jobs[i]) } } @@ -594,6 +703,7 @@ func (e *Engine) SetSettings(id string, s model.Settings) error { return fmt.Errorf("settings were locked when this job started; add the folder again for different encoding settings") } e.jobs[i].Settings = s + e.refreshReadinessLocked(&e.jobs[i]) e.estimateLocked(&e.jobs[i]) } e.persistLocked() @@ -663,6 +773,13 @@ func (e *Engine) loop() { break } j := e.jobs[i] + if j.Settings.NoMenu && len(j.ActiveVideos()) != 1 { + e.jobs[i].State = model.Blocked + e.jobs[i].Error = "No menu requires exactly one included video; enable menus or exclude the other files" + e.persistLocked() + e.mu.Unlock() + continue + } ctx, cancel := context.WithCancel(e.ctx) e.cancels[j.ID] = cancel delete(e.pauses, j.ID) @@ -782,6 +899,17 @@ func checkSpace(ctx context.Context, s model.Settings, videos []model.Video) err if s.StageLocally { needWork += stage * int64(s.Encoders+1) } + if s.Encoder() == "HCenc" { + // Bound concurrent lossless intermediates by raw 4:2:0 frame size, + // with headroom for the container/codec. FFV1 normally needs less. + var largest float64 + for _, v := range videos { + if v.Encoded == "" && v.Duration > largest { + largest = v.Duration + } + } + needWork += int64(largest * media.Ratio(s.FPS()) * 720 * float64(s.Height()) * 1.5 * 1.1 * float64(s.Encoders)) + } output := remaining for _, v := range videos { output += v.EncodedSize @@ -814,6 +942,9 @@ func (e *Engine) run(ctx context.Context, j model.Job) error { if err := j.Settings.Validate(); err != nil { return err } + if err := e.tools.RequireEncoder(j.Settings); err != nil { + return err + } if err := fsops.RequireLocal(ctx, j.Settings.WorkDir); err != nil { return err } @@ -821,6 +952,9 @@ func (e *Engine) run(ctx context.Context, j model.Job) error { if len(videos) == 0 { return fmt.Errorf("no included videos") } + if j.Settings.NoMenu && len(videos) != 1 { + return fmt.Errorf("no menu requires exactly one included video; enable menus or exclude the other files") + } for _, v := range videos { if v.Error != "" && v.Duration <= 0 { return fmt.Errorf("%s: %s", v.Relative, v.Error) @@ -1060,6 +1194,16 @@ func (e *Engine) encode(ctx context.Context, j model.Job, videos []model.Video, release() continue } + if v.Encoded == "" && !v.CropChecked { + e.update(j.ID, false, func(job *model.Job) { job.Stage = "Checking black borders · " + v.Label }) + var err error + v, err = e.tools.DetectPillarbox(ctx, v, task.input, log) + if err != nil { + fail(v, err) + release() + continue + } + } v.Thumbnail = filepath.Join(dir, "thumbnail.jpg") if _, err := os.Stat(v.Thumbnail); err != nil { if err = e.tools.Thumbnail(ctx, v, task.input, v.Thumbnail, log); err != nil { diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.go index 2e2db26..646b2b3 100644 --- a/internal/engine/engine_test.go +++ b/internal/engine/engine_test.go @@ -2,6 +2,7 @@ package engine import ( "context" + "easydvd/internal/fsops" "easydvd/internal/media" "easydvd/internal/model" "easydvd/internal/store" @@ -11,6 +12,22 @@ import ( "time" ) +func TestMain(m *testing.M) { + if len(os.Args) > 1 && os.Args[1] == "--fs-worker" { + if err := fsops.Worker(os.Args[2:], os.Stdout); err != nil { + os.Exit(1) + } + os.Exit(0) + } + if len(os.Args) > 2 && os.Args[1] == "--scan-worker" { + if err := media.ScanWorker(os.Args[2], os.Args[3:], os.Stdout); err != nil { + os.Exit(1) + } + os.Exit(0) + } + os.Exit(m.Run()) +} + func TestRecoverAndLockSettings(t *testing.T) { st, err := store.Open(filepath.Join(t.TempDir(), "q.db")) if err != nil { @@ -116,6 +133,82 @@ func TestBulkExclusionIsAtomicAndPersisted(t *testing.T) { } } +func TestExcludingFailedFilesUnblocksJob(t *testing.T) { + st, err := store.Open(filepath.Join(t.TempDir(), "q.db")) + if err != nil { + t.Fatal(err) + } + defer st.Close() + s := model.DefaultSettings(t.TempDir()) + j := model.Job{ID: model.ID(), State: model.Blocked, ScanComplete: true, Settings: s, Error: "One or more videos could not be inspected; retry or exclude them", Videos: []model.Video{{ID: "good", Duration: 10}, {ID: "bad", Error: "not a video"}}} + if err = st.Save([]model.Job{j}); err != nil { + t.Fatal(err) + } + e, err := New(st, s, media.Tools{}) + if err != nil { + t.Fatal(err) + } + defer e.Close() + if err = e.SetExcluded(j.ID, []string{"bad"}, true); err != nil { + t.Fatal(err) + } + if got := e.Snapshot().Jobs[0]; got.State != model.Ready || got.Error != "" { + t.Fatal(got) + } + include := false + if err = e.Edit(j.ID, "", "bad", "", &include); err != nil { + t.Fatal(err) + } + if e.Snapshot().Jobs[0].State != model.Blocked { + t.Fatal("re-included failure was accepted") + } + exclude := true + if err = e.Edit(j.ID, "", "bad", "", &exclude); err != nil { + t.Fatal(err) + } + if e.Snapshot().Jobs[0].State != model.Ready { + t.Fatal("per-file exclusion did not unblock") + } + if err = e.SetExcluded(j.ID, []string{"good"}, true); err != nil { + t.Fatal(err) + } + if e.Snapshot().Jobs[0].State != model.Blocked { + t.Fatal("empty job became ready") + } +} + +func TestInvalidNoMenuJobStaysEditable(t *testing.T) { + st, err := store.Open(filepath.Join(t.TempDir(), "q.db")) + if err != nil { + t.Fatal(err) + } + defer st.Close() + s := model.DefaultSettings(t.TempDir()) + s.NoMenu = true + j := model.Job{ID: model.ID(), State: model.Ready, ScanComplete: true, Settings: s, Videos: []model.Video{{ID: "one", Duration: 10}, {ID: "two", Duration: 10}}} + if err = st.Save([]model.Job{j}); err != nil { + t.Fatal(err) + } + e, err := New(st, s, media.Tools{}) + if err != nil { + t.Fatal(err) + } + defer e.Close() + e.Start() + deadline := time.Now().Add(time.Second) + for time.Now().Before(deadline) { + got := e.Snapshot().Jobs[0] + if got.State == model.Blocked { + if got.Locked { + t.Fatal("invalid no-menu choice locked settings") + } + return + } + time.Sleep(5 * time.Millisecond) + } + t.Fatal("invalid no-menu job was not blocked") +} + func TestClearQueueStopsWorkersAndKeepsFiles(t *testing.T) { st, err := store.Open(filepath.Join(t.TempDir(), "q.db")) if err != nil { diff --git a/internal/integration/issues_test.go b/internal/integration/issues_test.go new file mode 100644 index 0000000..d1e040c --- /dev/null +++ b/internal/integration/issues_test.go @@ -0,0 +1,232 @@ +package integration + +import ( + "bytes" + "context" + "easydvd/internal/engine" + "easydvd/internal/media" + "easydvd/internal/model" + "easydvd/internal/process" + "easydvd/internal/store" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func issueTools(t *testing.T) (media.Tools, context.Context) { + t.Helper() + if os.Getenv("EASYDVD_INTEGRATION") != "1" { + t.Skip("set EASYDVD_INTEGRATION=1") + } + tools := media.FindTools() + if err := tools.Require(); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + t.Cleanup(cancel) + return tools, ctx +} + +func TestSelectedFilesSurviveRescanAndExclusion(t *testing.T) { + tools, ctx := issueTools(t) + dir := t.TempDir() + source := filepath.Join(dir, "sources") + if err := os.MkdirAll(filepath.Join(source, "other"), 0755); err != nil { + t.Fatal(err) + } + first, second := filepath.Join(source, "clip.mp4"), filepath.Join(source, "other", "clip.mp4") + for _, name := range []string{first, second, filepath.Join(source, "unselected.mp4")} { + if err := process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=320x240:r=25", "-t", "1", "-c:v", "libx264", name}, process.Options{}); err != nil { + t.Fatal(err) + } + } + broken := filepath.Join(source, "broken.mp4") + if err := os.WriteFile(broken, []byte("not a video"), 0644); err != nil { + t.Fatal(err) + } + s := model.DefaultSettings(dir) + s.VideoEncoder = "FFmpeg" + s.Encoders = 1 + st, err := store.Open(filepath.Join(dir, "queue.db")) + if err != nil { + t.Fatal(err) + } + defer st.Close() + e, err := engine.New(st, s, tools) + if err != nil { + t.Fatal(err) + } + defer e.Close() + if err = e.AddFiles([]string{first, second, broken}); err != nil { + t.Fatal(err) + } + j := wait(t, e, func(s engine.Snapshot) bool { return s.Jobs[0].State != model.Scanning }).Jobs[0] + if j.State != model.Blocked || len(j.Videos) != 3 { + t.Fatal(j.State, j.Error, len(j.Videos)) + } + var badID string + for _, v := range j.Videos { + if v.Error != "" { + badID = v.ID + } + } + if badID == "" { + t.Fatal("broken fixture was not flagged") + } + if err = e.SetExcluded(j.ID, []string{badID}, true); err != nil { + t.Fatal(err) + } + if e.Snapshot().Jobs[0].State != model.Ready { + t.Fatal("exclusion did not enable start") + } + // Restart as an interrupted scan, forcing rediscovery from saved Sources. + e.Close() + j = e.Snapshot().Jobs[0] + j.ScanComplete, j.State = false, model.Paused + if err = st.Save([]model.Job{j}); err != nil { + t.Fatal(err) + } + e, err = engine.New(st, s, tools) + if err != nil { + t.Fatal(err) + } + defer e.Close() + e.Start() + j = wait(t, e, func(s engine.Snapshot) bool { + return s.Jobs[0].State == model.Complete || s.Jobs[0].State == model.Blocked + }).Jobs[0] + if j.State != model.Complete || len(j.Videos) != 3 || len(j.ActiveVideos()) != 2 || j.ActiveVideos()[0].ID == j.ActiveVideos()[1].ID { + t.Fatal(j.State, j.Error, j.Videos) + } + if err = e.AddFiles([]string{first}); err != nil { + t.Fatal("single file should be allowed after previous job completes", err) + } +} + +func TestSingleFileAutoplayAndPillarbox(t *testing.T) { + tools, ctx := issueTools(t) + dir := t.TempDir() + source := filepath.Join(dir, "Film & café Ω") + if err := os.MkdirAll(source, 0755); err != nil { + t.Fatal(err) + } + path := filepath.Join(source, "video.mp4") + if err := process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=960x720:r=25,pad=1280:720:160:0", "-t", "2", "-c:v", "libx264", path}, process.Options{}); err != nil { + t.Fatal(err) + } + for _, encoder := range []string{"FFmpeg", "HCenc"} { + for _, standard := range []string{"PAL", "NTSC"} { + t.Run(encoder+"/"+standard, func(t *testing.T) { + s := model.DefaultSettings(dir) + s.VideoEncoder, s.Standard, s.NoMenu, s.KeepWork, s.Encoders = encoder, standard, true, true, 1 + if encoder == "HCenc" && tools.HCencFolder(s) == "" { + t.Skip("HCenc runtime unavailable") + } + s.WorkDir = filepath.Join(dir, encoder+standard+" café Ω") + s.OutputDir = filepath.Join(dir, encoder+standard+" output") + st, err := store.Open(filepath.Join(s.WorkDir, "queue.db")) + if err != nil { + t.Fatal(err) + } + defer st.Close() + e, err := engine.New(st, s, tools) + if err != nil { + t.Fatal(err) + } + defer e.Close() + if err = e.Add(path); err != nil { + t.Fatal(err) + } + e.Start() + j := wait(t, e, func(s engine.Snapshot) bool { + return s.Jobs[0].State == model.Complete || s.Jobs[0].State == model.Blocked + }).Jobs[0] + if j.State != model.Complete { + t.Fatal(j.Error) + } + v := j.Videos[0] + if v.CropLeft != 160 || v.CropRight != 160 || v.Aspect() != "4:3" { + t.Fatal(v) + } + authorDir := filepath.Join(s.WorkDir, "jobs", j.ID, "generation-"+j.Generation, "disc-001") + xml, err := os.ReadFile(filepath.Join(authorDir, "dvd.xml")) + if err != nil || !strings.Contains(string(xml), "jump title 1;") || strings.Contains(string(xml), "") { + t.Fatal(string(xml), err) + } + if pages, _ := filepath.Glob(filepath.Join(authorDir, "page-*")); len(pages) != 0 { + t.Fatal("menu-free job generated menu assets", pages) + } + var out bytes.Buffer + if err = process.Run(ctx, tools.FFprobe, []string{"-v", "error", "-f", "dvdvideo", "-title", "1", "-i", j.Discs[0].ISO, "-show_streams", "-show_format", "-of", "json"}, process.Options{Stdout: &out}); err != nil { + t.Fatal(err) + } + var probe struct { + Streams []struct { + Codec string `json:"codec_name"` + DAR string `json:"display_aspect_ratio"` + Height int `json:"height"` + } + Format struct { + Duration string `json:"duration"` + } + } + if err = json.Unmarshal(out.Bytes(), &probe); err != nil { + t.Fatal(err) + } + if len(probe.Streams) < 2 || probe.Streams[0].Codec != "mpeg2video" || probe.Streams[0].DAR != "4:3" || probe.Streams[0].Height != s.Height() || probe.Streams[1].Codec != "ac3" { + t.Fatal(out.String()) + } + if duration := media.Ratio(probe.Format.Duration); duration < 1.92 || duration > 2.08 { + t.Fatal("duration drift", duration) + } + if err = process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-xerror", "-f", "dvdvideo", "-title", "1", "-i", j.Discs[0].ISO, "-f", "null", "NUL"}, process.Options{}); err != nil { + t.Fatal(err) + } + if encoder == "HCenc" { + log, err := os.ReadFile(filepath.Join(filepath.Dir(v.Encoded), "hcenc.log")) + if err != nil || !strings.Contains(string(log), "encoding - pass 2") { + t.Fatal("no two-pass evidence", err) + } + } + }) + } + } +} + +func TestWiderFramePreventsPillarboxCrop(t *testing.T) { + tools, ctx := issueTools(t) + dir := t.TempDir() + path := filepath.Join(dir, "changes.mkv") + // The final frame contains genuine 16:9 picture content, outside the + // otherwise consistent black borders. Sampling would miss this case. + filter := "testsrc2=s=1280x720:r=25,drawbox=x=0:y=0:w=160:h=ih:c=black:t=fill:enable='lt(t,1.96)',drawbox=x=1120:y=0:w=160:h=ih:c=black:t=fill:enable='lt(t,1.96)'" + if err := process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-y", "-f", "lavfi", "-i", filter, "-t", "2", "-c:v", "ffv1", path}, process.Options{}); err != nil { + t.Fatal(err) + } + v := model.Video{Width: 1280, Height: 720, DAR: 16.0 / 9, FPS: 25, Duration: 2} + v, err := tools.DetectPillarbox(ctx, v, path, nil) + if err != nil || !v.CropChecked || v.CropLeft != 0 || v.CropRight != 0 { + t.Fatal(v, err) + } + t.Log(fmt.Sprintf("Retained full 16:9 frame after checking entire clip: %s", v.Aspect())) +} + +func TestTinyDetailInBorderPreventsCropping(t *testing.T) { + tools, ctx := issueTools(t) + dir := t.TempDir() + path := filepath.Join(dir, "detail.mkv") + // A 2x2 mark is too small to change a black column's average reliably. + // Per-pixel bounding boxes must retain it, even on one frame only. + filter := "testsrc2=s=960x720:r=25,pad=1280:720:160:0,drawbox=x=10:y=10:w=2:h=2:c=white:t=fill:enable='gte(t,0.96)'" + if err := process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-y", "-f", "lavfi", "-i", filter, "-t", "1", "-c:v", "ffv1", path}, process.Options{}); err != nil { + t.Fatal(err) + } + v, err := tools.DetectPillarbox(ctx, model.Video{Width: 1280, Height: 720, DAR: 16.0 / 9, Duration: 1}, path, nil) + if err != nil || v.CropLeft != 0 || v.CropRight != 0 { + t.Fatal("border detail was removed", v, err) + } +} diff --git a/internal/integration/pipeline_test.go b/internal/integration/pipeline_test.go index 4464430..caf0127 100644 --- a/internal/integration/pipeline_test.go +++ b/internal/integration/pipeline_test.go @@ -52,6 +52,17 @@ func wait(t *testing.T, e *engine.Engine, predicate func(engine.Snapshot) bool) } } func TestPipeline(t *testing.T) { + testPipeline(t, "FFmpeg") +} + +func TestHCencPipeline(t *testing.T) { + if os.Getenv("EASYDVD_INTEGRATION") != "1" || media.FindTools().HCencFolder(model.DefaultSettings(t.TempDir())) == "" { + t.Skip("HCenc runtime unavailable") + } + testPipeline(t, "HCenc") +} + +func testPipeline(t *testing.T, encoder string) { if os.Getenv("EASYDVD_INTEGRATION") != "1" { t.Skip("set EASYDVD_INTEGRATION=1 to run real encoders and DVD authoring") } @@ -93,6 +104,7 @@ func TestPipeline(t *testing.T) { for _, standard := range []string{"PAL", "NTSC"} { t.Run(standard, func(t *testing.T) { s := model.DefaultSettings(dir) + s.VideoEncoder = encoder s.Standard = standard s.OutputDir = filepath.Join(dir, "output-"+standard) s.WorkDir = filepath.Join(dir, "work-"+standard) diff --git a/internal/media/author.go b/internal/media/author.go index e83680d..446bf72 100644 --- a/internal/media/author.go +++ b/internal/media/author.go @@ -14,6 +14,11 @@ import ( ) func AuthorXML(videos []model.Video, pages []menu.Page, s model.Settings, dir string) string { + if s.NoMenu && len(videos) == 1 { + v := videos[0] + relative, _ := filepath.Rel(dir, v.Encoded) + return fmt.Sprintf("jump title 1;\n", strings.ToLower(s.Standard), v.Aspect(), menu.Escape(filepath.ToSlash(relative))) + } var b strings.Builder b.WriteString("\ng0 = 0; g3 = 1024; jump vmgm menu 1;\n") aspect := s.Menu.Defaults().Aspect @@ -84,12 +89,19 @@ func (t Tools) Author(ctx context.Context, j model.Job, disc model.Disc, total i if len(videos) == 0 { return "", fmt.Errorf("cannot author an empty disc") } - if err := stage("Creating menus"); err != nil { - return "", err + if j.Settings.NoMenu && (len(j.ActiveVideos()) != 1 || len(videos) != 1) { + return "", fmt.Errorf("no menu requires exactly one included video") } - pages, err := menu.Render(dir, j.Title, disc.Number, total, videos, j.Settings) - if err != nil { - return "", err + var pages []menu.Page + var err error + if !j.Settings.NoMenu { + if err = stage("Creating menus"); err != nil { + return "", err + } + pages, err = menu.Render(dir, j.Title, disc.Number, total, videos, j.Settings) + if err != nil { + return "", err + } } for _, p := range pages { if err := stage(fmt.Sprintf("Creating menu page %d of %d", p.Number, len(pages))); err != nil { diff --git a/internal/media/discover.go b/internal/media/discover.go index 2803f59..f5d55d6 100644 --- a/internal/media/discover.go +++ b/internal/media/discover.go @@ -33,6 +33,9 @@ func ScanWorker(root string, exclude []string, out io.Writer) error { return err } if d.IsDir() { + if d.Name() == "__MACOSX" { + return filepath.SkipDir + } for _, x := range exclude { if x != "" && filepath.Clean(path) == filepath.Clean(x) { return filepath.SkipDir diff --git a/internal/media/discover_test.go b/internal/media/discover_test.go new file mode 100644 index 0000000..187641b --- /dev/null +++ b/internal/media/discover_test.go @@ -0,0 +1,38 @@ +package media + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "testing" +) + +func TestScanSkipsAppleDoubleMetadata(t *testing.T) { + dir := t.TempDir() + for _, name := range []string{"film.mp4", "._film.mp4", ".hidden-but-real.MOV", "nested/clip.mkv", "nested/._clip.mkv", "__MACOSX/ghost.mp4", "notes.txt"} { + path := filepath.Join(dir, name) + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("fixture"), 0644); err != nil { + t.Fatal(err) + } + } + var out bytes.Buffer + if err := ScanWorker(dir, nil, &out); err != nil { + t.Fatal(err) + } + decoder := json.NewDecoder(&out) + var paths []string + for decoder.More() { + var r ScanRecord + if err := decoder.Decode(&r); err != nil { + t.Fatal(err) + } + paths = append(paths, filepath.ToSlash(r.Path)) + } + if len(paths) != 3 || paths[0] != ".hidden-but-real.MOV" || paths[1] != "film.mp4" || paths[2] != "nested/clip.mkv" { + t.Fatal(paths) + } +} diff --git a/internal/media/encode.go b/internal/media/encode.go index 8bd5c21..d7ece57 100644 --- a/internal/media/encode.go +++ b/internal/media/encode.go @@ -44,7 +44,7 @@ func HashFile(ctx context.Context, path string) (string, error) { } func ValidArtifact(ctx context.Context, v model.Video, s model.Settings) bool { - if v.Encoded == "" || v.EncodingKey != s.EncodingKey()+v.Fingerprint() { + if v.Encoded == "" || v.EncodingKey != v.ArtifactKey(s) { return false } st, e := os.Stat(v.Encoded) @@ -62,10 +62,11 @@ func VideoFilter(v model.Video, s model.Settings) (string, bool) { } h := s.Height() w, scaledH := 720, h - if v.DAR > target { - scaledH = int(math.Round(float64(h)*target/v.DAR/2)) * 2 + dar := v.ContentDAR() + if dar > target { + scaledH = int(math.Round(float64(h)*target/dar/2)) * 2 } else { - w = int(math.Round(720*v.DAR/target/2)) * 2 + w = int(math.Round(720*dar/target/2)) * 2 } if w < 2 { w = 2 @@ -77,6 +78,9 @@ func VideoFilter(v model.Video, s model.Settings) (string, bool) { matching := s.Standard == "PAL" && math.Abs(v.FPS-25) < .02 || s.Standard == "NTSC" && math.Abs(v.FPS-30000.0/1001) < .02 keep := interlaced && matching && v.Rotation == 0 filters := []string{} + if v.CropLeft+v.CropRight > 0 { + filters = append(filters, fmt.Sprintf("crop=%d:%d:%d:0", v.Width-v.CropLeft-v.CropRight, v.Height, v.CropLeft)) + } if interlaced && !keep { filters = append(filters, "bwdif=mode=send_frame:parity=auto:deint=all") } @@ -132,6 +136,11 @@ func EncodeArgs(v model.Video, s model.Settings, input, passlog, output string, } func (t Tools) Encode(ctx context.Context, v model.Video, s model.Settings, input, dir string, log io.Writer, progress func(float64)) (model.Video, error) { + var err error + v, err = t.DetectPillarbox(ctx, v, input, log) + if err != nil { + return v, err + } if err := os.MkdirAll(dir, 0755); err != nil { return v, err } @@ -142,22 +151,28 @@ func (t Tools) Encode(ctx context.Context, v model.Video, s model.Settings, inpu if runtime.GOOS == "windows" { null = "NUL" } - for pass := 1; pass <= 2; pass++ { - out := null - if pass == 2 { - out = part + if s.Encoder() == "HCenc" { + if err := t.encodeHCenc(ctx, v, s, input, dir, log, progress); err != nil { + return v, err } - p := pass - err := process.Run(ctx, t.FFmpeg, EncodeArgs(v, s, input, passlog, out, pass), process.Options{Dir: dir, Log: log, Line: func(line string) { - if strings.HasPrefix(line, "out_time_us=") { - us, _ := strconv.ParseFloat(strings.TrimPrefix(line, "out_time_us="), 64) - if progress != nil { - progress(math.Min(1, (float64(p-1)+us/1e6/v.Duration)/2)) + } else { + for pass := 1; pass <= 2; pass++ { + out := null + if pass == 2 { + out = part + } + p := pass + err := process.Run(ctx, t.FFmpeg, EncodeArgs(v, s, input, passlog, out, pass), process.Options{Dir: dir, Log: log, Line: func(line string) { + if strings.HasPrefix(line, "out_time_us=") { + us, _ := strconv.ParseFloat(strings.TrimPrefix(line, "out_time_us="), 64) + if progress != nil { + progress(math.Min(1, (float64(p-1)+us/1e6/v.Duration)/2)) + } } + }}) + if err != nil { + return v, err } - }}) - if err != nil { - return v, err } } // A complete decode catches truncated streams before they become reusable checkpoints. @@ -173,7 +188,7 @@ func (t Tools) Encode(ctx context.Context, v model.Video, s model.Settings, inpu } v.Encoded = final v.EncodedSize = st.Size() - v.EncodingKey = s.EncodingKey() + v.Fingerprint() + v.EncodingKey = v.ArtifactKey(s) v.EncodedHash, err = HashFile(ctx, final) return v, err } @@ -181,11 +196,15 @@ func (t Tools) Encode(ctx context.Context, v model.Video, s model.Settings, inpu func (t Tools) Thumbnail(ctx context.Context, v model.Video, input, path string, log io.Writer) error { seconds := math.Min(v.Duration*.25, 30) w, h := 320, 240 - if v.DAR >= 4.0/3 { - h = max(2, int(math.Round(320/v.DAR/2))*2) + dar := v.ContentDAR() + if dar >= 4.0/3 { + h = max(2, int(math.Round(320/dar/2))*2) } else { - w = max(2, int(math.Round(240*v.DAR/2))*2) + w = max(2, int(math.Round(240*dar/2))*2) } filter := fmt.Sprintf("scale=%d:%d:flags=lanczos,pad=320:240:(ow-iw)/2:(oh-ih)/2,setsar=1", w, h) + if v.CropLeft+v.CropRight > 0 { + filter = fmt.Sprintf("crop=%d:%d:%d:0,", v.Width-v.CropLeft-v.CropRight, v.Height, v.CropLeft) + filter + } return process.Run(ctx, t.FFmpeg, []string{"-hide_banner", "-nostdin", "-y", "-ss", fmt.Sprintf("%.3f", seconds), "-i", input, "-map", fmt.Sprintf("0:%d", v.VideoStream), "-vf", filter, "-frames:v", "1", "-update", "1", path}, process.Options{Log: log}) } diff --git a/internal/media/encode_test.go b/internal/media/encode_test.go index 0343a4f..d1472da 100644 --- a/internal/media/encode_test.go +++ b/internal/media/encode_test.go @@ -72,3 +72,17 @@ func TestAuthorNavigation(t *testing.T) { t.Fatal("navigation must not generate a disc-wide jump-pad command table", x) } } + +func TestMenuFreeFirstPlay(t *testing.T) { + s := model.DefaultSettings(t.TempDir()) + s.NoMenu = true + x := AuthorXML([]model.Video{{Encoded: filepath.Join("work", "a & b.mpg"), DAR: 4.0 / 3}}, nil, s, "work") + for _, want := range []string{"jump title 1;", "exit;", "a & b.mpg"} { + if !strings.Contains(x, want) { + t.Fatal(x) + } + } + if strings.Contains(x, "") || strings.Contains(x, "page-") || strings.Contains(x, " 1 { + count, _ = strconv.Atoi(frames[1]) + } + if preparedFrames <= 0 || count != preparedFrames || !strings.Contains(log, "encoding - pass 1") || !strings.Contains(log, "encoding - pass 2") { + return fmt.Errorf("HCenc did not complete both passes for all %d prepared frames; inspect the job log", preparedFrames) + } + return nil +} diff --git a/internal/media/hcenc_test.go b/internal/media/hcenc_test.go new file mode 100644 index 0000000..fbf2dc8 --- /dev/null +++ b/internal/media/hcenc_test.go @@ -0,0 +1,53 @@ +package media + +import ( + "easydvd/internal/model" + "strings" + "testing" +) + +func TestHCencDVDSettings(t *testing.T) { + s := model.DefaultSettings(t.TempDir()) + v := model.Video{DAR: 16.0 / 9, FPS: 25, FieldOrder: "bb"} + ini := HCencINI(v, s) + for _, want := range []string{"*PROFILE BEST", "*BITRATE 8000", "*MAXBITRATE 9000", "*AUTOGOP 15", "*CLOSEDGOPS", "*ASPECT 16:9", "*INTERLACED\n*BFF", "*COLOUR 5", "*SILENT", "*WAIT 0"} { + if !strings.Contains(ini, want) { + t.Fatal(want, ini) + } + } + s.Standard = "NTSC" + ini = HCencINI(v, s) + if !strings.Contains(ini, "*AUTOGOP 18") || !strings.Contains(ini, "*PROGRESSIVE\n*PROG_SEQ") || strings.Contains(ini, "*INTERLACED") || !strings.Contains(ini, "*COLOUR 6") { + t.Fatal(ini) + } + for _, forbidden := range []string{"*CQ", "*1PASS", "*LOSSLESS"} { + if strings.Contains(ini, forbidden) { + t.Fatal(ini) + } + } +} + +func TestHCencMustCompleteBothPassesAndEveryFrame(t *testing.T) { + valid := "encoding - pass 1\nencoding - pass 2\nnr. of frames: 50\r\n" + if err := validateHCencLog(valid, 50); err != nil { + t.Fatal(err) + } + for _, log := range []string{"", strings.ReplaceAll(valid, "pass 2", "pass failed"), strings.ReplaceAll(valid, "50", "49")} { + if err := validateHCencLog(log, 50); err == nil { + t.Fatal("incomplete encode was accepted", log) + } + } + s := model.DefaultSettings(t.TempDir()) + if s.Encoder() != "HCenc" { + t.Fatal("new jobs must default to HCenc") + } + key := s.EncodingKey() + s.VideoEncoder = "FFmpeg" + if s.EncodingKey() == key { + t.Fatal("encoder changes must invalidate cache") + } + s.VideoEncoder = "" + if s.Encoder() != "FFmpeg" || s.EncodingKey() != model.Hash("mpeg2-v2-8000-9000-ac3-256-2pass-PAL") { + t.Fatal("legacy jobs lost their encoding profile") + } +} diff --git a/internal/media/pillarbox.go b/internal/media/pillarbox.go new file mode 100644 index 0000000..623b747 --- /dev/null +++ b/internal/media/pillarbox.go @@ -0,0 +1,95 @@ +package media + +import ( + "context" + "easydvd/internal/model" + "easydvd/internal/process" + "fmt" + "io" + "math" + "regexp" + "runtime" + "strconv" + "strings" +) + +var cropPattern = regexp.MustCompile(`crop=(-?\d+):(-?\d+):(-?\d+):(-?\d+)`) + +// pillarboxEvidence keeps the union of visible content over the entire video. +// A single wider frame prevents cropping. Letterbox bars are never removed. +type pillarboxEvidence struct { + width, height, border int + frames, visible int + safe bool + pending string +} + +func (p *pillarboxEvidence) Write(data []byte) (int, error) { + p.pending += string(data) + end := strings.LastIndexByte(p.pending, '\n') + if end < 0 { + return len(data), nil + } + complete := p.pending[:end+1] + p.pending = p.pending[end+1:] + for _, match := range cropPattern.FindAllStringSubmatch(complete, -1) { + p.frames++ + values := [4]int{} + for i := range values { + values[i], _ = strconv.Atoi(match[i+1]) + } + w, h, x, y := values[0], values[1], values[2], values[3] + if w <= 0 || h <= 0 { + continue + } // all-black frame + if x < 0 || y < 0 || x+w > p.width || y+h > p.height { + p.safe = false + continue + } + p.visible++ + if x < p.border || x+w > p.width-p.border { + p.safe = false + } + } + return len(data), nil +} + +func (t Tools) DetectPillarbox(ctx context.Context, v model.Video, input string, log io.Writer) (model.Video, error) { + if v.CropChecked { + return v, nil + } + // Narrow scope: only a 16:9 container containing a centered 4:3 image. + if math.Abs(v.DAR-16.0/9) > .025 || v.Width <= 0 || v.Height <= 0 { + v.CropChecked = true + return v, nil + } + border := int(math.Floor(float64(v.Width)*(1-(4.0/3)/v.DAR)/4)) * 2 + if border < 2 { + v.CropChecked = true + return v, nil + } + evidence := &pillarboxEvidence{width: v.Width, height: v.Height, border: border, safe: true} + null := "/dev/null" + if runtime.GOOS == "windows" { + null = "NUL" + } + // Inspect every decoded frame, before any resize. The low threshold is + // deliberate: noisy or uncertain borders retain the full source image. + // bbox checks individual pixels. cropdetect's line averages could miss a + // small logo or a faint detail in an otherwise black border. Keep 16-bit + // precision while normalizing full/limited range to a common black level. + // Allow two 8-bit luma levels above nominal black for compression ringing; + // ProRes side borders can contain this invisible residue across a block. + err := process.Run(ctx, t.FFmpeg, []string{"-hide_banner", "-nostdin", "-v", "info", "-xerror", "-i", input, "-map", fmt.Sprintf("0:%d", v.VideoStream), "-vf", "scale=iw:ih:in_range=auto:out_range=tv,format=yuv444p16le,bbox=min_val=4608", "-an", "-sn", "-dn", "-f", "null", null}, process.Options{Log: evidence}) + if err != nil { + return v, fmt.Errorf("checking pillarbox borders: %w", err) + } + v.CropChecked = true + if evidence.safe && evidence.visible >= 3 { + v.CropLeft, v.CropRight = border, border + if log != nil { + fmt.Fprintf(log, "\nConfirmed 4:3 pillarbox: %s, cropped %d black pixels per side after checking %d frames\n", v.Relative, border, evidence.frames) + } + } + return v, nil +} diff --git a/internal/media/pillarbox_test.go b/internal/media/pillarbox_test.go new file mode 100644 index 0000000..e7528a9 --- /dev/null +++ b/internal/media/pillarbox_test.go @@ -0,0 +1,42 @@ +package media + +import ( + "easydvd/internal/model" + "fmt" + "strings" + "testing" +) + +func TestPillarboxEvidenceRejectsAnyWiderFrame(t *testing.T) { + p := &pillarboxEvidence{width: 1920, height: 1080, border: 240, safe: true} + // Writes may split a crop diagnostic at any byte. + _, _ = p.Write([]byte("crop=1440:1080:24")) + _, _ = p.Write([]byte("0:0\n")) + if !p.safe || p.visible != 1 { + t.Fatal(p) + } + for _, crop := range []string{"1440:1080:240:0", "0:0:0:0", "-1918:-1078:1918:1078"} { + _, _ = fmt.Fprintf(p, "crop=%s\n", crop) + } + if !p.safe { + t.Fatal("black frames should not invalidate established borders") + } + _, _ = p.Write([]byte("crop=1920:1080:0:0\n")) + if p.safe { + t.Fatal("one wider frame must veto cropping") + } +} + +func TestPillarboxKeepsContentAspectAndCacheIdentity(t *testing.T) { + s := model.DefaultSettings(t.TempDir()) + v := model.Video{Width: 1920, Height: 1080, DAR: 16.0 / 9, CropLeft: 240, CropRight: 240, FPS: 25} + filter, _ := VideoFilter(v, s) + if v.Aspect() != "4:3" || v.ContentDAR() != 4.0/3 || !strings.HasPrefix(filter, "crop=1440:1080:240:0,scale=720:576:") { + t.Fatal(filter, v.ContentDAR()) + } + before := v.ArtifactKey(s) + v.CropLeft, v.CropRight = 0, 0 + if before == v.ArtifactKey(s) { + t.Fatal("changed cropping reused an encoded artifact") + } +} diff --git a/internal/media/probe.go b/internal/media/probe.go index b0865ae..3336a30 100644 --- a/internal/media/probe.go +++ b/internal/media/probe.go @@ -23,7 +23,10 @@ func init() { extensions[s] = true } } -func IsVideo(path string) bool { return extensions[strings.ToLower(filepath.Ext(path))] } +func IsVideo(path string) bool { + // macOS AppleDouble files carry resource metadata, never video data. + return !strings.HasPrefix(filepath.Base(path), "._") && extensions[strings.ToLower(filepath.Ext(path))] +} type stream struct { Index int `json:"index"` diff --git a/internal/model/model.go b/internal/model/model.go index 7b5a526..5c2c58d 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -30,18 +30,27 @@ type Settings struct { TitlesPerPage int `json:"titles_per_page"` StageLocally bool `json:"stage_locally"` Encoders int `json:"encoders"` + VideoEncoder string `json:"video_encoder,omitempty"` + HCencDir string `json:"hcenc_dir,omitempty"` OutputDir string `json:"output_dir"` WorkDir string `json:"work_dir"` Theme string `json:"theme"` KeepWork bool `json:"keep_work"` + NoMenu bool `json:"no_menu,omitempty"` Menu MenuStyle `json:"menu"` } func DefaultSettings(base string) Settings { - return Settings{Standard: "PAL", Media: "DVD-5", Packing: "Strict order", Layout: "Text", TitlesPerPage: 10, StageLocally: true, Encoders: 2, OutputDir: filepath.Join(base, "easyDVD Output"), WorkDir: filepath.Join(base, "easyDVD Work"), Theme: "System", Menu: DefaultMenuStyle()} + return Settings{Standard: "PAL", Media: "DVD-5", Packing: "Strict order", Layout: "Text", TitlesPerPage: 10, StageLocally: true, Encoders: 2, VideoEncoder: "HCenc", OutputDir: filepath.Join(base, "easyDVD Output"), WorkDir: filepath.Join(base, "easyDVD Work"), Theme: "System", Menu: DefaultMenuStyle()} } func (s Settings) Validate() error { + if s.Encoder() != "HCenc" && s.Encoder() != "FFmpeg" { + return fmt.Errorf("choose HCenc or FFmpeg as video encoder") + } + if s.HCencDir != "" && !filepath.IsAbs(s.HCencDir) { + return fmt.Errorf("HCenc folder must be an absolute path") + } if s.Standard != "PAL" && s.Standard != "NTSC" { return fmt.Errorf("choose PAL or NTSC") } @@ -101,7 +110,26 @@ func (s Settings) GOP() string { // Only settings affecting an encoded title belong here. Menu edits and packing do not re-encode. func (s Settings) EncodingKey() string { - return Hash("mpeg2-v2-8000-9000-ac3-256-2pass-" + s.Standard) + if s.VideoEncoder == "" { + return Hash("mpeg2-v2-8000-9000-ac3-256-2pass-" + s.Standard) + } + return Hash("mpeg2-v3-pillarbox-8000-9000-ac3-256-2pass-" + s.Encoder() + "-" + s.Standard) +} + +// Empty identifies queues saved before encoder selection existed. +func (s Settings) Encoder() string { + if s.VideoEncoder == "" { + return "FFmpeg" + } + return s.VideoEncoder +} + +func (v Video) ArtifactKey(s Settings) string { + key := s.EncodingKey() + v.Fingerprint() + if v.CropLeft+v.CropRight > 0 { + key += fmt.Sprintf(":crop:%d:%d", v.CropLeft, v.CropRight) + } + return key } type Video struct { @@ -115,6 +143,9 @@ type Video struct { Width int `json:"width"` Height int `json:"height"` DAR float64 `json:"dar"` + CropLeft int `json:"crop_left,omitempty"` + CropRight int `json:"crop_right,omitempty"` + CropChecked bool `json:"crop_checked,omitempty"` FPS float64 `json:"fps"` FieldOrder string `json:"field_order"` VideoStream int `json:"video_stream"` @@ -144,12 +175,19 @@ func (v Video) OriginalLabel() string { func (v Video) Fingerprint() string { return Hash(fmt.Sprintf("%s:%d:%d", v.Path, v.Size, v.ModTime)) } func (v Video) EstimatedBytes() int64 { return int64(v.Duration * 8256000 / 8 * 1.035) } func (v Video) Aspect() string { - if v.DAR >= 1.55 { + if v.ContentDAR() >= 1.55 { return "16:9" } return "4:3" } +func (v Video) ContentDAR() float64 { + if v.Width > 0 && v.CropLeft >= 0 && v.CropRight >= 0 && v.CropLeft+v.CropRight < v.Width { + return v.DAR * float64(v.Width-v.CropLeft-v.CropRight) / float64(v.Width) + } + return v.DAR +} + type Disc struct { Number int `json:"number"` VideoIDs []string `json:"video_ids"` @@ -162,6 +200,7 @@ type Disc struct { type Job struct { ID string `json:"id"` Folder string `json:"folder"` + Sources []string `json:"sources,omitempty"` Title string `json:"title"` State State `json:"state"` Stage string `json:"stage"` @@ -201,6 +240,7 @@ func (j Job) Duration() float64 { } func (j Job) Clone() Job { c := j + c.Sources = append([]string(nil), j.Sources...) c.Videos = append([]Video(nil), j.Videos...) c.Discs = append([]Disc(nil), j.Discs...) for i := range c.Discs { diff --git a/internal/store/store.go b/internal/store/store.go index acda4fe..ec979e9 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -101,7 +101,8 @@ func (s *Store) Settings(fallback model.Settings) (model.Settings, error) { if err != nil { return fallback, err } - var v model.Settings + // New pending jobs adopt current defaults; saved started jobs retain theirs. + v := fallback err = json.Unmarshal(b, &v) return v, err } diff --git a/internal/ui/drop.go b/internal/ui/drop.go new file mode 100644 index 0000000..18a3771 --- /dev/null +++ b/internal/ui/drop.go @@ -0,0 +1,64 @@ +package ui + +import ( + "context" + "easydvd/internal/fsops" + "easydvd/internal/media" + "fmt" + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/container" + "fyne.io/fyne/v2/dialog" + "fyne.io/fyne/v2/widget" +) + +// Classify off the UI thread: stat may need to contact a network share. +func (u *window) addDroppedPaths(paths []string) { + u.action(func() error { + var files []string + for _, path := range paths { + info, err := fsops.Stat(context.Background(), path) + if err != nil { + return err + } + if !info.Exists { + return fmt.Errorf("source does not exist: %s", path) + } + if info.Directory { + if err = u.engine.Add(path); err != nil { + return err + } + } else if media.IsVideo(path) { + files = append(files, path) + } + } + if len(files) == 1 { + return u.engine.AddFiles(files) + } + if len(files) > 1 { + fyne.Do(func() { u.chooseFileGrouping(files) }) + } + return nil + }) +} + +func (u *window) chooseFileGrouping(files []string) { + choice := widget.NewRadioGroup([]string{"All files in one DVD set", "A separate DVD set for each file"}, nil) + choice.SetSelected(choice.Options[0]) + dialog.NewCustomConfirm("Add video files", "Add files", "Cancel", container.NewVBox(widget.NewLabel(fmt.Sprintf("How should these %d videos be queued?", len(files))), choice), func(ok bool) { + if !ok { + return + } + together := choice.Selected == choice.Options[0] + u.action(func() error { + if together { + return u.engine.AddFiles(files) + } + for _, path := range files { + if err := u.engine.AddFiles([]string{path}); err != nil { + return err + } + } + return nil + }) + }, u.win).Show() +} diff --git a/internal/ui/drop_test.go b/internal/ui/drop_test.go new file mode 100644 index 0000000..548a294 --- /dev/null +++ b/internal/ui/drop_test.go @@ -0,0 +1,36 @@ +package ui + +import ( + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/test" + "fyne.io/fyne/v2/widget" + "testing" +) + +func TestMultipleFileDropOffersGroupingAndCanBeCanceled(t *testing.T) { + u := fileListFixture(t) + u.chooseFileGrouping([]string{"first.mp4", "second.mp4"}) + var choice *widget.RadioGroup + var cancel *widget.Button + walkFileTestObjects(u.win.Canvas().Overlays().Top(), func(object fyne.CanvasObject) { + switch w := object.(type) { + case *widget.RadioGroup: + choice = w + case *widget.Button: + if w.Text == "Cancel" { + cancel = w + } + } + }) + if choice == nil || len(choice.Options) != 2 || cancel == nil { + t.Fatal("file grouping choice was not shown") + } + if choice.Selected != "All files in one DVD set" { + t.Fatal(choice.Selected) + } + choice.SetSelected("A separate DVD set for each file") + test.Tap(cancel) + if len(u.engine.Snapshot().Jobs) != 1 { + t.Fatal("cancel queued new jobs") + } +} diff --git a/internal/ui/files.go b/internal/ui/files.go index 1162747..d704fac 100644 --- a/internal/ui/files.go +++ b/internal/ui/files.go @@ -65,6 +65,37 @@ func (u *window) buildFileList() fyne.CanvasObject { } func (u *window) setFileSelected(id string, selected bool) { + shift := false + if driver, ok := u.app.Driver().(desktop.Driver); ok { + shift = driver.CurrentKeyModifiers()&fyne.KeyModifierShift != 0 + } + u.selectFileRange(id, selected, shift) +} + +func (u *window) selectFileRange(id string, selected, shift bool) { + if shift && u.selectionAnchor != "" { + if j := u.selectedJob(); j != nil { + anchor, target := -1, -1 + for i, v := range j.Videos { + if v.ID == u.selectionAnchor { + anchor = i + } + if v.ID == id { + target = i + } + } + if anchor >= 0 && target >= 0 { + for i := min(anchor, target); i <= max(anchor, target); i++ { + // Shift always selects the inclusive range, even if the endpoint was selected. + u.selectedFiles[j.Videos[i].ID] = true + } + u.refreshFileSelection() + u.files.Refresh() + return + } + } + } + u.selectionAnchor = id if selected { u.selectedFiles[id] = true } else { @@ -82,6 +113,7 @@ func (u *window) refreshFileSelection() { } if u.selectionJob != jobID { u.selectionJob = jobID + u.selectionAnchor = "" clear(u.selectedFiles) u.files.UnselectAll() u.files.ScrollToTop() diff --git a/internal/ui/files_test.go b/internal/ui/files_test.go index ca191d4..07b1ec9 100644 --- a/internal/ui/files_test.go +++ b/internal/ui/files_test.go @@ -171,6 +171,33 @@ func TestFileSelectionBulkAndPerRowActions(t *testing.T) { } } +func TestShiftSelectionUsesInclusiveAnchorAcrossRecycledRows(t *testing.T) { + u := fileListFixture(t) + u.selectFileRange("4", true, false) + u.selectFileRange("16", true, true) + if len(u.selectedFiles) != 13 { + t.Fatal(u.selectedFiles) + } + u.selectFileRange("1", true, true) + if len(u.selectedFiles) != 16 || u.selectionAnchor != "4" { + t.Fatal("reverse range moved the anchor", u.selectedFiles) + } + u.selectFileRange("10", false, false) + if u.selectedFiles["10"] || u.selectionAnchor != "10" { + t.Fatal("plain click did not reset anchor") + } + u.selectFileRange("12", false, true) + if !u.selectedFiles["10"] || !u.selectedFiles["11"] || !u.selectedFiles["12"] { + t.Fatal("selected endpoint toggled range off") + } + u.snapshot.Jobs = append(u.snapshot.Jobs, model.Job{ID: "another", State: model.Ready}) + u.selected = "another" + u.refreshFileSelection() + if u.selectionAnchor != "" || len(u.selectedFiles) != 0 { + t.Fatal("anchor leaked to another job") + } +} + func TestFileTitleDialogAndReadOnlyStates(t *testing.T) { u := fileListFixture(t) r := newFileRow(u) diff --git a/internal/ui/playback_test.go b/internal/ui/playback_test.go new file mode 100644 index 0000000..c232cd1 --- /dev/null +++ b/internal/ui/playback_test.go @@ -0,0 +1,66 @@ +package ui + +import ( + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/test" + "fyne.io/fyne/v2/widget" + "strings" + "testing" + "time" +) + +func TestNoMenuOnlySelectableForSingleVideoJob(t *testing.T) { + u := fileListFixture(t) + j := u.selectedJob() + u.settingsDialog(j.ID, j.Settings) + var noMenu *widget.Check + var cancel *widget.Button + find := func(object fyne.CanvasObject) { + switch w := object.(type) { + case *widget.Check: + if strings.HasPrefix(w.Text, "No menu") { + noMenu = w + } + case *widget.Button: + if w.Text == "Cancel" { + cancel = w + } + } + } + walkFileTestObjects(u.win.Canvas().Overlays().Top(), find) + if noMenu == nil || !noMenu.Disabled() { + t.Fatal("multiple-video job offered no-menu playback") + } + test.Tap(cancel) + var ids []string + for _, v := range j.Videos[1:] { + ids = append(ids, v.ID) + } + if err := u.engine.SetExcluded(j.ID, ids, true); err != nil { + t.Fatal(err) + } + u.snapshot = u.engine.Snapshot() + u.refresh() + j = u.selectedJob() + u.settingsDialog(j.ID, j.Settings) + var save *widget.Button + walkFileTestObjects(u.win.Canvas().Overlays().Top(), func(object fyne.CanvasObject) { + find(object) + if w, ok := object.(*widget.Button); ok && w.Text == "Save settings" { + save = w + } + }) + if noMenu == nil || noMenu.Disabled() || save == nil { + t.Fatal("single-video playback option unavailable") + } + noMenu.SetChecked(true) + test.Tap(save) + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if u.engine.Snapshot().Jobs[0].Settings.NoMenu { + return + } + time.Sleep(5 * time.Millisecond) + } + t.Fatal("no-menu choice was not saved") +} diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 4f79079..f80f82b 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -61,6 +61,7 @@ type window struct { snapshot engine.Snapshot selected string selectionJob string + selectionAnchor string selectedFiles map[string]bool fileHints *fyne.Container selectAll *widget.Check @@ -121,6 +122,7 @@ func Run() error { if !u.ensureMedia() { return } + var paths []string for _, uri := range uris { if uri.Scheme() != "file" { continue @@ -130,8 +132,9 @@ func Run() error { p = p[1:] } p = filepath.FromSlash(p) - u.action(func() error { return e.Add(p) }) + paths = append(paths, p) } + u.addDroppedPaths(paths) }) w.SetCloseIntercept(func() { s := u.snapshot @@ -253,8 +256,8 @@ func (u *window) build() fyne.CanvasObject { u.clear = widget.NewButtonWithIcon("Clear queue", theme.DeleteIcon(), u.clearQueue) queueHeading := container.NewBorder(nil, nil, nil, u.clear, widget.NewLabelWithStyle("Queue", fyne.TextAlignLeading, fyne.TextStyle{Bold: true})) queue := container.NewBorder(container.NewVBox(queueHeading, widget.NewSeparator()), container.NewHBox(u.up, u.down, layout.NewSpacer(), u.remove), nil, nil, u.queue) - dropLabel := widget.NewLabelWithStyle("Drop folders here", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}) - sub := widget.NewLabelWithStyle("One folder → one DVD set · Subfolders included", fyne.TextAlignCenter, fyne.TextStyle{}) + dropLabel := widget.NewLabelWithStyle("Drop folders or video files here", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}) + sub := widget.NewLabelWithStyle("Folders include subfolders · Group files into DVD sets", fyne.TextAlignCenter, fyne.TextStyle{}) border := canvas.NewRectangle(color.Transparent) border.StrokeColor = theme.DisabledColor() border.StrokeWidth = 1 @@ -271,7 +274,7 @@ func (u *window) build() fyne.CanvasObject { largeBorder.StrokeColor = theme.DisabledColor() largeBorder.StrokeWidth = 1 largeBorder.CornerRadius = 5 - largeDrop := container.NewStack(largeBorder, container.NewPadded(container.NewVBox(layout.NewSpacer(), widget.NewLabelWithStyle("Drop folders here", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}), widget.NewLabelWithStyle("One folder → one DVD set · Subfolders included", fyne.TextAlignCenter, fyne.TextStyle{}), container.NewCenter(widget.NewButtonWithIcon("Add folders", theme.FolderOpenIcon(), u.addFolders)), layout.NewSpacer()))) + largeDrop := container.NewStack(largeBorder, container.NewPadded(container.NewVBox(layout.NewSpacer(), widget.NewLabelWithStyle("Drop folders or video files here", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}), widget.NewLabelWithStyle("Folders include subfolders · Group files into DVD sets", fyne.TextAlignCenter, fyne.TextStyle{}), container.NewCenter(widget.NewButtonWithIcon("Add folders", theme.FolderOpenIcon(), u.addFolders)), layout.NewSpacer()))) u.empty = container.NewCenter(container.NewGridWrap(fyne.NewSize(510, 230), largeDrop)) u.dropBar = container.NewVBox(drop, widget.NewSeparator()) right := container.NewBorder(u.dropBar, nil, nil, nil, container.NewStack(u.empty, u.details)) @@ -351,7 +354,7 @@ func (u *window) refresh() { u.details.Show() u.dropBar.Show() enabled(u.settings, !j.Locked && !u.snapshot.Clearing) - enabled(u.preview, len(j.ActiveVideos()) > 0 && j.ScanComplete) + enabled(u.preview, len(j.ActiveVideos()) > 0 && j.ScanComplete && !j.Settings.NoMenu) enabled(u.cancel, j.State != model.Complete && j.State != model.Canceled) enabled(u.retry, u.mediaReady && !u.snapshot.Clearing && !u.snapshot.Busy[j.ID] && (j.State == model.Blocked || j.State == model.Paused || j.State == model.Canceled)) } @@ -416,8 +419,18 @@ func (u *window) settingsDialog(id string, s model.Settings) { stage.SetChecked(s.StageLocally) keep := widget.NewCheck("Keep intermediate media after success", nil) keep.SetChecked(s.KeepWork) + noMenu := widget.NewCheck("No menu — start playback automatically (one included video)", nil) + noMenu.SetChecked(s.NoMenu) + if !s.NoMenu && (id == "" || u.selectedJob() == nil || len(u.selectedJob().ActiveVideos()) != 1) { + noMenu.Disable() + } workers := widget.NewSelect([]string{"1", "2"}, nil) workers.SetSelected(strconv.Itoa(s.Encoders)) + encoder := widget.NewSelect([]string{"HCenc", "FFmpeg"}, nil) + encoder.SetSelected(s.Encoder()) + hcencFolder := widget.NewEntry() + hcencFolder.SetText(s.HCencDir) + hcencFolder.SetPlaceHolder("Choose the HCenc installation folder, or leave blank for automatic detection") output := widget.NewEntry() output.SetText(s.OutputDir) work := widget.NewEntry() @@ -437,6 +450,9 @@ func (u *window) settingsDialog(id string, s model.Settings) { appearance := widget.NewSelect([]string{"System", "Light", "Dark"}, nil) appearance.SetSelected(s.Theme) form := widget.NewForm(widget.NewFormItem("TV standard", standard), widget.NewFormItem("Disc capacity", medium), widget.NewFormItem("File allocation", packingMode), widget.NewFormItem("Menu layout", menuLayout), widget.NewFormItem("Titles per page", perPage), widget.NewFormItem("Encoding workers", workers), widget.NewFormItem("Output folder", folder(output)), widget.NewFormItem("Local work folder", folder(work)), widget.NewFormItem("Appearance", appearance)) + form.Append("Playback", noMenu) + form.Append("Video encoder", encoder) + form.Append("HCenc folder", folder(hcencFolder)) note := "Applies to new and pending jobs. Started jobs retain their settings." if id != "" { note = "Settings for this folder. Locked when processing starts." @@ -457,8 +473,11 @@ func (u *window) settingsDialog(id string, s model.Settings) { next.Layout = menuLayout.Selected next.TitlesPerPage = n next.Encoders, _ = strconv.Atoi(workers.Selected) + next.VideoEncoder = encoder.Selected + next.HCencDir = strings.TrimSpace(hcencFolder.Text) next.StageLocally = stage.Checked next.KeepWork = keep.Checked + next.NoMenu = noMenu.Checked next.OutputDir = strings.TrimSpace(output.Text) next.WorkDir = strings.TrimSpace(work.Text) next.Theme = appearance.Selected @@ -512,7 +531,9 @@ func (u *window) diagnostics() { u.action(func() error { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - statuses := u.engine.Tools().Check(ctx) + tools := u.engine.Tools() + statuses := tools.Check(ctx) + statuses = append(statuses, tools.EncoderStatus(u.engine.Snapshot().Settings)) var text strings.Builder for _, s := range statuses { fmt.Fprintf(&text, "%s\n%s\n%s\n", s.Name, s.Path, s.Version) diff --git a/scripts/package.ps1 b/scripts/package.ps1 index bc8d182..024e609 100644 --- a/scripts/package.ps1 +++ b/scripts/package.ps1 @@ -36,6 +36,8 @@ foreach ($file in $documentation) { Copy-Item -LiteralPath (Join-Path $ProjectRoot $file) -Destination $target } Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'tools.lock.json') -Destination $bundle +New-Item -ItemType Directory -Force -Path (Join-Path $bundle 'scripts') | Out-Null +Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'prepare-hcenc.ps1') -Destination (Join-Path $bundle 'scripts') $Version | Set-Content -LiteralPath (Join-Path $bundle 'VERSION') -Encoding utf8 @{version=$Version; repository=(Get-Content -LiteralPath (Join-Path $ProjectRoot 'RELEASE_REPOSITORY') -Raw).Trim(); publicRelease=[bool]$PublicRelease; offline=[bool]$IncludeFFmpeg; authoringToolchain=$ToolLock.authoring.id; commit=(& git -C $ProjectRoot rev-parse --verify HEAD 2>$null)} | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $bundle 'release.json') -Encoding utf8 Use-DevTools diff --git a/scripts/prepare-hcenc.ps1 b/scripts/prepare-hcenc.ps1 new file mode 100644 index 0000000..403d83b --- /dev/null +++ b/scripts/prepare-hcenc.ps1 @@ -0,0 +1,44 @@ +param([string]$OutputDir, [string]$CacheDir, [string]$SevenZip) +$ErrorActionPreference = 'Stop' +$setupRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +if (-not $OutputDir) { + $OutputDir = if (Test-Path -LiteralPath (Join-Path $setupRoot 'go.mod')) { Join-Path $setupRoot '.tools/hcenc/bin' } else { Join-Path $setupRoot 'tools/hcenc' } +} +if (-not $CacheDir) { $CacheDir = Join-Path ([IO.Path]::GetTempPath()) 'easyDVD-hcenc-setup' } +$OutputDir = [IO.Path]::GetFullPath($OutputDir) +$CacheDir = [IO.Path]::GetFullPath($CacheDir) +if (-not $SevenZip) { + $found = Get-Command 7z.exe -ErrorAction SilentlyContinue + if ($found) { $SevenZip = $found.Source } + elseif (Test-Path -LiteralPath 'C:/Program Files/7-Zip/7z.exe') { $SevenZip = 'C:/Program Files/7-Zip/7z.exe' } + else { throw 'Install 7-Zip or pass -SevenZip with the path to 7z.exe.' } +} +New-Item -ItemType Directory -Force -Path $CacheDir,$OutputDir | Out-Null +$packages = @( + @{name='hcenc'; url='http://hank315.nl/files/HC_028/HC028_21-12-2015.zip'; sha256='ed392df990120cd5430454bec68555dd444f1193f930e021c42b1871f5e245a7'}, + @{name='avisynth'; url='https://github.com/AviSynth/AviSynthPlus/releases/download/v3.7.5/AviSynthPlus_3.7.5_20250420-filesonly.7z'; sha256='4db18a1b3787b46ed99e810fa41cdc238f7f6ac82ffa6ed84d53fa8cefb5146f'}, + @{name='ffms2'; url='https://github.com/FFMS/ffms2/releases/download/2.40/ffms2-2.40-msvc.7z'; sha256='0da7454faaab87fc1515d72ffc2edeaee0e6090fa2f27a8986bdebed06197457'} +) +foreach ($package in $packages) { + $archive = Join-Path $CacheDir ($package.name + [IO.Path]::GetExtension($package.url)) + if (-not (Test-Path -LiteralPath $archive) -or (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLowerInvariant() -ne $package.sha256) { + & curl.exe --fail --location --retry 2 --silent --show-error $package.url --output $archive + if ($LASTEXITCODE -ne 0) { throw "Download failed: $($package.name)" } + } + if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLowerInvariant() -ne $package.sha256) { throw "Checksum mismatch: $archive" } + & $SevenZip x $archive "-o$CacheDir/$($package.name)" -y | Out-Null + if ($LASTEXITCODE -ne 0) { throw "Extraction failed: $($package.name)" } +} +$files = @( + @{source='hcenc/HC028_21-12-2015/HCenc_028.exe'; target='HCenc_028.exe'}, + @{source='hcenc/HC028_21-12-2015/misc/HC028.pdf'; target='HC028.pdf'}, + @{source='avisynth/AviSynthPlus_3.7.5_20250420-filesonly/x86/AviSynth.dll'; target='AviSynth.dll'}, + @{source='avisynth/AviSynthPlus_3.7.5_20250420-filesonly/gpl.txt'; target='AviSynth-GPL.txt'}, + @{source='avisynth/AviSynthPlus_3.7.5_20250420-filesonly/lgpl_for_used_libs.txt'; target='AviSynth-LGPL.txt'}, + @{source='ffms2/ffms2-2.40-msvc/x86/ffms2.dll'; target='ffms2.dll'}, + @{source='ffms2/ffms2-2.40-msvc/COPYING'; target='FFMS2-COPYING.txt'} +) +foreach ($file in $files) { Copy-Item -LiteralPath (Join-Path $CacheDir $file.source) -Destination (Join-Path $OutputDir $file.target) -Force } +$packages | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $OutputDir 'downloads.json') -Encoding UTF8 +Write-Host "HCenc runtime ready: $OutputDir" +Write-Host 'Choose this folder in Settings / HCenc folder, or pass -hcenc-dir to the CLI.' diff --git a/validation/GITHUB-ISSUES-2026-10-29.md b/validation/GITHUB-ISSUES-2026-10-29.md new file mode 100644 index 0000000..43ceab5 --- /dev/null +++ b/validation/GITHUB-ISSUES-2026-10-29.md @@ -0,0 +1,68 @@ +# GitHub issue validation — 2026-10-29 + +Addresses issues [#1](https://github.com/maghofer/easyDVD/issues/1), +[#2](https://github.com/maghofer/easyDVD/issues/2), +[#3](https://github.com/maghofer/easyDVD/issues/3), +[#5](https://github.com/maghofer/easyDVD/issues/5), +[#6](https://github.com/maghofer/easyDVD/issues/6), and +[#7](https://github.com/maghofer/easyDVD/issues/7). + +## Behavior + +- Scans ignore AppleDouble `._` sidecars and `__MACOSX` metadata directories. + Excluding a failed file returns an otherwise valid, fully scanned job to Ready; + including it again blocks the job. Genuine hidden videos remain eligible. +- Shift selects the inclusive range from the last ordinary selection, including + rows outside the visible list. Switching jobs clears the selection anchor. +- Single file drops create one job. Multiple file drops offer a combined set or + separate sets. Exact file selections persist through rescans/restarts, including + equal basenames in different directories; unselected siblings stay out. +- Single-title jobs offer No menu in Job settings. DVD first play jumps directly + to title 1 and playback stops at the end; no menu media/images are generated. + Invalid multi-title requests are rejected before settings are locked. +- New jobs default to HCenc BEST, two-pass VBR, 8/9 Mbps, DVD GOP/VBV settings. + FFmpeg normalizes lossless frames and handles AC-3/muxing. Logs must prove both + passes and the complete prepared frame count. Legacy started jobs retain their + FFmpeg profile and compatible checkpoints. Setup is described in + [Encoder setup](../docs/ENCODERS.md). +- Automatic 16:9-to-4:3 conversion checks every frame's pixel bounding box before + accepting symmetric black side borders. Analysis keeps 16-bit precision and + allows two nominal 8-bit luma levels above black for compression residue. + Wider picture content or a tiny visible border mark vetoes cropping. Actual + content aspect controls scaling; rounding differences are padded. + +## Completed checks + +- All-package unit tests and `go vet` passed on Windows. +- Race tests passed for media, engine, store and subprocess packages. +- Linux compilation with the headless `ci` tag passed. +- Actual FFmpeg and HCenc PAL/NTSC pipelines passed, including title/audio + properties, menu navigation generation, pause/restart encode reuse, publication + recovery, isolated file selection/rescans, Unicode source/work paths and + menu-free ISO output. Tests also author 36-title and 99-title discs. +- A final-frame transition to genuine widescreen and a 2×2 visible mark in a + border both prevented cropping. Unit tests cover split diagnostic writes. +- libVLC 3.0.24 confirmed automatic first play and normal end-of-playback for the + synthetic two-second disc and a real 6.875-second source. The check explicitly + selects software decoding to avoid a local GPU-driver teardown crash. +- The pinned HCenc/AviSynth+/FFMS2 setup helper passed from both repository and + simulated extracted-package locations. x86 PE checks reject mixed bitness. +- GUI selection/grouping/playback tests passed. Light and dark file-list + renderings were generated; the light rendering was visually inspected. +- Windows GUI/CLI/benchmark builds, whitespace checks and source audit passed. + +## Real media + +A 291.0625-second, 1280×720 ProRes source at 16 fps with PCM audio was processed +independently as a single-file PAL, menu-free HCenc job. All 4,657 source frames +were checked; 160 pixels per side were removed. HCenc completed both passes for +all 7,277 normalized frames. The authored title is MPEG-2 720×576, 25 fps, **4:3**, +with stereo AC-3 at 48 kHz. DVD-demuxed duration is 291.080 seconds (difference +0.0175 seconds), and full DVD-title decoding completed without errors. The ISO +is 303,040,512 bytes. The shorter real DNxHD source also completed HCenc authoring +and autoplay validation. + +All queues, runtime downloads, test media, builds and ISO files used isolated +scratch locations. The user's GUI queue was not opened or changed, and share +fixtures were read only. Physical-player compatibility and comparative encoder +quality remain outside these checks. From fade89da04572903f893eb9665cf8a7146b65b14 Mon Sep 17 00:00:00 2001 From: maghofer <327971135+maghofer@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:26:13 +0100 Subject: [PATCH 2/7] Measure encoder performance and preserve near-4:3 edge variations --- .github/workflows/ci.yml | 2 + cmd/easydvd-benchmark/main.go | 270 ++++++++------ docs/ENCODERS.md | 18 +- internal/app/cli.go | 2 +- internal/engine/engine.go | 3 +- internal/integration/issues_test.go | 62 ++++ internal/media/author.go | 20 +- internal/media/hcenc.go | 8 +- internal/media/pillarbox.go | 37 +- internal/media/pillarbox_test.go | 20 ++ internal/model/model.go | 14 +- internal/model/model_test.go | 16 + internal/platform/legacy_other.go | 7 + internal/platform/legacy_windows.go | 143 ++++++++ internal/platform/legacy_windows_test.go | 38 ++ internal/process/process.go | 23 ++ internal/process/process_test.go | 24 ++ internal/ui/ui.go | 17 +- .../ENCODER-PERFORMANCE-2026-10-29.json | 328 ++++++++++++++++++ validation/ENCODER-PERFORMANCE-2026-10-29.md | 95 +++++ validation/GITHUB-ISSUES-2026-10-29.md | 4 + 21 files changed, 1027 insertions(+), 124 deletions(-) create mode 100644 internal/platform/legacy_other.go create mode 100644 internal/platform/legacy_windows.go create mode 100644 internal/platform/legacy_windows_test.go create mode 100644 validation/ENCODER-PERFORMANCE-2026-10-29.json create mode 100644 validation/ENCODER-PERFORMANCE-2026-10-29.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e9106dd..a8a1a5c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,6 +17,8 @@ jobs: run: ./scripts/audit-source.ps1 windows: runs-on: windows-latest + env: + EASYDVD_HCENC: ${{ github.workspace }}/.tools/hcenc/bin steps: - uses: actions/checkout@v4 - uses: actions/cache@v4 diff --git a/cmd/easydvd-benchmark/main.go b/cmd/easydvd-benchmark/main.go index 496599f..ed16952 100644 --- a/cmd/easydvd-benchmark/main.go +++ b/cmd/easydvd-benchmark/main.go @@ -12,6 +12,7 @@ import ( "os/signal" "path/filepath" "regexp" + "runtime" "strconv" "strings" "time" @@ -23,16 +24,27 @@ import ( ) type Result struct { - Encoder string - Status string - Seconds float64 - Bytes int64 - PSNR string - SSIM string - DVDISO string - Error string + Run int + Encoder string + Status string + Seconds float64 + CPUSeconds float64 + CPUPercent float64 + EncodingSeconds float64 + EncodingCPUPercent float64 + EncodingFPS float64 + Steps []process.Metrics + Bytes int64 + PSNR string + SSIM string + DVDISO string + Error string } type Report struct { + InputMode string + LogicalCPUs int + Repeats int + Preparation []process.Metrics Source string SourceSHA256 string Reference string @@ -62,10 +74,16 @@ func run() error { output := flag.String("output", "", "New directory for references, encoded samples, ISOs and report") standard := flag.String("standard", "PAL", "PAL or NTSC") seconds := flag.Float64("seconds", 10, "Maximum sample duration") + offset := flag.Float64("offset", 0, "Start time in seconds for the sample") + repeats := flag.Int("repeats", 1, "Repeated runs, alternating encoder order") + sourcePipeline := flag.Bool("source-pipeline", false, "Include source decoding/scaling; input must be a complete sample within -seconds, with -offset 0") mpeg := flag.String("mpeg2enc", "", "Optional mpeg2enc executable") hc := flag.String("hcenc", "", "Optional HCenc executable") ffms := flag.String("ffms2", "", "FFMS2 AviSynth plugin DLL, required for HCenc") flag.Parse() + if *offset < 0 || *repeats < 1 { + return fmt.Errorf("offset must be nonnegative and repeats positive") + } if *input == "" || *output == "" { return fmt.Errorf("use -input VIDEO -output NEW_DIRECTORY [-mpeg2enc EXE] [-hcenc EXE -ffms2 DLL]") } @@ -91,6 +109,12 @@ func run() error { s.WorkDir = filepath.Join(dir, "work") s.OutputDir = filepath.Join(dir, "output") s.Encoders = 1 + if *hc != "" { + s.HCencDir, _ = filepath.Abs(filepath.Dir(*hc)) + } + if *ffms != "" && *hc != "" && !strings.EqualFold(filepath.Clean(filepath.Dir(*ffms)), s.HCencDir) { + return fmt.Errorf("use a complete private HCenc runtime with ffms2.dll beside HCenc_028.exe") + } if err = s.Validate(); err != nil { return err } @@ -109,7 +133,19 @@ func run() error { if err != nil { return err } - duration := min(original.Duration, *seconds) + var preparation []process.Metrics + prepCtx := process.Observe(ctx, func(m process.Metrics) { preparation = append(preparation, m) }) + original, err = tools.DetectPillarbox(prepCtx, original, source, log) + if err != nil { + return err + } + duration := min(original.Duration-*offset, *seconds) + if duration <= 0 { + return fmt.Errorf("offset is beyond source duration") + } + if *sourcePipeline && (*offset != 0 || duration < original.Duration) { + return fmt.Errorf("-source-pipeline needs a complete sample: use -offset 0 and -seconds at least the source duration") + } // Normalize once; encoder comparisons must not include different scaling or cadence conversions. interlaced := original.FieldOrder == "tt" || original.FieldOrder == "bb" || original.FieldOrder == "tb" || original.FieldOrder == "bt" normalized := original @@ -119,122 +155,143 @@ func run() error { filter = "bwdif=mode=send_frame:parity=auto:deint=all," + filter } reference := filepath.Join(dir, "reference.y4m") - if err = process.Run(ctx, tools.FFmpeg, []string{"-hide_banner", "-nostdin", "-y", "-i", source, "-map", fmt.Sprintf("0:%d", original.VideoStream), "-vf", filter, "-t", fmt.Sprintf("%.6f", duration), "-pix_fmt", "yuv420p", "-an", "-f", "yuv4mpegpipe", reference}, process.Options{Log: log}); err != nil { + if err = process.Run(prepCtx, tools.FFmpeg, []string{"-hide_banner", "-nostdin", "-y", "-ss", fmt.Sprintf("%.6f", *offset), "-i", source, "-map", fmt.Sprintf("0:%d", original.VideoStream), "-vf", filter, "-t", fmt.Sprintf("%.6f", duration), "-pix_fmt", "yuv420p", "-an", "-f", "yuv4mpegpipe", reference}, process.Options{Log: log}); err != nil { return err } - ref := model.Video{ID: "reference", Path: reference, Relative: "reference.y4m", Label: "Encoder sample", Width: 720, Height: s.Height(), DAR: 4.0 / 3, FPS: media.Ratio(s.FPS()), Duration: duration, AudioStream: -1, FieldOrder: "progressive"} + ref := model.Video{ID: "reference", Path: reference, Relative: "reference.y4m", Label: "Encoder sample", Width: 720, Height: s.Height(), DAR: 4.0 / 3, FPS: media.Ratio(s.FPS()), Duration: duration, AudioStream: -1, FieldOrder: "progressive", CropChecked: true, CropVersion: media.PillarboxVersion} if original.Aspect() == "16:9" { ref.DAR = 16.0 / 9 } report := Report{Source: source, Reference: reference, Standard: s.Standard, Duration: duration, Tools: tools.Check(ctx), Notes: []string{"Prepared frames are identical for all encoder inputs; audio and menu size are excluded from video-size comparisons.", "FFmpeg and HCenc target 8 Mbps average / 9 Mbps peak. mpeg2enc uses quality 2 with an 8 Mbps cap; compare measured sizes as well as quality.", "SSIM and PSNR are supporting measurements. Review grain, fine detail, motion, banding and cadence visually before choosing an encoder.", "A generated ISO confirms basic authoring interoperability; physical-player validation and full DVD/VBV conformance remain separate checks.", "HCenc requires a matching AviSynth installation and FFMS2 plugin. Optional encoders are not redistributed by easyDVD."}} + report.LogicalCPUs, report.Repeats, report.Preparation = runtime.NumCPU(), *repeats, preparation + report.InputMode = "DVD-resolution prepared reference" + if *sourcePipeline { + report.InputMode = "Original-resolution source decoding and scaling" + } + report.Notes = append(report.Notes, "Seconds includes the production encode path (HCenc lossless preparation, audio/mux, full decode validation and checkpoint hashing). EncodingSeconds isolates the two MPEG-2 passes. CPU percentages use process CPU seconds divided by wall seconds and all logical CPUs. Preparation is recorded separately. Encoder order alternates between repeats; no candidates run concurrently.") report.SourceSHA256, _ = media.HashFile(ctx, source) report.ReferenceSHA256, _ = media.HashFile(ctx, reference) - for _, name := range []string{"FFmpeg", "mpeg2enc", "HCenc"} { - result := Result{Encoder: name, Status: "not available"} - candidate := filepath.Join(dir, strings.ToLower(name)) - if err = os.MkdirAll(candidate, 0755); err != nil { - return err + for run := 1; run <= *repeats; run++ { + names := []string{"FFmpeg", "HCenc", "mpeg2enc"} + if run%2 == 0 { + names = []string{"HCenc", "FFmpeg", "mpeg2enc"} } - encoded := "" - start := time.Now() - switch name { - case "FFmpeg": - var v model.Video - v, err = tools.Encode(ctx, ref, s, reference, candidate, log, nil) - encoded = v.Encoded - case "mpeg2enc": - binary := *mpeg - if binary == "" { - binary, _ = exec.LookPath("mpeg2enc") + for _, name := range names { + result := Result{Run: run, Encoder: name, Status: "not available"} + measured := process.Observe(ctx, func(m process.Metrics) { result.Steps = append(result.Steps, m) }) + candidate := filepath.Join(dir, fmt.Sprintf("%02d-%s", run, strings.ToLower(name))) + if err = os.MkdirAll(candidate, 0755); err != nil { + return err } - if binary == "" { - report.Results = append(report.Results, result) - continue + encoded := "" + start := time.Now() + switch name { + case "FFmpeg", "HCenc": + settings := s + settings.VideoEncoder = name + if name == "HCenc" { + if e := tools.RequireEncoder(settings); e != nil { + result.Error = e.Error() + report.Results = append(report.Results, result) + continue + } + } + var v model.Video + video, input := ref, reference + if *sourcePipeline { + video, input = original, source + } + v, err = tools.Encode(measured, video, settings, input, candidate, log, nil) + encoded = v.Encoded + case "mpeg2enc": + binary := *mpeg + if binary == "" { + binary, _ = exec.LookPath("mpeg2enc") + } + if binary == "" { + report.Results = append(report.Results, result) + continue + } + binary, _ = filepath.Abs(binary) + encoded = filepath.Join(candidate, "video.m2v") + f, e := os.Open(reference) + if e != nil { + return e + } + norm := "p" + if s.Standard == "NTSC" { + norm = "n" + } + aspect := "2" + if ref.Aspect() == "16:9" { + aspect = "3" + } + err = process.Run(measured, binary, []string{"-f", "8", "-n", norm, "-a", aspect, "-b", "8000", "-q", "2", "-I", "0", "-o", encoded}, process.Options{Stdin: f, Log: log}) + f.Close() } - binary, _ = filepath.Abs(binary) - encoded = filepath.Join(candidate, "video.m2v") - f, e := os.Open(reference) - if e != nil { - return e + result.Seconds = time.Since(start).Seconds() + var encodingCPU float64 + for _, step := range result.Steps { + result.CPUSeconds += step.CPUSeconds + if strings.HasPrefix(strings.ToLower(filepath.Base(step.Executable)), "hcenc") || hasArg(step.Args, "-pass") { + result.EncodingSeconds += step.Seconds + encodingCPU += step.CPUSeconds + } } - norm := "p" - if s.Standard == "NTSC" { - norm = "n" + result.CPUPercent = result.CPUSeconds / result.Seconds / float64(runtime.NumCPU()) * 100 + if result.EncodingSeconds > 0 { + result.EncodingCPUPercent = encodingCPU / result.EncodingSeconds / float64(runtime.NumCPU()) * 100 + result.EncodingFPS = duration * media.Ratio(s.FPS()) / result.EncodingSeconds } - aspect := "2" - if ref.Aspect() == "16:9" { - aspect = "3" + if err != nil { + result.Status = "failed" + result.Error = err.Error() + report.Results = append(report.Results, result) + continue } - err = process.Run(ctx, binary, []string{"-f", "8", "-n", norm, "-a", aspect, "-b", "8000", "-q", "2", "-I", "0", "-o", encoded}, process.Options{Stdin: f, Log: log}) - f.Close() - case "HCenc": - if *hc == "" || *ffms == "" { - result.Error = "Supply -hcenc and -ffms2; install matching AviSynth separately" + result.Status = "encoded" + st, e := os.Stat(encoded) + if e != nil { + result.Status = "failed" + result.Error = e.Error() report.Results = append(report.Results, result) continue } - binary, _ := filepath.Abs(*hc) - plugin, _ := filepath.Abs(*ffms) - script := fmt.Sprintf("LoadPlugin(\"%s\")\nFFVideoSource(\"%s\", cache=false)\nConvertToYV12(interlaced=false)\n", plugin, reference) - if err = os.WriteFile(filepath.Join(candidate, "source.avs"), []byte(script), 0644); err != nil { - return err + result.Bytes = st.Size() + if name == "FFmpeg" || name == "HCenc" { + elementary := filepath.Join(candidate, "video.m2v") + err = process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-y", "-i", encoded, "-map", "0:v:0", "-c:v", "copy", "-an", "-f", "mpeg2video", elementary}, process.Options{Log: log}) + if err == nil { + st, _ = os.Stat(elementary) + result.Bytes = st.Size() + } } - ini := fmt.Sprintf("*INFILE %s\n*OUTFILE %s\n*BITRATE 8000\n*MAXBITRATE 9000\n*PROFILE BEST\n*ASPECT %s\n*PROGRESSIVE\n", filepath.Join(candidate, "source.avs"), filepath.Join(candidate, "video.m2v"), ref.Aspect()) - if err = os.WriteFile(filepath.Join(candidate, "HC.ini"), []byte(ini), 0644); err != nil { - return err + result.PSNR = metric(ctx, tools, reference, encoded, "psnr", log) + result.SSIM = metric(ctx, tools, reference, encoded, "ssim", log) + dvdVideo := encoded + if name != "FFmpeg" && name != "HCenc" { + dvdVideo = filepath.Join(candidate, "video.mpg") + err = process.Run(ctx, tools.FFmpeg, []string{"-hide_banner", "-nostdin", "-y", "-i", encoded, "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo", "-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "ac3", "-ac", "2", "-b:a", "256k", "-t", fmt.Sprintf("%.6f", duration), "-f", "dvd", "-muxrate", "10080k", "-packetsize", "2048", dvdVideo}, process.Options{Log: log}) } - encoded = filepath.Join(candidate, "video.m2v") - err = process.Run(ctx, binary, []string{"-ini", filepath.Join(candidate, "HC.ini")}, process.Options{Dir: candidate, Log: log}) - } - result.Seconds = time.Since(start).Seconds() - if err != nil { - result.Status = "failed" - result.Error = err.Error() - report.Results = append(report.Results, result) - continue - } - result.Status = "encoded" - st, e := os.Stat(encoded) - if e != nil { - result.Status = "failed" - result.Error = e.Error() - report.Results = append(report.Results, result) - continue - } - result.Bytes = st.Size() - if name == "FFmpeg" { - elementary := filepath.Join(candidate, "video.m2v") - err = process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-y", "-i", encoded, "-map", "0:v:0", "-c:v", "copy", "-an", "-f", "mpeg2video", elementary}, process.Options{Log: log}) if err == nil { - st, _ = os.Stat(elementary) - result.Bytes = st.Size() + v := ref + v.Encoded = dvdVideo + j := model.Job{Title: name + " sample", Settings: s, Videos: []model.Video{v}} + iso, e := tools.Author(ctx, j, model.Disc{Number: 1, VideoIDs: []string{v.ID}}, 1, filepath.Join(candidate, "dvd-check"), log, func(string) error { return nil }) + if e != nil { + err = e + } else { + result.DVDISO = iso + result.Status = "authored" + } } - } - result.PSNR = metric(ctx, tools, reference, encoded, "psnr", log) - result.SSIM = metric(ctx, tools, reference, encoded, "ssim", log) - dvdVideo := encoded - if name != "FFmpeg" { - dvdVideo = filepath.Join(candidate, "video.mpg") - err = process.Run(ctx, tools.FFmpeg, []string{"-hide_banner", "-nostdin", "-y", "-i", encoded, "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo", "-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "ac3", "-ac", "2", "-b:a", "256k", "-t", fmt.Sprintf("%.6f", duration), "-f", "dvd", "-muxrate", "10080k", "-packetsize", "2048", dvdVideo}, process.Options{Log: log}) - } - if err == nil { - v := ref - v.Encoded = dvdVideo - j := model.Job{Title: name + " sample", Settings: s, Videos: []model.Video{v}} - iso, e := tools.Author(ctx, j, model.Disc{Number: 1, VideoIDs: []string{v.ID}}, 1, filepath.Join(candidate, "dvd-check"), log, func(string) error { return nil }) - if e != nil { - err = e - } else { - result.DVDISO = iso - result.Status = "authored" + if err != nil { + result.Error = err.Error() + result.Status = "authoring failed" } + report.Results = append(report.Results, result) + fmt.Printf("Run %d %s: %s · %.2fs total · %.2fs MPEG-2 · %.1f%% CPU · %d bytes · SSIM %s · PSNR %s\n", run, name, result.Status, result.Seconds, result.EncodingSeconds, result.EncodingCPUPercent, result.Bytes, result.SSIM, result.PSNR) } - if err != nil { - result.Error = err.Error() - result.Status = "authoring failed" - } - report.Results = append(report.Results, result) - fmt.Printf("%s: %s · %.2fs · %d bytes · SSIM %s · PSNR %s\n", name, result.Status, result.Seconds, result.Bytes, result.SSIM, result.PSNR) } b, err := json.MarshalIndent(report, "", " ") if err != nil { @@ -246,6 +303,15 @@ func run() error { fmt.Println("Report:", filepath.Join(dir, "report.json")) return ctx.Err() } + +func hasArg(args []string, want string) bool { + for _, arg := range args { + if arg == want { + return true + } + } + return false +} func metric(ctx context.Context, t media.Tools, reference, encoded, name string, log io.Writer) string { var b strings.Builder filter := "[0:v]setpts=PTS-STARTPTS[r];[1:v]setpts=PTS-STARTPTS[d];[r][d]" + name diff --git a/docs/ENCODERS.md b/docs/ENCODERS.md index 0f79d46..8342370 100644 --- a/docs/ENCODERS.md +++ b/docs/ENCODERS.md @@ -41,7 +41,11 @@ boundaries, so the displayed percentage can remain steady during either pass. For 16:9 input, easyDVD checks every decoded frame before resizing. It removes only symmetric black side borders that leave the full centered 4:3 picture. -A single frame with picture content outside that area prevents cropping. +A frame with picture content beyond the accepted border area prevents cropping. +Small variations at the 4:3 boundary are accepted by expanding the kept image to +include every observed pixel. Crop coordinates are rounded outward for chroma +alignment; the extra pixels are fitted with padding rather than stretched. +Content beyond this narrow edge margin still prevents cropping. The check uses per-pixel luminance with a two-level tolerance above nominal 8-bit black for compression residue, retaining 16-bit analysis precision. Uncertain or noisier borders keep the original frame. Letterbox bars are retained. @@ -63,6 +67,18 @@ represented by fabricated results. ./bin/easydvd-benchmark.exe -input C:\Scans\sample.mov -output C:\Benchmarks\trial-02 -mpeg2enc C:\Tools\mpeg2enc.exe -hcenc C:\Tools\HCenc.exe -ffms2 C:\Tools\ffms2.dll ``` +Use `-repeats 3` for repeated runs with alternating encoder order and `-offset` +to select another scene. The report includes per-process wall/CPU time and +separates MPEG-2 passes from preparation/muxing/validation. For a complete short +source clip, `-source-pipeline -seconds 1000` includes its original decoding and +scaling costs. The normal benchmark uses the same DVD-resolution reference for +both encoders. CPU percentages are normalized to all logical processors. + +HCenc can process up to four titles concurrently under Encoding workers; +FFmpeg retains its two-worker limit. A single title uses one HCenc process, +whose CPU utilization depends on its own threading. The default remains two +workers. Raising HCenc process priority does not remove a thread-scaling limit. + The benchmark's optional `-hcenc` / `-ffms2` paths are independent of the app's encoder setting and require the same matching-bitness AviSynth runtime. The harness does not switch the app's encoder automatically. diff --git a/internal/app/cli.go b/internal/app/cli.go index d10cf9c..59dd106 100644 --- a/internal/app/cli.go +++ b/internal/app/cli.go @@ -73,7 +73,7 @@ func CLI(args []string) error { ffmpegDir := fs.String("ffmpeg-dir", "", "Use FFmpeg and FFprobe from this folder for this run") downloadFFmpeg := fs.Bool("download-ffmpeg", false, "Download and remember the recommended private FFmpeg installation") resume := fs.Bool("resume", false, "Resume saved queue") - workers := fs.Int("encoders", 2, "Parallel encoders (1–2)") + workers := fs.Int("encoders", 2, "Parallel encoders (1–4 HCenc, 1–2 FFmpeg)") encoder := fs.String("video-encoder", defaults.Encoder(), "Video encoder: HCenc or FFmpeg") hcencDir := fs.String("hcenc-dir", "", "HCenc folder with 32-bit AviSynth.dll and ffms2.dll") if err := fs.Parse(args); err != nil { diff --git a/internal/engine/engine.go b/internal/engine/engine.go index d9653a0..4091e04 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -294,6 +294,7 @@ func (e *Engine) scanLocked(id string) { v.Excluded = previous.Excluded if previous.Fingerprint() == v.Fingerprint() { v.CropLeft, v.CropRight, v.CropChecked = previous.CropLeft, previous.CropRight, previous.CropChecked + v.CropVersion = previous.CropVersion v.Encoded = previous.Encoded v.EncodedSize = previous.EncodedSize v.EncodedHash = previous.EncodedHash @@ -1194,7 +1195,7 @@ func (e *Engine) encode(ctx context.Context, j model.Job, videos []model.Video, release() continue } - if v.Encoded == "" && !v.CropChecked { + if v.Encoded == "" && (!v.CropChecked || v.CropVersion != media.PillarboxVersion) { e.update(j.ID, false, func(job *model.Job) { job.Stage = "Checking black borders · " + v.Label }) var err error v, err = e.tools.DetectPillarbox(ctx, v, task.input, log) diff --git a/internal/integration/issues_test.go b/internal/integration/issues_test.go index d1e040c..f9e3946 100644 --- a/internal/integration/issues_test.go +++ b/internal/integration/issues_test.go @@ -230,3 +230,65 @@ func TestTinyDetailInBorderPreventsCropping(t *testing.T) { t.Fatal("border detail was removed", v, err) } } + +func TestNearFourThreeBordersKeepAllContent(t *testing.T) { + tools, ctx := issueTools(t) + dir := t.TempDir() + path := filepath.Join(dir, "edge-variation.mkv") + // The picture is four pixels wider than exact 4:3. Keep those pixels and + // fit into a 4:3 DVD frame; never retain the original 160-pixel sidebars. + if err := process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=964x720:r=25,pad=1280:720:158:0", "-t", "1", "-c:v", "ffv1", path}, process.Options{}); err != nil { + t.Fatal(err) + } + v, err := tools.DetectPillarbox(ctx, model.Video{Width: 1280, Height: 720, DAR: 16.0 / 9, Duration: 1}, path, nil) + if err != nil || v.CropLeft != 158 || v.CropRight != 158 || v.Aspect() != "4:3" || v.CropVersion != media.PillarboxVersion { + t.Fatal(v, err) + } +} + +func TestHCencFourWorkers(t *testing.T) { + tools, ctx := issueTools(t) + dir := t.TempDir() + s := model.DefaultSettings(dir) + if tools.HCencFolder(s) == "" { + t.Skip("HCenc runtime unavailable") + } + s.Encoders = 4 + source := filepath.Join(dir, "sources") + if err := os.Mkdir(source, 0755); err != nil { + t.Fatal(err) + } + first := filepath.Join(source, "1.mp4") + if err := process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=320x240:r=25", "-t", "1", "-c:v", "libx264", first}, process.Options{}); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(first) + if err != nil { + t.Fatal(err) + } + for n := 2; n <= 4; n++ { + if err := os.WriteFile(filepath.Join(source, fmt.Sprintf("%d.mp4", n)), data, 0644); err != nil { + t.Fatal(err) + } + } + st, err := store.Open(filepath.Join(dir, "queue.db")) + if err != nil { + t.Fatal(err) + } + defer st.Close() + e, err := engine.New(st, s, tools) + if err != nil { + t.Fatal(err) + } + defer e.Close() + if err = e.Add(source); err != nil { + t.Fatal(err) + } + e.Start() + j := wait(t, e, func(s engine.Snapshot) bool { + return s.Jobs[0].State == model.Complete || s.Jobs[0].State == model.Blocked + }).Jobs[0] + if j.State != model.Complete || len(j.Videos) != 4 || len(j.Discs) != 1 { + t.Fatal(j.State, j.Error) + } +} diff --git a/internal/media/author.go b/internal/media/author.go index 446bf72..bbecf3e 100644 --- a/internal/media/author.go +++ b/internal/media/author.go @@ -10,6 +10,7 @@ import ( "easydvd/internal/menu" "easydvd/internal/model" + "easydvd/internal/platform" "easydvd/internal/process" ) @@ -92,6 +93,15 @@ func (t Tools) Author(ctx context.Context, j model.Job, disc model.Disc, total i if j.Settings.NoMenu && (len(j.ActiveVideos()) != 1 || len(videos) != 1) { return "", fmt.Errorf("no menu requires exactly one included video") } + var related []string + for _, video := range videos { + related = append(related, video.Encoded) + } + toolDir, cleanup, dirErr := platform.LegacyWorkingDir(dir, related...) + if dirErr != nil { + return "", dirErr + } + defer cleanup() var pages []menu.Page var err error if !j.Settings.NoMenu { @@ -111,7 +121,7 @@ func (t Tools) Author(ctx context.Context, j model.Job, disc model.Disc, total i final := fmt.Sprintf("page-%03d.mpg", p.Number) target := strings.ToLower(j.Settings.Standard) + "-dvd" args := []string{"-hide_banner", "-nostdin", "-y", "-loop", "1", "-i", filepath.Base(p.Background), "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo", "-target", target, "-aspect", j.Settings.Menu.Defaults().Aspect, "-b:v", "2000k", "-b:a", "256k", "-ac", "2", "-t", "1", base} - if err = process.Run(ctx, t.FFmpeg, args, process.Options{Dir: dir, Log: log}); err != nil { + if err = process.Run(ctx, t.FFmpeg, args, process.Options{Dir: toolDir, Log: log}); err != nil { return "", err } in, e := os.Open(filepath.Join(dir, base)) @@ -123,7 +133,7 @@ func (t Tools) Author(ctx context.Context, j model.Job, disc model.Disc, total i in.Close() return "", e } - err = process.Run(ctx, t.Spumux, []string{"-s", "0", filepath.Base(p.XML)}, process.Options{Dir: dir, Stdin: in, Stdout: out, Log: log, Env: []string{"VIDEO_FORMAT=" + strings.ToUpper(j.Settings.Standard)}}) + err = process.Run(ctx, t.Spumux, []string{"-s", "0", filepath.Base(p.XML)}, process.Options{Dir: toolDir, Stdin: in, Stdout: out, Log: log, Env: []string{"VIDEO_FORMAT=" + strings.ToUpper(j.Settings.Standard)}}) in.Close() ce := out.Close() if err != nil { @@ -146,7 +156,7 @@ func (t Tools) Author(ctx context.Context, j model.Job, disc model.Disc, total i in.Close() return "", err } - err = process.Run(ctx, t.Spumux, []string{"-s", "1", filepath.Base(p.LetterboxXML)}, process.Options{Dir: dir, Stdin: in, Stdout: out, Log: log, Env: []string{"VIDEO_FORMAT=" + strings.ToUpper(j.Settings.Standard)}}) + err = process.Run(ctx, t.Spumux, []string{"-s", "1", filepath.Base(p.LetterboxXML)}, process.Options{Dir: toolDir, Stdin: in, Stdout: out, Log: log, Env: []string{"VIDEO_FORMAT=" + strings.ToUpper(j.Settings.Standard)}}) in.Close() ce = out.Close() if err != nil { @@ -168,7 +178,7 @@ func (t Tools) Author(ctx context.Context, j model.Job, disc model.Disc, total i if err := stage("Authoring DVD"); err != nil { return "", err } - if err = process.Run(ctx, t.DVDAuthor, []string{"-x", "dvd.xml"}, process.Options{Dir: dir, Log: log, Env: []string{"VIDEO_FORMAT=" + j.Settings.Standard}}); err != nil { + if err = process.Run(ctx, t.DVDAuthor, []string{"-x", "dvd.xml"}, process.Options{Dir: toolDir, Log: log, Env: []string{"VIDEO_FORMAT=" + j.Settings.Standard}}); err != nil { return "", err } if err = os.MkdirAll(filepath.Join(dir, "dvd", "AUDIO_TS"), 0755); err != nil { @@ -181,7 +191,7 @@ func (t Tools) Author(ctx context.Context, j model.Job, disc model.Disc, total i return "", err } volume := fmt.Sprintf("EASYDVD_%03d", disc.Number) - if err = process.Run(ctx, t.Mkisofs, []string{"-dvd-video", "-udf", "-V", volume, "-o", "disc.iso", "dvd"}, process.Options{Dir: dir, Log: log}); err != nil { + if err = process.Run(ctx, t.Mkisofs, []string{"-dvd-video", "-udf", "-V", volume, "-o", "disc.iso", "dvd"}, process.Options{Dir: toolDir, Log: log}); err != nil { return "", err } path := filepath.Join(dir, "disc.iso") diff --git a/internal/media/hcenc.go b/internal/media/hcenc.go index be1810f..ba8ab65 100644 --- a/internal/media/hcenc.go +++ b/internal/media/hcenc.go @@ -4,6 +4,7 @@ import ( "context" "debug/pe" "easydvd/internal/model" + "easydvd/internal/platform" "easydvd/internal/process" "fmt" "io" @@ -156,7 +157,12 @@ func (t Tools) encodeHCenc(ctx context.Context, v model.Video, s model.Settings, if progress != nil { progress(.25) } - err = process.Run(ctx, filepath.Join(t.HCencFolder(s), "HCenc_028.exe"), []string{"-ini", "HC.ini"}, process.Options{Dir: dir, Log: log, Stdout: log}) + toolDir, cleanup, err := platform.LegacyWorkingDir(dir) + if err != nil { + return err + } + defer cleanup() + err = process.Run(ctx, filepath.Join(t.HCencFolder(s), "HCenc_028.exe"), []string{"-ini", "HC.ini"}, process.Options{Dir: toolDir, Log: log, Stdout: log}) // HCenc can return success after an input/configuration error. Require its // elementary stream as well as successful decode/metadata validation below. hcLog, _ := os.ReadFile(filepath.Join(dir, "hcenc.log")) diff --git a/internal/media/pillarbox.go b/internal/media/pillarbox.go index 623b747..0498205 100644 --- a/internal/media/pillarbox.go +++ b/internal/media/pillarbox.go @@ -15,13 +15,20 @@ import ( var cropPattern = regexp.MustCompile(`crop=(-?\d+):(-?\d+):(-?\d+):(-?\d+)`) +const PillarboxVersion = 2 + // pillarboxEvidence keeps the union of visible content over the entire video. // A single wider frame prevents cropping. Letterbox bars are never removed. type pillarboxEvidence struct { - width, height, border int - frames, visible int - safe bool - pending string + width, height, border int + tolerance, left, right int + frames, visible int + safe bool + pending string +} + +func (p *pillarboxEvidence) crops() (int, int) { + return min(p.border, p.left) / 2 * 2, min(p.border, p.width-p.right) / 2 * 2 } func (p *pillarboxEvidence) Write(data []byte) (int, error) { @@ -47,7 +54,12 @@ func (p *pillarboxEvidence) Write(data []byte) (int, error) { continue } p.visible++ - if x < p.border || x+w > p.width-p.border { + if p.visible == 1 { + p.left, p.right = x, x+w + } else { + p.left, p.right = min(p.left, x), max(p.right, x+w) + } + if x < p.border-p.tolerance || x+w > p.width-p.border+p.tolerance { p.safe = false } } @@ -55,9 +67,11 @@ func (p *pillarboxEvidence) Write(data []byte) (int, error) { } func (t Tools) DetectPillarbox(ctx context.Context, v model.Video, input string, log io.Writer) (model.Video, error) { - if v.CropChecked { + if v.CropChecked && v.CropVersion == PillarboxVersion { return v, nil } + v.CropLeft, v.CropRight = 0, 0 + v.CropVersion = PillarboxVersion // Narrow scope: only a 16:9 container containing a centered 4:3 image. if math.Abs(v.DAR-16.0/9) > .025 || v.Width <= 0 || v.Height <= 0 { v.CropChecked = true @@ -68,7 +82,7 @@ func (t Tools) DetectPillarbox(ctx context.Context, v model.Video, input string, v.CropChecked = true return v, nil } - evidence := &pillarboxEvidence{width: v.Width, height: v.Height, border: border, safe: true} + evidence := &pillarboxEvidence{width: v.Width, height: v.Height, border: border, tolerance: max(2, v.Width/200), safe: true} null := "/dev/null" if runtime.GOOS == "windows" { null = "NUL" @@ -86,10 +100,15 @@ func (t Tools) DetectPillarbox(ctx context.Context, v model.Video, input string, } v.CropChecked = true if evidence.safe && evidence.visible >= 3 { - v.CropLeft, v.CropRight = border, border + // Include the union of every frame's visible pixels, rounded outward + // for chroma alignment. A few pixels of codec residue at the 4:3 edge + // must expand the kept image instead of vetoing all border removal. + v.CropLeft, v.CropRight = evidence.crops() if log != nil { - fmt.Fprintf(log, "\nConfirmed 4:3 pillarbox: %s, cropped %d black pixels per side after checking %d frames\n", v.Relative, border, evidence.frames) + fmt.Fprintf(log, "\nConfirmed 4:3 pillarbox: %s, cropped %d left / %d right black pixels after checking %d frames; kept all content bounds [%d,%d)\n", v.Relative, v.CropLeft, v.CropRight, evidence.frames, evidence.left, evidence.right) } + } else if log != nil { + fmt.Fprintf(log, "\nRetained 16:9 source: %s; %d visible frames, content bounds [%d,%d), expected 4:3 bounds [%d,%d), edge tolerance %d pixels\n", v.Relative, evidence.visible, evidence.left, evidence.right, border, v.Width-border, evidence.tolerance) } return v, nil } diff --git a/internal/media/pillarbox_test.go b/internal/media/pillarbox_test.go index e7528a9..33af5fd 100644 --- a/internal/media/pillarbox_test.go +++ b/internal/media/pillarbox_test.go @@ -40,3 +40,23 @@ func TestPillarboxKeepsContentAspectAndCacheIdentity(t *testing.T) { t.Fatal("changed cropping reused an encoded artifact") } } + +func TestSmallEdgeVariationExpandsKeptImage(t *testing.T) { + p := &pillarboxEvidence{width: 1280, height: 720, border: 160, tolerance: 6, safe: true} + for _, crop := range []string{"960:720:160:0", "961:720:160:0", "962:720:159:0", "963:720:158:0", "963:720:159:0"} { + fmt.Fprintf(p, "crop=%s\n", crop) + } + left, right := p.crops() + if !p.safe || left != 158 || right != 158 { + t.Fatal("edge variation vetoed crop or removed visible pixels", p, left, right) + } + v := model.Video{Width: 1280, Height: 720, DAR: 16.0 / 9, CropLeft: left, CropRight: right} + f, _ := VideoFilter(v, model.DefaultSettings(t.TempDir())) + if v.Aspect() != "4:3" || !strings.Contains(f, "crop=964:720:158:0") || !strings.Contains(f, "pad=720:576") { + t.Fatal(f) + } + fmt.Fprintf(p, "crop=1280:720:0:0\n") + if p.safe { + t.Fatal("real widescreen content must still prevent cropping") + } +} diff --git a/internal/model/model.go b/internal/model/model.go index 5c2c58d..c179648 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -70,8 +70,8 @@ func (s Settings) Validate() error { if s.TitlesPerPage < 1 || s.TitlesPerPage > max { return fmt.Errorf("titles per page must be 1–%d for this layout", max) } - if s.Encoders < 1 || s.Encoders > 2 { - return fmt.Errorf("use one or two encoding workers") + if s.Encoders < 1 || s.Encoders > s.MaxEncoders() { + return fmt.Errorf("use 1–%d encoding workers with %s", s.MaxEncoders(), s.Encoder()) } if !filepath.IsAbs(s.OutputDir) || !filepath.IsAbs(s.WorkDir) { return fmt.Errorf("output and work folders must be absolute paths") @@ -113,7 +113,7 @@ func (s Settings) EncodingKey() string { if s.VideoEncoder == "" { return Hash("mpeg2-v2-8000-9000-ac3-256-2pass-" + s.Standard) } - return Hash("mpeg2-v3-pillarbox-8000-9000-ac3-256-2pass-" + s.Encoder() + "-" + s.Standard) + return Hash("mpeg2-v4-pillarbox-bounds-8000-9000-ac3-256-2pass-" + s.Encoder() + "-" + s.Standard) } // Empty identifies queues saved before encoder selection existed. @@ -124,6 +124,13 @@ func (s Settings) Encoder() string { return s.VideoEncoder } +func (s Settings) MaxEncoders() int { + if s.Encoder() == "HCenc" { + return 4 + } + return 2 +} + func (v Video) ArtifactKey(s Settings) string { key := s.EncodingKey() + v.Fingerprint() if v.CropLeft+v.CropRight > 0 { @@ -146,6 +153,7 @@ type Video struct { CropLeft int `json:"crop_left,omitempty"` CropRight int `json:"crop_right,omitempty"` CropChecked bool `json:"crop_checked,omitempty"` + CropVersion int `json:"crop_version,omitempty"` FPS float64 `json:"fps"` FieldOrder string `json:"field_order"` VideoStream int `json:"video_stream"` diff --git a/internal/model/model_test.go b/internal/model/model_test.go index d457ec2..2adf286 100644 --- a/internal/model/model_test.go +++ b/internal/model/model_test.go @@ -46,3 +46,19 @@ func TestEncodingKeyAndSettings(t *testing.T) { t.Fatal("illegal menu density accepted") } } + +func TestWorkerLimitsFollowEncoder(t *testing.T) { + s := DefaultSettings(t.TempDir()) + s.Encoders = 4 + if err := s.Validate(); err != nil { + t.Fatal(err) + } + s.VideoEncoder = "FFmpeg" + if err := s.Validate(); err == nil { + t.Fatal("four FFmpeg workers should not be allowed") + } + s.Encoders = 2 + if err := s.Validate(); err != nil { + t.Fatal(err) + } +} diff --git a/internal/platform/legacy_other.go b/internal/platform/legacy_other.go new file mode 100644 index 0000000..c45cc48 --- /dev/null +++ b/internal/platform/legacy_other.go @@ -0,0 +1,7 @@ +//go:build !windows + +package platform + +func LegacyWorkingDir(path string, related ...string) (string, func(), error) { + return path, func() {}, nil +} diff --git a/internal/platform/legacy_windows.go b/internal/platform/legacy_windows.go new file mode 100644 index 0000000..ed82f50 --- /dev/null +++ b/internal/platform/legacy_windows.go @@ -0,0 +1,143 @@ +//go:build windows + +package platform + +import ( + "encoding/binary" + "fmt" + "golang.org/x/sys/windows" + "os" + "path/filepath" + "strings" +) + +// LegacyWorkingDir gives ANSI-based helpers an existing short path when one +// is available. Relative media names remain valid while Windows' ANSI directory +// enumeration avoids lossy conversion of a Unicode parent directory. +func shortPath(path string) string { + if path == "" { + return path + } + input, err := windows.UTF16PtrFromString(path) + if err != nil { + return path + } + buffer := make([]uint16, 1024) + for { + n, err := windows.GetShortPathName(input, &buffer[0], uint32(len(buffer))) + if err != nil || n == 0 { + return path + } + if n >= uint32(len(buffer)) { + buffer = make([]uint16, n+1) + continue + } + return windows.UTF16ToString(buffer[:n]) + } +} + +func asciiPath(path string) bool { + for _, r := range path { + if r > 127 { + return false + } + } + return true +} + +// Alias the common media root, rather than just the working directory, so +// relative references such as ../../assets remain inside the same tree. +func LegacyWorkingDir(dir string, related ...string) (string, func(), error) { + noop := func() {} + if windows.GetACP() == 65001 || asciiPath(dir) { + return dir, noop, nil + } + if short := shortPath(dir); asciiPath(short) { + return short, noop, nil + } + root := dir + for _, path := range related { + for { + rel, err := filepath.Rel(root, path) + if err != nil { + return "", noop, err + } + if rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + break + } + parent := filepath.Dir(root) + if parent == root { + return "", noop, fmt.Errorf("authoring assets must share a local volume") + } + root = parent + } + } + tempRoot := shortPath(os.TempDir()) + if !asciiPath(tempRoot) { + return "", noop, fmt.Errorf("DVD helpers need an ASCII temporary path on this Windows locale; set TEMP to a local folder") + } + parent, err := os.MkdirTemp(tempRoot, "easydvd-path-") + if err != nil { + return "", noop, err + } + link := filepath.Join(parent, "media") + cleanup := func() { _ = os.Remove(link); _ = os.Remove(parent) } + if err = directoryJunction(link, root); err != nil { + cleanup() + return "", noop, err + } + rel, err := filepath.Rel(root, dir) + if err != nil { + cleanup() + return "", noop, err + } + return filepath.Join(link, rel), cleanup, nil +} + +// Directory junction creation uses Unicode APIs and requires no symlink privilege. +// Cleanup removes only the junction itself, never its target directory. +func directoryJunction(link, target string) error { + if err := os.Mkdir(link, 0700); err != nil { + return err + } + absolute, err := filepath.Abs(target) + if err != nil { + return err + } + substitute := `\??\` + absolute + if strings.HasPrefix(absolute, `\\`) { + substitute = `\??\UNC\` + strings.TrimPrefix(absolute, `\\`) + } + sub, err := windows.UTF16FromString(substitute) + if err != nil { + return err + } + printName, err := windows.UTF16FromString(absolute) + if err != nil { + return err + } + names := append(sub, printName...) + buffer := make([]byte, 16+2*len(names)) + if len(buffer) > 16*1024 { + return fmt.Errorf("legacy authoring path is too long") + } + binary.LittleEndian.PutUint32(buffer[0:], windows.IO_REPARSE_TAG_MOUNT_POINT) + binary.LittleEndian.PutUint16(buffer[4:], uint16(len(buffer)-8)) + binary.LittleEndian.PutUint16(buffer[10:], uint16((len(sub)-1)*2)) + binary.LittleEndian.PutUint16(buffer[12:], uint16(len(sub)*2)) + binary.LittleEndian.PutUint16(buffer[14:], uint16((len(printName)-1)*2)) + for i, code := range names { + binary.LittleEndian.PutUint16(buffer[16+2*i:], code) + } + path, err := windows.UTF16PtrFromString(link) + if err != nil { + return err + } + handle, err := windows.CreateFile(path, windows.GENERIC_WRITE, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT|windows.FILE_FLAG_BACKUP_SEMANTICS, 0) + if err != nil { + return err + } + defer windows.CloseHandle(handle) + var returned uint32 + return windows.DeviceIoControl(handle, windows.FSCTL_SET_REPARSE_POINT, &buffer[0], uint32(len(buffer)), nil, 0, &returned, nil) +} diff --git a/internal/platform/legacy_windows_test.go b/internal/platform/legacy_windows_test.go new file mode 100644 index 0000000..894b02f --- /dev/null +++ b/internal/platform/legacy_windows_test.go @@ -0,0 +1,38 @@ +//go:build windows + +package platform + +import ( + "os" + "path/filepath" + "testing" +) + +func TestLegacyJunctionPreservesRelativeMediaAndCleanup(t *testing.T) { + root := filepath.Join(t.TempDir(), "café Ω") + if err := os.MkdirAll(filepath.Join(root, "generation", "disc"), 0755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(root, "assets"), 0755); err != nil { + t.Fatal(err) + } + source := filepath.Join(root, "assets", "video.mpg") + if err := os.WriteFile(source, []byte("retained source"), 0644); err != nil { + t.Fatal(err) + } + link := filepath.Join(t.TempDir(), "alias") + if err := directoryJunction(link, root); err != nil { + t.Fatal(err) + } + defer os.Remove(link) + data, err := os.ReadFile(filepath.Join(link, "generation", "disc", "..", "..", "assets", "video.mpg")) + if err != nil || string(data) != "retained source" { + t.Fatal(string(data), err) + } + if err := os.Remove(link); err != nil { + t.Fatal(err) + } + if data, err := os.ReadFile(source); err != nil || string(data) != "retained source" { + t.Fatal("removing alias affected source", err) + } +} diff --git a/internal/process/process.go b/internal/process/process.go index b6c2257..987a76a 100644 --- a/internal/process/process.go +++ b/internal/process/process.go @@ -8,6 +8,7 @@ import ( "io" "os" "os/exec" + "runtime" "strings" "sync" "time" @@ -38,6 +39,22 @@ type Options struct { Line func(string) } +// Metrics reports process CPU time independently of wall time. CPUPercent is +// normalized to all logical CPUs, matching system-wide CPU utilization displays. +type Metrics struct { + Executable string `json:"executable"` + Args []string `json:"args"` + Seconds float64 `json:"seconds"` + CPUSeconds float64 `json:"cpu_seconds"` + CPUPercent float64 `json:"cpu_percent"` +} + +type observerKey struct{} + +func Observe(ctx context.Context, fn func(Metrics)) context.Context { + return context.WithValue(ctx, observerKey{}, fn) +} + func Run(ctx context.Context, exe string, args []string, opts Options) error { if err := ctx.Err(); err != nil { return err @@ -75,6 +92,7 @@ func Run(ctx context.Context, exe string, args []string, opts Options) error { return err } defer cleanup() + started := time.Now() if err = cmd.Start(); err != nil { return fmt.Errorf("start %s: %w", exe, err) } @@ -90,6 +108,11 @@ func Run(ctx context.Context, exe string, args []string, opts Options) error { <-readDone } err = cmd.Wait() + if observer, ok := ctx.Value(observerKey{}).(func(Metrics)); ok && cmd.ProcessState != nil { + elapsed := time.Since(started).Seconds() + cpu := (cmd.ProcessState.UserTime() + cmd.ProcessState.SystemTime()).Seconds() + observer(Metrics{Executable: exe, Args: append([]string(nil), args...), Seconds: elapsed, CPUSeconds: cpu, CPUPercent: cpu / elapsed / float64(runtime.NumCPU()) * 100}) + } if ctx.Err() != nil { return ctx.Err() } diff --git a/internal/process/process_test.go b/internal/process/process_test.go index 96978df..eeafe84 100644 --- a/internal/process/process_test.go +++ b/internal/process/process_test.go @@ -15,6 +15,15 @@ func TestProcessHelper(t *testing.T) { if os.Getenv("EASYDVD_PROCESS_TEST") != "1" { return } + if os.Args[len(os.Args)-1] == "cpu" { + end := time.Now().Add(120 * time.Millisecond) + var sum uint64 + for time.Now().Before(end) { + sum = sum*1664525 + 1013904223 + } + fmt.Println(sum) + os.Exit(0) + } if len(os.Args) > 0 && os.Args[len(os.Args)-1] == "spawn" { exe, _ := os.Executable() cmd := exec.Command(exe, "-test.run=TestProcessHelper", "--", "child") @@ -57,3 +66,18 @@ func TestFatalDiagnosticBeforeEarlierWarnings(t *testing.T) { t.Fatal("fatal cause must be visible while retaining earlier context", got) } } + +func TestObservedProcessReportsCPUAndWallTime(t *testing.T) { + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + var measurements []Metrics + ctx := Observe(context.Background(), func(m Metrics) { measurements = append(measurements, m) }) + if err := Run(ctx, exe, []string{"-test.run=TestProcessHelper", "--", "cpu"}, Options{Env: []string{"EASYDVD_PROCESS_TEST=1"}}); err != nil { + t.Fatal(err) + } + if len(measurements) != 1 || measurements[0].CPUSeconds <= 0 || measurements[0].Seconds <= 0 || measurements[0].CPUPercent <= 0 { + t.Fatal(measurements) + } +} diff --git a/internal/ui/ui.go b/internal/ui/ui.go index f80f82b..1b95422 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -424,10 +424,25 @@ func (u *window) settingsDialog(id string, s model.Settings) { if !s.NoMenu && (id == "" || u.selectedJob() == nil || len(u.selectedJob().ActiveVideos()) != 1) { noMenu.Disable() } - workers := widget.NewSelect([]string{"1", "2"}, nil) + workerOptions := []string{"1", "2"} + if s.Encoder() == "HCenc" { + workerOptions = append(workerOptions, "3", "4") + } + workers := widget.NewSelect(workerOptions, nil) workers.SetSelected(strconv.Itoa(s.Encoders)) encoder := widget.NewSelect([]string{"HCenc", "FFmpeg"}, nil) encoder.SetSelected(s.Encoder()) + encoder.OnChanged = func(value string) { + count, _ := strconv.Atoi(workers.Selected) + options := []string{"1", "2"} + if value == "HCenc" { + options = append(options, "3", "4") + } else if count > 2 { + count = 2 + } + workers.SetOptions(options) + workers.SetSelected(strconv.Itoa(max(1, count))) + } hcencFolder := widget.NewEntry() hcencFolder.SetText(s.HCencDir) hcencFolder.SetPlaceHolder("Choose the HCenc installation folder, or leave blank for automatic detection") diff --git a/validation/ENCODER-PERFORMANCE-2026-10-29.json b/validation/ENCODER-PERFORMANCE-2026-10-29.json new file mode 100644 index 0000000..65be78a --- /dev/null +++ b/validation/ENCODER-PERFORMANCE-2026-10-29.json @@ -0,0 +1,328 @@ +{ + "date": "2026-10-29", + "cpu": "AMD Ryzen 7 9800X3D", + "physical_cores": 8, + "logical_cpus": 16, + "standard": "PAL", + "output": "MPEG-2 720x576 25 fps 4:3, AC-3 256 kbps", + "video_target_kbps": 8000, + "video_max_kbps": 9000, + "hcenc_profile": "BEST", + "source": "H.264 1280x720 progressive at 18 fps; deidentified real film-scan fixture", + "benchmarks": { + "prepared": { + "input_mode": "DVD-resolution prepared reference", + "duration_seconds": 60, + "runs": [ + { + "Run": 1, + "Encoder": "FFmpeg", + "Status": "authored", + "Seconds": 1.5358067, + "CPUSeconds": 7.6875, + "CPUPercent": 31.2844546126801, + "EncodingSeconds": 1.3490258, + "EncodingCPUPercent": 30.98300640358398, + "EncodingFPS": 1111.9135008389017, + "Bytes": 54830123, + "PSNR": "44.276801", + "SSIM": "0.975386" + }, + { + "Run": 1, + "Encoder": "HCenc", + "Status": "authored", + "Seconds": 15.9722931, + "CPUSeconds": 54.25, + "CPUPercent": 21.228166668191182, + "EncodingSeconds": 13.5544469, + "EncodingCPUPercent": 20.562324641959385, + "EncodingFPS": 110.66478854257048, + "Bytes": 59973269, + "PSNR": "44.539718", + "SSIM": "0.979832" + }, + { + "Run": 2, + "Encoder": "HCenc", + "Status": "authored", + "Seconds": 15.5190543, + "CPUSeconds": 53.765625, + "CPUPercent": 21.65306917252039, + "EncodingSeconds": 13.0973016, + "EncodingCPUPercent": 21.071253524466442, + "EncodingFPS": 114.52740769136751, + "Bytes": 59524582, + "PSNR": "44.527139", + "SSIM": "0.979758" + }, + { + "Run": 2, + "Encoder": "FFmpeg", + "Status": "authored", + "Seconds": 1.4946086, + "CPUSeconds": 8.328125, + "CPUPercent": 34.82569366321056, + "EncodingSeconds": 1.3125353999999998, + "EncodingCPUPercent": 34.82048941308555, + "EncodingFPS": 1142.8263191987053, + "Bytes": 54830123, + "PSNR": "44.276801", + "SSIM": "0.975386" + }, + { + "Run": 3, + "Encoder": "FFmpeg", + "Status": "authored", + "Seconds": 1.4965806, + "CPUSeconds": 8.0625, + "CPUPercent": 33.67050528384505, + "EncodingSeconds": 1.3134335, + "EncodingCPUPercent": 34.49927232707252, + "EncodingFPS": 1142.0448770341247, + "Bytes": 54830123, + "PSNR": "44.276801", + "SSIM": "0.975386" + }, + { + "Run": 3, + "Encoder": "HCenc", + "Status": "authored", + "Seconds": 15.717074, + "CPUSeconds": 53.015625, + "CPUPercent": 21.082019226352184, + "EncodingSeconds": 13.3027151, + "EncodingCPUPercent": 20.43755714200028, + "EncodingFPS": 112.75893595586362, + "Bytes": 59735462, + "PSNR": "44.534609", + "SSIM": "0.979822" + } + ], + "medians": { + "FFmpeg": { + "Seconds": 1.4965806, + "CPUPercent": 33.67050528384505, + "EncodingSeconds": 1.3134335, + "EncodingCPUPercent": 34.49927232707252, + "Bytes": 54830123.0, + "PSNR": 44.276801, + "SSIM": 0.975386 + }, + "HCenc": { + "Seconds": 15.717074, + "CPUPercent": 21.228166668191182, + "EncodingSeconds": 13.3027151, + "EncodingCPUPercent": 20.562324641959385, + "Bytes": 59735462.0, + "PSNR": 44.534609, + "SSIM": 0.979822 + } + } + }, + "source_pipeline": { + "input_mode": "Original-resolution source decoding and scaling", + "duration_seconds": 60, + "runs": [ + { + "Run": 1, + "Encoder": "FFmpeg", + "Status": "authored", + "Seconds": 2.0645383, + "CPUSeconds": 25.671875, + "CPUPercent": 77.7167557269342, + "EncodingSeconds": 1.8835001999999998, + "EncodingCPUPercent": 79.74265811068139, + "EncodingFPS": 796.3896154616815, + "Bytes": 55421404, + "PSNR": "43.856987", + "SSIM": "0.973764" + }, + { + "Run": 1, + "Encoder": "HCenc", + "Status": "authored", + "Seconds": 17.7779251, + "CPUSeconds": 64.140625, + "CPUPercent": 22.54925161373303, + "EncodingSeconds": 14.8261964, + "EncodingCPUPercent": 19.549434135379453, + "EncodingFPS": 101.1722736925298, + "Bytes": 59734256, + "PSNR": "43.601239", + "SSIM": "0.976982" + }, + { + "Run": 2, + "Encoder": "HCenc", + "Status": "authored", + "Seconds": 18.6528627, + "CPUSeconds": 66.890625, + "CPUPercent": 22.412988985867567, + "EncodingSeconds": 15.621947800000001, + "EncodingCPUPercent": 18.94119998915884, + "EncodingFPS": 96.0187563806864, + "Bytes": 59993740, + "PSNR": "43.592824", + "SSIM": "0.976968" + }, + { + "Run": 2, + "Encoder": "FFmpeg", + "Status": "authored", + "Seconds": 2.0171053, + "CPUSeconds": 25.71875, + "CPUPercent": 79.68953703111087, + "EncodingSeconds": 1.8342578, + "EncodingCPUPercent": 82.73526900090053, + "EncodingFPS": 817.7694542173952, + "Bytes": 55421404, + "PSNR": "43.856987", + "SSIM": "0.973764" + }, + { + "Run": 3, + "Encoder": "FFmpeg", + "Status": "authored", + "Seconds": 2.0217354, + "CPUSeconds": 24.5625, + "CPUPercent": 75.93259978531316, + "EncodingSeconds": 1.836566, + "EncodingCPUPercent": 81.46147483945582, + "EncodingFPS": 816.7416798525073, + "Bytes": 55421404, + "PSNR": "43.856987", + "SSIM": "0.973764" + }, + { + "Run": 3, + "Encoder": "HCenc", + "Status": "authored", + "Seconds": 17.0604499, + "CPUSeconds": 64.96875, + "CPUPercent": 23.800936662285796, + "EncodingSeconds": 14.1210292, + "EncodingCPUPercent": 19.993175762996085, + "EncodingFPS": 106.22455196112759, + "Bytes": 59723629, + "PSNR": "43.613617", + "SSIM": "0.977045" + } + ], + "medians": { + "FFmpeg": { + "Seconds": 2.0217354, + "CPUPercent": 77.7167557269342, + "EncodingSeconds": 1.836566, + "EncodingCPUPercent": 81.46147483945582, + "Bytes": 55421404.0, + "PSNR": 43.856987, + "SSIM": 0.973764 + }, + "HCenc": { + "Seconds": 17.7779251, + "CPUPercent": 22.54925161373303, + "EncodingSeconds": 14.8261964, + "EncodingCPUPercent": 19.549434135379453, + "Bytes": 59734256.0, + "PSNR": 43.601239, + "SSIM": 0.976982 + } + } + } + }, + "priority_runs": [ + { + "priority": "IDLE", + "copies": 1, + "seconds": 12.9943314, + "cpu_seconds": 42.734375, + "cpu_percent": 20.554335234977923, + "fps": 115.43495035073525 + }, + { + "priority": "NORMAL", + "copies": 1, + "seconds": 14.3404926, + "cpu_seconds": 43.765625, + "cpu_percent": 19.074320797738846, + "fps": 104.59891733426228 + }, + { + "priority": "NORMAL", + "copies": 1, + "seconds": 13.0772834, + "cpu_seconds": 43.0625, + "cpu_percent": 20.580774826673863, + "fps": 114.70272182064969 + }, + { + "priority": "IDLE", + "copies": 1, + "seconds": 13.8274325, + "cpu_seconds": 43.9375, + "cpu_percent": 19.85975162055573, + "fps": 108.48000885196872 + }, + { + "priority": "IDLE", + "copies": 1, + "seconds": 14.2496069, + "cpu_seconds": 45.40625, + "cpu_percent": 19.915571320076204, + "fps": 105.26606176062303 + }, + { + "priority": "NORMAL", + "copies": 1, + "seconds": 13.0758808, + "cpu_seconds": 42.265625, + "cpu_percent": 20.202092714855585, + "fps": 114.7150255453537 + }, + { + "priority": "NORMAL", + "copies": 2, + "seconds": 14.1732161, + "cpu_seconds": 93.203125, + "cpu_percent": 41.1000246620102, + "fps": 211.66684955858398 + }, + { + "priority": "IDLE", + "copies": 2, + "seconds": 14.3115074, + "cpu_seconds": 93.078125, + "cpu_percent": 40.64828847099643, + "fps": 209.62152456421188 + } + ], + "four_normal": { + "priority": "NORMAL", + "copies": 4, + "seconds": 18.1428816, + "cpu_seconds": 203.9375, + "cpu_percent": 70.2539653348121, + "fps": 330.7082156122322 + }, + "four_idle": { + "priority": "IDLE", + "copies": 4, + "seconds": 17.4328555, + "cpu_seconds": 202.234375, + "cpu_percent": 72.50475079943158, + "fps": 344.1776936658484 + }, + "crop_regression": { + "source_frames_checked": 14312, + "content_left": 158, + "content_right_exclusive": 1122, + "crop_left": 158, + "crop_right": 158, + "source_duration": 795.111111, + "dvd_duration": 795.12, + "dvd_aspect": "4:3", + "full_dvd_decode": "passed", + "iso_hash_matches_manifest": true + } +} diff --git a/validation/ENCODER-PERFORMANCE-2026-10-29.md b/validation/ENCODER-PERFORMANCE-2026-10-29.md new file mode 100644 index 0000000..803eca8 --- /dev/null +++ b/validation/ENCODER-PERFORMANCE-2026-10-29.md @@ -0,0 +1,95 @@ +# Encoder performance and pillarbox follow-up — 2026-10-29 + +Measured on an AMD Ryzen 7 9800X3D (8 cores / 16 logical processors), Windows, +FFmpeg 9.0.2 and HCenc 0.28.0.2 BEST. Inputs came from a read-only real film-scan +fixture: H.264, 1280×720, 18 fps, with baked-in black side borders. All benchmark +media, references, complete logs and ISOs remain in isolated local scratch space. +Deidentified measurements are in [the JSON results](ENCODER-PERFORMANCE-2026-10-29.json). + +## One-title comparison + +Each encoder ran three times, alternating order, without concurrent encoders. +PAL output is 720×576 at 25 fps, 4:3, two-pass video at 8 Mbps average / 9 Mbps +maximum and AC-3 audio. CPU use is process user+kernel CPU time divided by wall +time and all 16 logical CPUs. These are averages, not instantaneous peaks. + +| 60-second test | FFmpeg elapsed | HCenc elapsed | FFmpeg average CPU | HCenc average CPU | +|---|---:|---:|---:|---:| +| Source decoding/scaling included | 2.02 s | 17.78 s | 77.7% | 22.5% | +| Same prepared DVD-resolution frames | 1.50 s | 15.72 s | 33.7% | 21.2% | + +Numbers are medians. Elapsed time includes the production encode path: MPEG-2 +passes, HCenc's lossless FFV1 preparation, audio/mux, full decode validation and +checkpoint hashing. Shared source analysis/reference creation, network staging, +quality metrics and DVD/ISO authoring are outside this timing. The prepared test +uses a scene beginning at 60 seconds; the source-path test uses the first minute. + +HCenc took **8.8×** as long in the source-path test. Its MPEG-2 phase averaged +19.5% CPU, equivalent to about 3.1 fully occupied logical processors. FFmpeg's +two passes including source decoding/scaling averaged 81.5%. The user's CPU +observation was reproduced. HCenc logs confirm SMP is active and both passes +finish; changing IDLE to NORMAL priority left utilization near 20% and produced +overlapping runtime ranges. There is no evidence that an application CPU cap or +process priority explains the difference. + +The source-path video streams were 55.42 MB for FFmpeg and 59.73 MB for HCenc. +HCenc's SSIM was slightly higher (0.976982 vs 0.973764), while PSNR was slightly +lower (43.60 vs 43.86 dB). On the other scene HCenc improved both metrics. Its +files were also larger. These measurements do not establish a universal quality +winner or compare equal-sized files; grain/motion still need visual review. + +## HCenc concurrency + +The same 1,500 prepared frames were encoded per title with private output and +log files. These numbers isolate native HCenc; normalization, audio and authoring +are outside the timing. All rows below use the existing IDLE priority. + +| Concurrent titles | Batch elapsed | Aggregate frames/second | Average total CPU | +|---|---:|---:|---:| +| 1 | 13.83 s (median of 3) | 108.5 | 19.9% | +| 2 | 14.31 s | 209.6 | 40.6% | +| 4 | 17.43 s | 344.2 | 72.5% | + +Four titles delivered about **3.2×** the throughput of one. Two/four-title batch +measurements are single runs, so small differences should not be overinterpreted. +NORMAL-priority batches gave similar results. The app now permits up to four +HCenc workers; the default stays two and FFmpeg retains its two-worker limit. +This improves multi-title jobs. A single video still uses one native encoder. + +## Why this file retained pillarboxes + +The earlier detector demanded that every frame fit exactly between x=160 and +x=1120. Across the complete 795.111111-second source, 12,591 frames extended +outside those exact bounds by only 1–2 pixels. The full observed horizontal union +was **[158,1122)** across 14,312 frames. Consequently the old code rejected the +crop and encoded/flagged the original frame as 16:9. The user's report was correct. + +The detector now allows a narrow boundary variation and expands the kept image +to include every observed pixel. This file removes 158 pixels from each side, +keeping a 964×720 source rectangle. Its actual aspect controls fitting into a +4:3 DVD frame; a tiny amount of vertical padding handles the difference without +stretching or discarding the edge. Wider content and a small visible mark deeper +inside a side border still prevent cropping. + +The detector/cache version changes so an old rejected crop is not reused for a +new encode. Completed outputs are preserved; a new job produces corrected media. +The complete failing source was re-encoded with FFmpeg. Both its MPG metadata and +DVD-demuxed title report **4:3**. Full DVD-title decoding passed; output duration +is 795.120 seconds (difference 0.008889 seconds), and the ISO hash matches the +manifest. The decoded frame was visually checked: the large baked-in side bars +are gone. The HCenc benchmark outputs also report 4:3 and author successfully. + +## Regression checks + +Unit tests/vet, media/engine/process/platform race tests, PAL/NTSC pipelines with +both encoders, the new edge-variation fixture, and an actual four-worker HCenc +job passed. The benchmark now explicitly chooses each backend; its older FFmpeg +case could inherit the HCenc default. Per-process CPU/wall timing and repeated, +alternating runs are now recorded. + +The preceding Windows CI run also exposed Unicode working-directory enumeration +in the legacy DVD helper and missing HCenc discovery from a test-package working +directory. Windows helpers now use short paths or temporary junctions when +needed, retaining relative media references; cleanup removes only the alias. +CI exports the prepared HCenc directory explicitly. No fixture or GUI queue was +modified by these checks. diff --git a/validation/GITHUB-ISSUES-2026-10-29.md b/validation/GITHUB-ISSUES-2026-10-29.md index 43ceab5..1cca7fb 100644 --- a/validation/GITHUB-ISSUES-2026-10-29.md +++ b/validation/GITHUB-ISSUES-2026-10-29.md @@ -1,5 +1,9 @@ # GitHub issue validation — 2026-10-29 +Follow-up: [performance measurements and the additional H.264 pillarbox +regression](ENCODER-PERFORMANCE-2026-10-29.md). That report records the stricter +boundary check's failure on the user's additional fixture and its correction. + Addresses issues [#1](https://github.com/maghofer/easyDVD/issues/1), [#2](https://github.com/maghofer/easyDVD/issues/2), [#3](https://github.com/maghofer/easyDVD/issues/3), From ec9744757e29d34b24e7c8db51513f8af36a9135 Mon Sep 17 00:00:00 2001 From: maghofer <327971135+maghofer@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:33:25 +0100 Subject: [PATCH 3/7] Protect legacy helper paths independently of parent process locale --- internal/platform/legacy_windows.go | 8 ++++---- validation/ENCODER-PERFORMANCE-2026-10-29.md | 5 +++++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/internal/platform/legacy_windows.go b/internal/platform/legacy_windows.go index ed82f50..05915be 100644 --- a/internal/platform/legacy_windows.go +++ b/internal/platform/legacy_windows.go @@ -11,9 +11,7 @@ import ( "strings" ) -// LegacyWorkingDir gives ANSI-based helpers an existing short path when one -// is available. Relative media names remain valid while Windows' ANSI directory -// enumeration avoids lossy conversion of a Unicode parent directory. +// shortPath returns an existing Windows short name when the volume provides one. func shortPath(path string) string { if path == "" { return path @@ -49,7 +47,9 @@ func asciiPath(path string) bool { // relative references such as ../../assets remain inside the same tree. func LegacyWorkingDir(dir string, related ...string) (string, func(), error) { noop := func() {} - if windows.GetACP() == 65001 || asciiPath(dir) { + // A UTF-8 manifest on the Go executable does not change a child helper's + // ANSI code page. Protect non-ASCII paths independently of our own GetACP. + if asciiPath(dir) { return dir, noop, nil } if short := shortPath(dir); asciiPath(short) { diff --git a/validation/ENCODER-PERFORMANCE-2026-10-29.md b/validation/ENCODER-PERFORMANCE-2026-10-29.md index 803eca8..c43046e 100644 --- a/validation/ENCODER-PERFORMANCE-2026-10-29.md +++ b/validation/ENCODER-PERFORMANCE-2026-10-29.md @@ -23,6 +23,8 @@ passes, HCenc's lossless FFV1 preparation, audio/mux, full decode validation and checkpoint hashing. Shared source analysis/reference creation, network staging, quality metrics and DVD/ISO authoring are outside this timing. The prepared test uses a scene beginning at 60 seconds; the source-path test uses the first minute. +CPU percentages sum the child tools' CPU time; Go's checkpoint hashing is +included in elapsed time but not in that CPU-time sum. HCenc took **8.8×** as long in the source-path test. Its MPEG-2 phase averaged 19.5% CPU, equivalent to about 3.1 fully occupied logical processors. FFmpeg's @@ -78,6 +80,9 @@ DVD-demuxed title report **4:3**. Full DVD-title decoding passed; output duratio is 795.120 seconds (difference 0.008889 seconds), and the ISO hash matches the manifest. The decoded frame was visually checked: the large baked-in side bars are gone. The HCenc benchmark outputs also report 4:3 and author successfully. +The second full-length source from the same user test (793.888889 seconds) was +also regenerated with 158 pixels removed per side. Its MPG reports 4:3; full DVD +decoding and ISO hash verification passed as well. ## Regression checks From 391dae85194c8fc7afaed90adf014b40cf3a97c8 Mon Sep 17 00:00:00 2001 From: maghofer <327971135+maghofer@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:37:09 +0100 Subject: [PATCH 4/7] Allow asynchronous process-tree termination within cancellation budget --- internal/process/process_test.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/internal/process/process_test.go b/internal/process/process_test.go index eeafe84..7330d8c 100644 --- a/internal/process/process_test.go +++ b/internal/process/process_test.go @@ -53,6 +53,12 @@ func TestCancelProcessTree(t *testing.T) { if pid == 0 { t.Fatal("helper did not start") } + // Group/job termination is asynchronous: the parent can be reaped before + // the kernel schedules a killed grandchild. Keep the same four-second + // cancellation budget rather than asserting on that intermediate state. + for processAlive(pid) && time.Since(start) < 4*time.Second { + time.Sleep(10 * time.Millisecond) + } if processAlive(pid) { t.Fatalf("grandchild %d survived cancellation", pid) } From 8afd8e91ff4cc3d5adaaf3b78df37bd1cb9e3c7b Mon Sep 17 00:00:00 2001 From: maghofer <327971135+maghofer@users.noreply.github.com> Date: Thu, 29 Oct 2026 20:29:00 +0100 Subject: [PATCH 5/7] Remove HCenc and tune FFmpeg for DVD quality --- .github/workflows/ci.yml | 9 - README.md | 10 +- THIRD_PARTY.md | 8 +- cmd/easydvd-benchmark/main.go | 242 ++- docs/ENCODERS.md | 192 ++- docs/RELEASING.md | 8 +- internal/app/cli.go | 13 +- internal/engine/engine.go | 18 - internal/integration/issues_test.go | 185 +-- internal/integration/pipeline_test.go | 44 +- internal/media/encode.go | 47 +- internal/media/encode_test.go | 2 +- internal/media/ffmpeg.go | 2 +- internal/media/ffmpeg_test.go | 4 +- internal/media/hcenc.go | 213 --- internal/media/hcenc_test.go | 53 - internal/model/model.go | 51 +- internal/model/model_test.go | 38 +- internal/ui/ui.go | 29 +- scripts/package.ps1 | 2 - scripts/prepare-hcenc.ps1 | 44 - validation/ENCODER-PERFORMANCE-2026-10-29.md | 4 + validation/FFMPEG-QUALITY-2026-10-29.json | 1486 ++++++++++++++++++ validation/FFMPEG-QUALITY-2026-10-29.md | 105 ++ validation/GITHUB-ISSUES-2026-10-29.md | 4 + 25 files changed, 1978 insertions(+), 835 deletions(-) delete mode 100644 internal/media/hcenc.go delete mode 100644 internal/media/hcenc_test.go delete mode 100644 scripts/prepare-hcenc.ps1 create mode 100644 validation/FFMPEG-QUALITY-2026-10-29.json create mode 100644 validation/FFMPEG-QUALITY-2026-10-29.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a8a1a5c..9398661 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,8 +17,6 @@ jobs: run: ./scripts/audit-source.ps1 windows: runs-on: windows-latest - env: - EASYDVD_HCENC: ${{ github.workspace }}/.tools/hcenc/bin steps: - uses: actions/checkout@v4 - uses: actions/cache@v4 @@ -28,13 +26,6 @@ jobs: - name: Prepare pinned development and media tools shell: pwsh run: ./scripts/bootstrap.ps1 - - uses: actions/cache@v4 - with: - path: .tools/hcenc - key: ${{ runner.os }}-hcenc-${{ hashFiles('scripts/prepare-hcenc.ps1') }} - - name: Prepare pinned HCenc runtime - shell: pwsh - run: ./scripts/prepare-hcenc.ps1 -CacheDir .tools/hcenc/setup - name: Build and validate DVD pipeline shell: pwsh run: ./scripts/build.ps1 -Test -Integration diff --git a/README.md b/README.md index b0709aa..690666f 100644 --- a/README.md +++ b/README.md @@ -52,10 +52,12 @@ using easyDVD. 3. Choose your TV standard, disc capacity and menu style, then select **Start / resume**. Finished ISO files appear in your output folder. -New jobs use HCenc for two-pass MPEG-2 video. Set up its private runtime as -described in [Encoder setup](docs/ENCODERS.md), or choose **FFmpeg** under -**Settings → Video encoder**. For a single included video, **Job settings → -Playback → No menu** creates a disc that starts automatically and stops at the end. +FFmpeg performs high-quality two-pass MPEG-2 encoding, targeting 9 Mbps video +with 448 kbps AC-3 audio. easyDVD adds discs instead of reducing the bitrate to +squeeze more footage onto one disc. FFmpeg remains an external dependency; +first run can locate it or download a private copy. See [Encoding quality](docs/ENCODERS.md). +For a single included video, **Job settings → Playback → No menu** creates a +disc that starts automatically and stops at the end. For more on menu appearance and presets, see [Menu settings](docs/MENUS.md). Report problems or suggest changes through [GitHub Issues](https://github.com/maghofer/easyDVD/issues). diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 9a51582..9850353 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -36,9 +36,5 @@ files used by older candidates. The current helper source recipe is in `scripts/toolchain/README.md`. No bit-identical reproduction claim is made; the matching source and all our build changes are supplied. -HCenc is the default video backend for new jobs; its private AviSynth/FFMS2 -runtime is installed separately. The setup helper preserves upstream notices and -records pinned download hashes. These binaries are not part of the normal app -package. mpeg2enc remains an optional benchmark input. These components are not -distributed by easyDVD. No encoder superiority claim is made without a -completed comparison on representative material. +FFmpeg is the sole video encoder. No AviSynth runtime or separately installed +MPEG-2 encoder is required. diff --git a/cmd/easydvd-benchmark/main.go b/cmd/easydvd-benchmark/main.go index ed16952..4b63e77 100644 --- a/cmd/easydvd-benchmark/main.go +++ b/cmd/easydvd-benchmark/main.go @@ -1,4 +1,4 @@ -// easydvd-benchmark compares MPEG-2 encoders against a single normalized reference. +// easydvd-benchmark measures the production encoder against a normalized reference. package main import ( @@ -8,7 +8,6 @@ import ( "fmt" "io" "os" - "os/exec" "os/signal" "path/filepath" "regexp" @@ -75,17 +74,14 @@ func run() error { standard := flag.String("standard", "PAL", "PAL or NTSC") seconds := flag.Float64("seconds", 10, "Maximum sample duration") offset := flag.Float64("offset", 0, "Start time in seconds for the sample") - repeats := flag.Int("repeats", 1, "Repeated runs, alternating encoder order") + repeats := flag.Int("repeats", 1, "Number of sequential production encoder runs") sourcePipeline := flag.Bool("source-pipeline", false, "Include source decoding/scaling; input must be a complete sample within -seconds, with -offset 0") - mpeg := flag.String("mpeg2enc", "", "Optional mpeg2enc executable") - hc := flag.String("hcenc", "", "Optional HCenc executable") - ffms := flag.String("ffms2", "", "FFMS2 AviSynth plugin DLL, required for HCenc") flag.Parse() if *offset < 0 || *repeats < 1 { return fmt.Errorf("offset must be nonnegative and repeats positive") } if *input == "" || *output == "" { - return fmt.Errorf("use -input VIDEO -output NEW_DIRECTORY [-mpeg2enc EXE] [-hcenc EXE -ffms2 DLL]") + return fmt.Errorf("use -input VIDEO -output NEW_DIRECTORY") } if *seconds <= 0 { return fmt.Errorf("sample duration must be positive") @@ -109,12 +105,6 @@ func run() error { s.WorkDir = filepath.Join(dir, "work") s.OutputDir = filepath.Join(dir, "output") s.Encoders = 1 - if *hc != "" { - s.HCencDir, _ = filepath.Abs(filepath.Dir(*hc)) - } - if *ffms != "" && *hc != "" && !strings.EqualFold(filepath.Clean(filepath.Dir(*ffms)), s.HCencDir) { - return fmt.Errorf("use a complete private HCenc runtime with ffms2.dll beside HCenc_028.exe") - } if err = s.Validate(); err != nil { return err } @@ -146,14 +136,19 @@ func run() error { if *sourcePipeline && (*offset != 0 || duration < original.Duration) { return fmt.Errorf("-source-pipeline needs a complete sample: use -offset 0 and -seconds at least the source duration") } - // Normalize once; encoder comparisons must not include different scaling or cadence conversions. + // Progressive references make frame-aligned PSNR/SSIM meaningful. The full + // source pipeline benchmark deliberately excludes retained interlaced input. interlaced := original.FieldOrder == "tt" || original.FieldOrder == "bb" || original.FieldOrder == "tb" || original.FieldOrder == "bt" + if *sourcePipeline && interlaced { + return fmt.Errorf("use a progressive sample for -source-pipeline frame quality measurements") + } normalized := original normalized.FieldOrder = "progressive" filter, _ := media.VideoFilter(normalized, s) if interlaced { filter = "bwdif=mode=send_frame:parity=auto:deint=all," + filter } + reference := filepath.Join(dir, "reference.y4m") if err = process.Run(prepCtx, tools.FFmpeg, []string{"-hide_banner", "-nostdin", "-y", "-ss", fmt.Sprintf("%.6f", *offset), "-i", source, "-map", fmt.Sprintf("0:%d", original.VideoStream), "-vf", filter, "-t", fmt.Sprintf("%.6f", duration), "-pix_fmt", "yuv420p", "-an", "-f", "yuv4mpegpipe", reference}, process.Options{Log: log}); err != nil { return err @@ -162,136 +157,110 @@ func run() error { if original.Aspect() == "16:9" { ref.DAR = 16.0 / 9 } - report := Report{Source: source, Reference: reference, Standard: s.Standard, Duration: duration, Tools: tools.Check(ctx), Notes: []string{"Prepared frames are identical for all encoder inputs; audio and menu size are excluded from video-size comparisons.", "FFmpeg and HCenc target 8 Mbps average / 9 Mbps peak. mpeg2enc uses quality 2 with an 8 Mbps cap; compare measured sizes as well as quality.", "SSIM and PSNR are supporting measurements. Review grain, fine detail, motion, banding and cadence visually before choosing an encoder.", "A generated ISO confirms basic authoring interoperability; physical-player validation and full DVD/VBV conformance remain separate checks.", "HCenc requires a matching AviSynth installation and FFMS2 plugin. Optional encoders are not redistributed by easyDVD."}} - report.LogicalCPUs, report.Repeats, report.Preparation = runtime.NumCPU(), *repeats, preparation - report.InputMode = "DVD-resolution prepared reference" + report := Report{Source: source, Reference: reference, Standard: s.Standard, Duration: duration, Tools: tools.Check(ctx), + LogicalCPUs: runtime.NumCPU(), Repeats: *repeats, Preparation: preparation, + InputMode: "DVD-resolution prepared progressive reference", + Notes: []string{ + "The production two-pass FFmpeg profile targets 9 Mbps video with a 9 Mbps peak and 448 kbps stereo AC-3. Video sizes exclude audio and DVD muxing.", + "Seconds includes production encoding, audio/mux, complete decode validation and checkpoint hashing; EncodingSeconds isolates both MPEG-2 passes. Reference preparation, quality measurements and authoring are outside these timings.", + "CPU percentages divide process CPU seconds by wall seconds and all logical CPUs. Runs are sequential.", + "SSIM/PSNR compare decoded output against the DVD-resolution reference. Visual assessment and physical-player compatibility still require separate review.", + }} if *sourcePipeline { - report.InputMode = "Original-resolution source decoding and scaling" + report.InputMode = "Original-resolution progressive source decoding and scaling" + } + + report.SourceSHA256, err = media.HashFile(ctx, source) + if err != nil { + return err + } + report.ReferenceSHA256, err = media.HashFile(ctx, reference) + if err != nil { + return err } - report.Notes = append(report.Notes, "Seconds includes the production encode path (HCenc lossless preparation, audio/mux, full decode validation and checkpoint hashing). EncodingSeconds isolates the two MPEG-2 passes. CPU percentages use process CPU seconds divided by wall seconds and all logical CPUs. Preparation is recorded separately. Encoder order alternates between repeats; no candidates run concurrently.") - report.SourceSHA256, _ = media.HashFile(ctx, source) - report.ReferenceSHA256, _ = media.HashFile(ctx, reference) + failed := false for run := 1; run <= *repeats; run++ { - names := []string{"FFmpeg", "HCenc", "mpeg2enc"} - if run%2 == 0 { - names = []string{"HCenc", "FFmpeg", "mpeg2enc"} + name := "FFmpeg" + + result := Result{Run: run, Encoder: name, Status: "encoding"} + measured := process.Observe(ctx, func(m process.Metrics) { result.Steps = append(result.Steps, m) }) + candidate := filepath.Join(dir, fmt.Sprintf("%02d-%s", run, strings.ToLower(name))) + if err = os.MkdirAll(candidate, 0755); err != nil { + return err } - for _, name := range names { - result := Result{Run: run, Encoder: name, Status: "not available"} - measured := process.Observe(ctx, func(m process.Metrics) { result.Steps = append(result.Steps, m) }) - candidate := filepath.Join(dir, fmt.Sprintf("%02d-%s", run, strings.ToLower(name))) - if err = os.MkdirAll(candidate, 0755); err != nil { - return err - } - encoded := "" - start := time.Now() - switch name { - case "FFmpeg", "HCenc": - settings := s - settings.VideoEncoder = name - if name == "HCenc" { - if e := tools.RequireEncoder(settings); e != nil { - result.Error = e.Error() - report.Results = append(report.Results, result) - continue - } - } - var v model.Video - video, input := ref, reference - if *sourcePipeline { - video, input = original, source - } - v, err = tools.Encode(measured, video, settings, input, candidate, log, nil) - encoded = v.Encoded - case "mpeg2enc": - binary := *mpeg - if binary == "" { - binary, _ = exec.LookPath("mpeg2enc") - } - if binary == "" { - report.Results = append(report.Results, result) - continue - } - binary, _ = filepath.Abs(binary) - encoded = filepath.Join(candidate, "video.m2v") - f, e := os.Open(reference) - if e != nil { - return e - } - norm := "p" - if s.Standard == "NTSC" { - norm = "n" - } - aspect := "2" - if ref.Aspect() == "16:9" { - aspect = "3" - } - err = process.Run(measured, binary, []string{"-f", "8", "-n", norm, "-a", aspect, "-b", "8000", "-q", "2", "-I", "0", "-o", encoded}, process.Options{Stdin: f, Log: log}) - f.Close() - } - result.Seconds = time.Since(start).Seconds() - var encodingCPU float64 - for _, step := range result.Steps { - result.CPUSeconds += step.CPUSeconds - if strings.HasPrefix(strings.ToLower(filepath.Base(step.Executable)), "hcenc") || hasArg(step.Args, "-pass") { - result.EncodingSeconds += step.Seconds - encodingCPU += step.CPUSeconds - } - } - result.CPUPercent = result.CPUSeconds / result.Seconds / float64(runtime.NumCPU()) * 100 - if result.EncodingSeconds > 0 { - result.EncodingCPUPercent = encodingCPU / result.EncodingSeconds / float64(runtime.NumCPU()) * 100 - result.EncodingFPS = duration * media.Ratio(s.FPS()) / result.EncodingSeconds - } - if err != nil { - result.Status = "failed" - result.Error = err.Error() - report.Results = append(report.Results, result) - continue - } - result.Status = "encoded" - st, e := os.Stat(encoded) - if e != nil { - result.Status = "failed" - result.Error = e.Error() - report.Results = append(report.Results, result) - continue - } - result.Bytes = st.Size() - if name == "FFmpeg" || name == "HCenc" { - elementary := filepath.Join(candidate, "video.m2v") - err = process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-y", "-i", encoded, "-map", "0:v:0", "-c:v", "copy", "-an", "-f", "mpeg2video", elementary}, process.Options{Log: log}) - if err == nil { - st, _ = os.Stat(elementary) - result.Bytes = st.Size() - } - } - result.PSNR = metric(ctx, tools, reference, encoded, "psnr", log) - result.SSIM = metric(ctx, tools, reference, encoded, "ssim", log) - dvdVideo := encoded - if name != "FFmpeg" && name != "HCenc" { - dvdVideo = filepath.Join(candidate, "video.mpg") - err = process.Run(ctx, tools.FFmpeg, []string{"-hide_banner", "-nostdin", "-y", "-i", encoded, "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo", "-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "ac3", "-ac", "2", "-b:a", "256k", "-t", fmt.Sprintf("%.6f", duration), "-f", "dvd", "-muxrate", "10080k", "-packetsize", "2048", dvdVideo}, process.Options{Log: log}) + start := time.Now() + video, input := ref, reference + if *sourcePipeline { + video, input = original, source + } + v, encodeErr := tools.Encode(measured, video, s, input, candidate, log, nil) + err = encodeErr + encoded := v.Encoded + + result.Seconds = time.Since(start).Seconds() + var encodingCPU float64 + for _, step := range result.Steps { + result.CPUSeconds += step.CPUSeconds + if hasArg(step.Args, "-pass") { + result.EncodingSeconds += step.Seconds + encodingCPU += step.CPUSeconds } + } + result.CPUPercent = result.CPUSeconds / result.Seconds / float64(runtime.NumCPU()) * 100 + if result.EncodingSeconds > 0 { + result.EncodingCPUPercent = encodingCPU / result.EncodingSeconds / float64(runtime.NumCPU()) * 100 + result.EncodingFPS = duration * media.Ratio(s.FPS()) / result.EncodingSeconds + } + if err != nil { + failed = true + result.Status = "failed" + result.Error = err.Error() + report.Results = append(report.Results, result) + continue + } + result.Status = "encoded" + st, e := os.Stat(encoded) + if e != nil { + failed = true + result.Status = "failed" + result.Error = e.Error() + report.Results = append(report.Results, result) + continue + } + result.Bytes = st.Size() + elementary := filepath.Join(candidate, "video.m2v") + err = process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-y", "-i", encoded, "-map", "0:v:0", "-c:v", "copy", "-an", "-f", "mpeg2video", elementary}, process.Options{Log: log}) + if err == nil { + st, err = os.Stat(elementary) if err == nil { - v := ref - v.Encoded = dvdVideo - j := model.Job{Title: name + " sample", Settings: s, Videos: []model.Video{v}} - iso, e := tools.Author(ctx, j, model.Disc{Number: 1, VideoIDs: []string{v.ID}}, 1, filepath.Join(candidate, "dvd-check"), log, func(string) error { return nil }) - if e != nil { - err = e - } else { - result.DVDISO = iso - result.Status = "authored" - } + result.Bytes = st.Size() } - if err != nil { - result.Error = err.Error() - result.Status = "authoring failed" + } + result.PSNR = metric(ctx, tools, reference, encoded, "psnr", log) + result.SSIM = metric(ctx, tools, reference, encoded, "ssim", log) + if err == nil && (strings.HasPrefix(result.PSNR, "failed:") || strings.HasPrefix(result.SSIM, "failed:") || result.PSNR == "unavailable" || result.SSIM == "unavailable") { + err = fmt.Errorf("quality measurement failed: PSNR %s; SSIM %s", result.PSNR, result.SSIM) + } + dvdVideo := encoded + if err == nil { + v := ref + v.Encoded = dvdVideo + j := model.Job{Title: name + " sample", Settings: s, Videos: []model.Video{v}} + iso, e := tools.Author(ctx, j, model.Disc{Number: 1, VideoIDs: []string{v.ID}}, 1, filepath.Join(candidate, "dvd-check"), log, func(string) error { return nil }) + if e != nil { + err = e + } else { + result.DVDISO = iso + result.Status = "authored" } - report.Results = append(report.Results, result) - fmt.Printf("Run %d %s: %s · %.2fs total · %.2fs MPEG-2 · %.1f%% CPU · %d bytes · SSIM %s · PSNR %s\n", run, name, result.Status, result.Seconds, result.EncodingSeconds, result.EncodingCPUPercent, result.Bytes, result.SSIM, result.PSNR) } + if err != nil { + result.Error = err.Error() + result.Status = "validation failed" + failed = true + } + report.Results = append(report.Results, result) + fmt.Printf("Run %d %s: %s · %.2fs total · %.2fs MPEG-2 · %.1f%% CPU · %d bytes · SSIM %s · PSNR %s\n", run, name, result.Status, result.Seconds, result.EncodingSeconds, result.EncodingCPUPercent, result.Bytes, result.SSIM, result.PSNR) } b, err := json.MarshalIndent(report, "", " ") if err != nil { @@ -301,6 +270,9 @@ func run() error { return err } fmt.Println("Report:", filepath.Join(dir, "report.json")) + if failed { + return fmt.Errorf("benchmark failed; inspect report.json and benchmark.log") + } return ctx.Err() } diff --git a/docs/ENCODERS.md b/docs/ENCODERS.md index 8342370..78f9074 100644 --- a/docs/ENCODERS.md +++ b/docs/ENCODERS.md @@ -1,113 +1,107 @@ -# MPEG-2 encoder comparison - -HCenc is the default video encoder for new jobs. It uses the BEST profile and -two-pass VBR at 8 Mbps average / 9 Mbps maximum. FFmpeg remains available in -Settings / Video encoder. Existing started jobs retain their previous encoder -and compatible saved encodes. Neither encoder is declared a universal quality -winner; review actual film scans, especially moving grain and fine texture. - -## HCenc setup - -HCenc 0.28 requires **32-bit** AviSynth and FFMS2 even though easyDVD itself is -64-bit. These components are installed separately from the normal portable app. -The pinned setup helper downloads and verifies all three components, preserves -their notices and creates a private runtime without changing system AviSynth: - -```powershell -./scripts/prepare-hcenc.ps1 -OutputDir C:\Tools\easyDVD-HCenc +# DVD encoding quality + +FFmpeg is the sole video encoder. The normal package keeps FFmpeg/FFprobe +external: locate a compatible installation or accept the app's private download. +There is no separate encoder runtime to install. + +## Bitrate and disc space + +Every title uses two-pass VBR with a **9,000 kbps target and maximum**. easyDVD +never lowers a title's bitrate to fit more footage on a disc: it packs the actual +encoded sizes and uses additional discs when needed. A title that cannot fit +whole on the selected medium is reported; choose DVD-9 or split the source. + +The ceiling follows FFmpeg's DVD target, leaving room for 448 kbps AC-3, +navigation and multiplexing within the 10,080 kbps programme-stream mux rate. +The DVD video buffer is 1,835,008 bits. A short programme may leave much of a +disc empty: exceeding the bitrate ceiling or adding padding cannot improve it. +Very simple material can also use fewer bits after reaching quantizer 1. +ISO size checks and packing reserves remain authoritative for disc capacity. + +## Production profile + +Both passes use the same quality settings: + +```text +-c:v mpeg2video -profile:v 4 -level:v 8 -pix_fmt yuv420p +-b:v 9000k -maxrate:v 9000k -minrate:v 0 -bufsize:v 1835008 +-qmin 1 -lmin 118 -mbd rd -trellis 1 -intra_vlc 1 +-cmp satd -subcmp satd -mepre 1 -precmp satd +-dia_size 2 -pre_dia_size 2 -last_pred 3 -bidir_refine 2 +-mpv_flags +mv0+cbp_rd +-bf 2 -flags +cgop -sc_threshold 1000000000 -dc 10 ``` -7-Zip is required for setup. Choose the resulting directory in Settings / HCenc -folder, or put it at `tools/hcenc` beside easyDVD.exe. Developers can run the -script without `-OutputDir` to use the detected `.tools/hcenc/bin` directory. -The runtime ZIP includes the same setup script; running it without `-OutputDir` -there installs into `tools/hcenc`, which the app detects automatically. -`EASYDVD_HCENC` and CLI `-hcenc-dir` are also supported. The directory contains -`HCenc_028.exe`, `AviSynth.dll` and `ffms2.dll`; mismatched 64-bit components are -rejected. Windows may need the Microsoft Visual C++ x86 runtime used by these -upstream components. A missing HCenc setup is reported explicitly; choose -FFmpeg in Settings to use the existing encoder instead. - -FFmpeg prepares DVD-resolution frames in a lossless FFV1 intermediate, preserving -the chosen crop, aspect, cadence and interlacing. HCenc performs both VBR passes -in one invocation. Its log must confirm both passes and the full prepared frame -count. FFmpeg encodes AC-3 audio (or silence for silent sources), muxes the DVD -stream and fully decodes it before checkpointing. Temporary lossless files are -removed after each encode attempt; the space estimate includes simultaneous -lossless intermediates. HCenc's progress advances at preparation and encoding -boundaries, so the displayed percentage can remain steady during either pass. +This is MPEG-2 Main Profile at Main Level. PAL uses 720×576 at 25 fps with a +maximum 15-picture GOP; NTSC uses 720×480 at 30000/1001 fps with an 18-picture +GOP. Closed GOPs and two B pictures are retained. The display aspect is 4:3 or +16:9 according to the actual picture. Each pass gets up to eight software +encoding threads, scaled down for the configured one or two concurrent titles. + +`qmin 1` and `lmin 118` permit finer quantization when space permits. Raising +only the target bitrate left the previous profile limited by quantizer 2 on +the tested footage. Rate-distortion macroblock decisions, trellis quantization, +intra VLC coding and the motion-search settings improve the use of available +bits. Nonlinear quantization and quantizer RD search were tested but omitted +because they regressed some of the supplied film samples. + +Pass one writes statistics without audio. Pass two encodes the selected audio +track to stereo AC-3 at **448 kbps / 48 kHz**, pads short audio, and creates silence +when needed. DVD muxing uses `-f dvd -muxrate 10080k -packetsize 2048`. The +source duration limits the result; every encoded MPG is fully decoded and +hashed before it can become a reusable checkpoint. A profile version change +invalidates old encoded checkpoints when an unfinished job resumes. + +Resizing uses Lanczos and BT.601 limited-range output, with BT.709 input assumed +for HD and BT.601 for SD. PAL tags are `bt470bg`, NTSC tags `smpte170m`, with +`bt709` transfer. No denoising, sharpening or custom quantization matrix is +applied. Matching interlaced footage retains field-aware scaling, field order +and `+ildct+ilme`; other interlaced footage is deinterlaced before conversion. + +The measured improvements, costs and validation scope are recorded in +[the quality report](../validation/FFMPEG-QUALITY-2026-10-29.md). These are +measurements on particular samples, not a universal claim about every source. ## Automatic pillarbox removal For 16:9 input, easyDVD checks every decoded frame before resizing. It removes only symmetric black side borders that leave the full centered 4:3 picture. -A frame with picture content beyond the accepted border area prevents cropping. -Small variations at the 4:3 boundary are accepted by expanding the kept image to -include every observed pixel. Crop coordinates are rounded outward for chroma -alignment; the extra pixels are fitted with padding rather than stretched. -Content beyond this narrow edge margin still prevents cropping. +Small variations at the boundary expand the kept image to include every +observed pixel, rounded outward for chroma alignment. The cropped picture's +actual display aspect controls scaling and DVD aspect; rounding differences +are padded rather than stretched. Wider content or small visible marks deeper +in a border prevent cropping. Letterbox bars are retained. + The check uses per-pixel luminance with a two-level tolerance above nominal -8-bit black for compression residue, retaining 16-bit analysis precision. -Uncertain or noisier borders keep the original frame. Letterbox bars are retained. -The cropped picture's actual display aspect controls scaling and DVD aspect; -rounding differences are padded rather than stretched. The border check adds a -decoding pass for new 16:9 encodes; completed compatible checkpoints are reused. +8-bit black, retaining 16-bit analysis precision. Uncertain or noisier borders +keep the original frame. This adds a decoding pass to new 16:9 encodes; +completed compatible checkpoints are reused. -## Repeatable harness +## Repeatable benchmark -`easydvd-benchmark` normalizes a short source exactly once to a YUV4MPEG reference. -Each encoder consumes those prepared frames. The directory contains the -reference and source hashes, encoded samples, elapsed encoding times, elementary -video sizes, PSNR/SSIM measurements, logs, and a basic authoring-test ISO per -successful encoder. A missing candidate is recorded as unavailable rather than -represented by fabricated results. +`easydvd-benchmark` prepares a progressive DVD-resolution YUV4MPEG reference, +runs the production FFmpeg path, measures video size and PSNR/SSIM, and authors +a test ISO. The report records reference/source hashes, per-process wall and CPU +time, and separate timings for both MPEG-2 passes. Audio and muxing are excluded +from the reported elementary video size. Preparation, metrics and authoring +are excluded from the encode timing. ```powershell -./bin/easydvd-benchmark.exe -input C:\Scans\sample.mov -output C:\Benchmarks\trial-01 -seconds 10 -./bin/easydvd-benchmark.exe -input C:\Scans\sample.mov -output C:\Benchmarks\trial-02 -mpeg2enc C:\Tools\mpeg2enc.exe -hcenc C:\Tools\HCenc.exe -ffms2 C:\Tools\ffms2.dll +./bin/easydvd-benchmark.exe -input C:\Scans\sample.mov -output C:\Benchmarks\trial-01 -seconds 20 -repeats 3 ``` -Use `-repeats 3` for repeated runs with alternating encoder order and `-offset` -to select another scene. The report includes per-process wall/CPU time and -separates MPEG-2 passes from preparation/muxing/validation. For a complete short -source clip, `-source-pipeline -seconds 1000` includes its original decoding and -scaling costs. The normal benchmark uses the same DVD-resolution reference for -both encoders. CPU percentages are normalized to all logical processors. - -HCenc can process up to four titles concurrently under Encoding workers; -FFmpeg retains its two-worker limit. A single title uses one HCenc process, -whose CPU utilization depends on its own threading. The default remains two -workers. Raising HCenc process priority does not remove a thread-scaling limit. - -The benchmark's optional `-hcenc` / `-ffms2` paths are independent of the app's -encoder setting and require the same matching-bitness AviSynth runtime. The -harness does not switch the app's encoder automatically. - -| Candidate | Initial settings | Integration considerations | -|---|---|---| -| FFmpeg software MPEG-2 | Two-pass, 8 Mbps average, 9 Mbps peak, DVD VBV/GOP | Available alternative; implemented and tested | -| mpeg2enc | DVD preset, quality 2, 8 Mbps maximum, progressive reference | Direct Y4M input; compare actual sizes because its rate-control target differs | -| HCenc | BEST profile, two-pass, 8 Mbps average, 9 Mbps maximum | Default for new jobs; private x86 AviSynth/FFMS2 runtime | - -## Evaluation - -Use several 10–30 second clips: stable grain, strong motion, pans, fine textures, -dark footage, fades, saturated colors, and scene changes. Include 4:3 SD and HD -scans and unusual stored frame rates. Avoid denoising and sharpening. Review -decoded results against the prepared DVD-resolution reference, not the HD original. - -Compare at approximately equal file sizes as well as the initial settings. A -smaller sample with slightly lower PSNR is not automatically better, and grain -can make metric-only rankings misleading. Inspect side-by-side motion playback -and full-resolution crops. A larger encoder win must survive DVD authoring, -software navigation and physical-player playback. - -The baseline synthetic smoke measurement is in `validation/encoder-baseline.json`. -It verifies the harness; synthetic test patterns do not determine the best encoder -for 8mm/16mm scans. Full three-encoder comparison on representative scans remains -a release/research task until the optional encoders and footage are provided. - -References: [FFmpeg codecs](https://ffmpeg.org/ffmpeg-codecs.html), -[DVD targets](https://ffmpeg.org/ffmpeg.html), -[MJPEG tools](https://mjpeg.sourceforge.io/), -[HCenc manual](https://hank315.nl/files/HC_028/HC028.pdf). +Use `-offset` for another scene. For a complete short progressive source, +`-source-pipeline -seconds 1000` includes original decoding and resizing in each +timed encode. Otherwise the prepared reference is the encode input. Interlaced +sources are deinterlaced for the prepared-reference measurement; retained-field +encoding is validated separately by integration tests. Runs are sequential; +CPU percentages are normalized to all logical processors. + +Review grain, texture, dark scenes, pans and transitions in motion as well as +PSNR/SSIM. The prepared SD reference is the quality comparison, since DVD +downscaling itself discards HD detail. Software authoring and decoding checks +do not replace burned-disc tests in standalone players. + +References: [FFmpeg DVD targets](https://ffmpeg.org/ffmpeg.html#target), +[codec options](https://ffmpeg.org/ffmpeg-codecs.html), +[MPlayer/MEncoder MPEG-2 encoding guidance](https://www.mplayerhq.hu/DOCS/HTML/en/MPlayer.html). diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 7b385d2..1b7865f 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -88,10 +88,8 @@ a compatible external installation or offers an explicit private download. No system-wide installation or PATH change is required. Packaging refuses to overwrite existing output directories. Close the app before rebuilding its exe. -HCenc is the default encoder for new jobs. Its HCenc/AviSynth/FFMS2 binaries -remain separate from the runtime ZIP; the included `scripts/prepare-hcenc.ps1` -downloads the pinned private x86 runtime into `tools/hcenc`. It requires 7-Zip. -See [encoder setup](ENCODERS.md) for manual location and the FFmpeg alternative. +FFmpeg is the sole video encoder and remains external in the normal package. +See [encoding quality](ENCODERS.md) for the production profile and benchmark. The authoring toolchain is built once into a reusable local/CI cache. A valid cache is verified and reused on subsequent app builds and pushes. To rebuild the @@ -121,7 +119,7 @@ three DVD helper executables; their non-system libraries are linked into them. but is not a substitute for a clean VM. - Test burned DVD-5 and DVD-9 media in representative standalone players, including menu return, Play All and aspect-ratio switching. -- Review actual film-scan output and complete the optional encoder comparison. +- Review actual film-scan output using the production profile and benchmark. - Record the results, known limitations, tag, source archive, build information and published ZIP hashes. Code signing is optional for a preview and is not configured by this project. diff --git a/internal/app/cli.go b/internal/app/cli.go index 59dd106..9cb17c1 100644 --- a/internal/app/cli.go +++ b/internal/app/cli.go @@ -73,9 +73,7 @@ func CLI(args []string) error { ffmpegDir := fs.String("ffmpeg-dir", "", "Use FFmpeg and FFprobe from this folder for this run") downloadFFmpeg := fs.Bool("download-ffmpeg", false, "Download and remember the recommended private FFmpeg installation") resume := fs.Bool("resume", false, "Resume saved queue") - workers := fs.Int("encoders", 2, "Parallel encoders (1–4 HCenc, 1–2 FFmpeg)") - encoder := fs.String("video-encoder", defaults.Encoder(), "Video encoder: HCenc or FFmpeg") - hcencDir := fs.String("hcenc-dir", "", "HCenc folder with 32-bit AviSynth.dll and ffms2.dll") + workers := fs.Int("encoders", 2, "Parallel encoders (1–2)") if err := fs.Parse(args); err != nil { return err } @@ -125,15 +123,12 @@ func CLI(args []string) error { if *tools { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - selected := defaults - selected.VideoEncoder, selected.HCencDir = *encoder, strings.TrimSpace(*hcencDir) - statuses := append(t.Check(ctx), t.EncoderStatus(selected)) - b, _ := json.MarshalIndent(statuses, "", " ") + b, _ := json.MarshalIndent(t.Check(ctx), "", " ") fmt.Println(string(b)) if err := t.Require(); err != nil { return err } - return t.RequireEncoder(selected) + return nil } if *downloadFFmpeg && fs.NArg() == 0 && !*resume { return t.Require() @@ -154,8 +149,6 @@ func CLI(args []string) error { defaults.KeepWork = *keep defaults.NoMenu = *noMenu defaults.Encoders = *workers - defaults.VideoEncoder = *encoder - defaults.HCencDir = strings.TrimSpace(*hcencDir) defaults.TitlesPerPage = *perPage if *efficient { defaults.Packing = "Space efficiency" diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 4091e04..5e6e54f 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -76,10 +76,6 @@ func New(st *store.Store, defaults model.Settings, t media.Tools, options ...Opt } for i := range e.jobs { j := &e.jobs[i] - if !j.Locked && j.Settings.VideoEncoder == "" { - j.Settings.VideoEncoder = settings.VideoEncoder - j.Settings.HCencDir = settings.HCencDir - } if len(j.ID) != 24 || strings.Trim(j.ID, "0123456789abcdef") != "" { cancel() return nil, fmt.Errorf("invalid saved job identifier") @@ -900,17 +896,6 @@ func checkSpace(ctx context.Context, s model.Settings, videos []model.Video) err if s.StageLocally { needWork += stage * int64(s.Encoders+1) } - if s.Encoder() == "HCenc" { - // Bound concurrent lossless intermediates by raw 4:2:0 frame size, - // with headroom for the container/codec. FFV1 normally needs less. - var largest float64 - for _, v := range videos { - if v.Encoded == "" && v.Duration > largest { - largest = v.Duration - } - } - needWork += int64(largest * media.Ratio(s.FPS()) * 720 * float64(s.Height()) * 1.5 * 1.1 * float64(s.Encoders)) - } output := remaining for _, v := range videos { output += v.EncodedSize @@ -943,9 +928,6 @@ func (e *Engine) run(ctx context.Context, j model.Job) error { if err := j.Settings.Validate(); err != nil { return err } - if err := e.tools.RequireEncoder(j.Settings); err != nil { - return err - } if err := fsops.RequireLocal(ctx, j.Settings.WorkDir); err != nil { return err } diff --git a/internal/integration/issues_test.go b/internal/integration/issues_test.go index f9e3946..bc22e4c 100644 --- a/internal/integration/issues_test.go +++ b/internal/integration/issues_test.go @@ -49,7 +49,6 @@ func TestSelectedFilesSurviveRescanAndExclusion(t *testing.T) { t.Fatal(err) } s := model.DefaultSettings(dir) - s.VideoEncoder = "FFmpeg" s.Encoders = 1 st, err := store.Open(filepath.Join(dir, "queue.db")) if err != nil { @@ -118,82 +117,71 @@ func TestSingleFileAutoplayAndPillarbox(t *testing.T) { if err := process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=960x720:r=25,pad=1280:720:160:0", "-t", "2", "-c:v", "libx264", path}, process.Options{}); err != nil { t.Fatal(err) } - for _, encoder := range []string{"FFmpeg", "HCenc"} { - for _, standard := range []string{"PAL", "NTSC"} { - t.Run(encoder+"/"+standard, func(t *testing.T) { - s := model.DefaultSettings(dir) - s.VideoEncoder, s.Standard, s.NoMenu, s.KeepWork, s.Encoders = encoder, standard, true, true, 1 - if encoder == "HCenc" && tools.HCencFolder(s) == "" { - t.Skip("HCenc runtime unavailable") + for _, standard := range []string{"PAL", "NTSC"} { + t.Run(standard, func(t *testing.T) { + s := model.DefaultSettings(dir) + s.Standard, s.NoMenu, s.KeepWork, s.Encoders = standard, true, true, 1 + s.WorkDir = filepath.Join(dir, standard+" café Ω") + s.OutputDir = filepath.Join(dir, standard+" output") + st, err := store.Open(filepath.Join(s.WorkDir, "queue.db")) + if err != nil { + t.Fatal(err) + } + defer st.Close() + e, err := engine.New(st, s, tools) + if err != nil { + t.Fatal(err) + } + defer e.Close() + if err = e.Add(path); err != nil { + t.Fatal(err) + } + e.Start() + j := wait(t, e, func(s engine.Snapshot) bool { + return s.Jobs[0].State == model.Complete || s.Jobs[0].State == model.Blocked + }).Jobs[0] + if j.State != model.Complete { + t.Fatal(j.Error) + } + v := j.Videos[0] + if v.CropLeft != 160 || v.CropRight != 160 || v.Aspect() != "4:3" { + t.Fatal(v) + } + authorDir := filepath.Join(s.WorkDir, "jobs", j.ID, "generation-"+j.Generation, "disc-001") + xml, err := os.ReadFile(filepath.Join(authorDir, "dvd.xml")) + if err != nil || !strings.Contains(string(xml), "jump title 1;") || strings.Contains(string(xml), "") { + t.Fatal(string(xml), err) + } + if pages, _ := filepath.Glob(filepath.Join(authorDir, "page-*")); len(pages) != 0 { + t.Fatal("menu-free job generated menu assets", pages) + } + var out bytes.Buffer + if err = process.Run(ctx, tools.FFprobe, []string{"-v", "error", "-f", "dvdvideo", "-title", "1", "-i", j.Discs[0].ISO, "-show_streams", "-show_format", "-of", "json"}, process.Options{Stdout: &out}); err != nil { + t.Fatal(err) + } + var probe struct { + Streams []struct { + Codec string `json:"codec_name"` + DAR string `json:"display_aspect_ratio"` + Height int `json:"height"` } - s.WorkDir = filepath.Join(dir, encoder+standard+" café Ω") - s.OutputDir = filepath.Join(dir, encoder+standard+" output") - st, err := store.Open(filepath.Join(s.WorkDir, "queue.db")) - if err != nil { - t.Fatal(err) + Format struct { + Duration string `json:"duration"` } - defer st.Close() - e, err := engine.New(st, s, tools) - if err != nil { - t.Fatal(err) - } - defer e.Close() - if err = e.Add(path); err != nil { - t.Fatal(err) - } - e.Start() - j := wait(t, e, func(s engine.Snapshot) bool { - return s.Jobs[0].State == model.Complete || s.Jobs[0].State == model.Blocked - }).Jobs[0] - if j.State != model.Complete { - t.Fatal(j.Error) - } - v := j.Videos[0] - if v.CropLeft != 160 || v.CropRight != 160 || v.Aspect() != "4:3" { - t.Fatal(v) - } - authorDir := filepath.Join(s.WorkDir, "jobs", j.ID, "generation-"+j.Generation, "disc-001") - xml, err := os.ReadFile(filepath.Join(authorDir, "dvd.xml")) - if err != nil || !strings.Contains(string(xml), "jump title 1;") || strings.Contains(string(xml), "") { - t.Fatal(string(xml), err) - } - if pages, _ := filepath.Glob(filepath.Join(authorDir, "page-*")); len(pages) != 0 { - t.Fatal("menu-free job generated menu assets", pages) - } - var out bytes.Buffer - if err = process.Run(ctx, tools.FFprobe, []string{"-v", "error", "-f", "dvdvideo", "-title", "1", "-i", j.Discs[0].ISO, "-show_streams", "-show_format", "-of", "json"}, process.Options{Stdout: &out}); err != nil { - t.Fatal(err) - } - var probe struct { - Streams []struct { - Codec string `json:"codec_name"` - DAR string `json:"display_aspect_ratio"` - Height int `json:"height"` - } - Format struct { - Duration string `json:"duration"` - } - } - if err = json.Unmarshal(out.Bytes(), &probe); err != nil { - t.Fatal(err) - } - if len(probe.Streams) < 2 || probe.Streams[0].Codec != "mpeg2video" || probe.Streams[0].DAR != "4:3" || probe.Streams[0].Height != s.Height() || probe.Streams[1].Codec != "ac3" { - t.Fatal(out.String()) - } - if duration := media.Ratio(probe.Format.Duration); duration < 1.92 || duration > 2.08 { - t.Fatal("duration drift", duration) - } - if err = process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-xerror", "-f", "dvdvideo", "-title", "1", "-i", j.Discs[0].ISO, "-f", "null", "NUL"}, process.Options{}); err != nil { - t.Fatal(err) - } - if encoder == "HCenc" { - log, err := os.ReadFile(filepath.Join(filepath.Dir(v.Encoded), "hcenc.log")) - if err != nil || !strings.Contains(string(log), "encoding - pass 2") { - t.Fatal("no two-pass evidence", err) - } - } - }) - } + } + if err = json.Unmarshal(out.Bytes(), &probe); err != nil { + t.Fatal(err) + } + if len(probe.Streams) < 2 || probe.Streams[0].Codec != "mpeg2video" || probe.Streams[0].DAR != "4:3" || probe.Streams[0].Height != s.Height() || probe.Streams[1].Codec != "ac3" { + t.Fatal(out.String()) + } + if duration := media.Ratio(probe.Format.Duration); duration < 1.92 || duration > 2.08 { + t.Fatal("duration drift", duration) + } + if err = process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-xerror", "-f", "dvdvideo", "-title", "1", "-i", j.Discs[0].ISO, "-f", "null", "NUL"}, process.Options{}); err != nil { + t.Fatal(err) + } + }) } } @@ -245,50 +233,3 @@ func TestNearFourThreeBordersKeepAllContent(t *testing.T) { t.Fatal(v, err) } } - -func TestHCencFourWorkers(t *testing.T) { - tools, ctx := issueTools(t) - dir := t.TempDir() - s := model.DefaultSettings(dir) - if tools.HCencFolder(s) == "" { - t.Skip("HCenc runtime unavailable") - } - s.Encoders = 4 - source := filepath.Join(dir, "sources") - if err := os.Mkdir(source, 0755); err != nil { - t.Fatal(err) - } - first := filepath.Join(source, "1.mp4") - if err := process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=320x240:r=25", "-t", "1", "-c:v", "libx264", first}, process.Options{}); err != nil { - t.Fatal(err) - } - data, err := os.ReadFile(first) - if err != nil { - t.Fatal(err) - } - for n := 2; n <= 4; n++ { - if err := os.WriteFile(filepath.Join(source, fmt.Sprintf("%d.mp4", n)), data, 0644); err != nil { - t.Fatal(err) - } - } - st, err := store.Open(filepath.Join(dir, "queue.db")) - if err != nil { - t.Fatal(err) - } - defer st.Close() - e, err := engine.New(st, s, tools) - if err != nil { - t.Fatal(err) - } - defer e.Close() - if err = e.Add(source); err != nil { - t.Fatal(err) - } - e.Start() - j := wait(t, e, func(s engine.Snapshot) bool { - return s.Jobs[0].State == model.Complete || s.Jobs[0].State == model.Blocked - }).Jobs[0] - if j.State != model.Complete || len(j.Videos) != 4 || len(j.Discs) != 1 { - t.Fatal(j.State, j.Error) - } -} diff --git a/internal/integration/pipeline_test.go b/internal/integration/pipeline_test.go index caf0127..261a413 100644 --- a/internal/integration/pipeline_test.go +++ b/internal/integration/pipeline_test.go @@ -52,17 +52,6 @@ func wait(t *testing.T, e *engine.Engine, predicate func(engine.Snapshot) bool) } } func TestPipeline(t *testing.T) { - testPipeline(t, "FFmpeg") -} - -func TestHCencPipeline(t *testing.T) { - if os.Getenv("EASYDVD_INTEGRATION") != "1" || media.FindTools().HCencFolder(model.DefaultSettings(t.TempDir())) == "" { - t.Skip("HCenc runtime unavailable") - } - testPipeline(t, "HCenc") -} - -func testPipeline(t *testing.T, encoder string) { if os.Getenv("EASYDVD_INTEGRATION") != "1" { t.Skip("set EASYDVD_INTEGRATION=1 to run real encoders and DVD authoring") } @@ -104,7 +93,6 @@ func testPipeline(t *testing.T, encoder string) { for _, standard := range []string{"PAL", "NTSC"} { t.Run(standard, func(t *testing.T) { s := model.DefaultSettings(dir) - s.VideoEncoder = encoder s.Standard = standard s.OutputDir = filepath.Join(dir, "output-"+standard) s.WorkDir = filepath.Join(dir, "work-"+standard) @@ -241,11 +229,15 @@ func testPipeline(t *testing.T, encoder string) { } var p struct { Streams []struct { - Codec string `json:"codec_name"` - Height int `json:"height"` - Channels int `json:"channels"` - DAR string `json:"display_aspect_ratio"` - Field string `json:"field_order"` + Codec string `json:"codec_name"` + Height int `json:"height"` + Channels int `json:"channels"` + DAR string `json:"display_aspect_ratio"` + Field string `json:"field_order"` + Pixel string `json:"pix_fmt"` + Rate string `json:"r_frame_rate"` + BitRate string `json:"bit_rate"` + SampleRate string `json:"sample_rate"` } `json:"streams"` Format struct { Duration string `json:"duration"` @@ -257,6 +249,24 @@ func testPipeline(t *testing.T, encoder string) { if len(p.Streams) < 2 || p.Streams[0].Codec != "mpeg2video" || p.Streams[0].Height != s.Height() || p.Streams[1].Codec != "ac3" || p.Streams[1].Channels != 2 { t.Fatal(b.String()) } + if p.Streams[0].Pixel != "yuv420p" || media.Ratio(p.Streams[0].Rate) != media.Ratio(s.FPS()) || p.Streams[1].BitRate != "448000" || p.Streams[1].SampleRate != "48000" { + t.Fatal("DVD profile, frame rate or audio constraints violated", b.String()) + } + // dvdvideo exposes IFO properties but does not report the MPEG-2 + // sequence profile/level; inspect the encoded title itself for these. + var sequence bytes.Buffer + if err = process.Run(ctx, tools.FFprobe, []string{"-v", "error", "-select_streams", "v:0", "-show_entries", "stream=profile,level", "-of", "json", j.Videos[n-1].Encoded}, process.Options{Stdout: &sequence}); err != nil { + t.Fatal(err) + } + var seq struct { + Streams []struct { + Profile string + Level int + } + } + if err = json.Unmarshal(sequence.Bytes(), &seq); err != nil || len(seq.Streams) != 1 || seq.Streams[0].Profile != "Main" || seq.Streams[0].Level != 8 { + t.Fatal("MPEG-2 Main Profile / Main Level required", sequence.String(), err) + } if n == 3 && p.Streams[0].DAR != "16:9" { t.Fatal("widescreen lost") } diff --git a/internal/media/encode.go b/internal/media/encode.go index d7ece57..2ec46ca 100644 --- a/internal/media/encode.go +++ b/internal/media/encode.go @@ -110,7 +110,18 @@ func EncodeArgs(v model.Video, s model.Settings, input, passlog, output string, if threads > 8 { threads = 8 } - args = append(args, "-map", fmt.Sprintf("0:%d", v.VideoStream), "-vf", filter, "-c:v", "mpeg2video", "-pix_fmt", "yuv420p", "-b:v", "8000k", "-maxrate:v", "9000k", "-minrate:v", "0", "-bufsize:v", "1835008", "-g", s.GOP(), "-bf", "2", "-flags", flags, "-sc_threshold", "1000000000", "-dc", "10", "-aspect", v.Aspect(), "-threads", strconv.Itoa(threads), "-pass", strconv.Itoa(pass), "-passlogfile", passlog, "-sn", "-dn", "-progress", "pipe:1", "-nostats") + // Use the DVD target's conservative peak for the average too: packing adds + // discs instead of lowering quality. qmin AND lmin permit quantizer 1; + // raising the bitrate alone leaves easy material capped at quantizer 2. + args = append(args, "-map", fmt.Sprintf("0:%d", v.VideoStream), "-vf", filter, + "-c:v", "mpeg2video", "-profile:v", "4", "-level:v", "8", "-pix_fmt", "yuv420p", + "-b:v", "9000k", "-maxrate:v", "9000k", "-minrate:v", "0", "-bufsize:v", "1835008", + "-qmin", "1", "-lmin", "118", "-mbd", "rd", "-trellis", "1", "-intra_vlc", "1", + "-cmp", "satd", "-subcmp", "satd", "-mepre", "1", "-precmp", "satd", + "-dia_size", "2", "-pre_dia_size", "2", "-last_pred", "3", "-bidir_refine", "2", "-mpv_flags", "+mv0+cbp_rd", + "-g", s.GOP(), "-bf", "2", "-flags", flags, "-sc_threshold", "1000000000", "-dc", "10", + "-aspect", v.Aspect(), "-threads", strconv.Itoa(threads), "-pass", strconv.Itoa(pass), "-passlogfile", passlog, + "-sn", "-dn", "-progress", "pipe:1", "-nostats") if interlaced { order := "tt" if v.FieldOrder == "bb" || v.FieldOrder == "bt" { @@ -130,7 +141,7 @@ func EncodeArgs(v model.Video, s model.Settings, input, passlog, output string, if v.AudioStream < 0 { audio = "1:a:0" } - args = append(args, "-map", audio, "-c:a", "ac3", "-ar", "48000", "-ac", "2", "-b:a", "256k", "-af", "apad", "-shortest", "-t", fmt.Sprintf("%.6f", v.Duration), "-f", "dvd", "-muxrate", "10080k", "-packetsize", "2048", output) + args = append(args, "-map", audio, "-c:a", "ac3", "-ar", "48000", "-ac", "2", "-b:a", "448k", "-af", "apad", "-shortest", "-t", fmt.Sprintf("%.6f", v.Duration), "-f", "dvd", "-muxrate", "10080k", "-packetsize", "2048", output) } return args } @@ -151,28 +162,22 @@ func (t Tools) Encode(ctx context.Context, v model.Video, s model.Settings, inpu if runtime.GOOS == "windows" { null = "NUL" } - if s.Encoder() == "HCenc" { - if err := t.encodeHCenc(ctx, v, s, input, dir, log, progress); err != nil { - return v, err + for pass := 1; pass <= 2; pass++ { + out := null + if pass == 2 { + out = part } - } else { - for pass := 1; pass <= 2; pass++ { - out := null - if pass == 2 { - out = part - } - p := pass - err := process.Run(ctx, t.FFmpeg, EncodeArgs(v, s, input, passlog, out, pass), process.Options{Dir: dir, Log: log, Line: func(line string) { - if strings.HasPrefix(line, "out_time_us=") { - us, _ := strconv.ParseFloat(strings.TrimPrefix(line, "out_time_us="), 64) - if progress != nil { - progress(math.Min(1, (float64(p-1)+us/1e6/v.Duration)/2)) - } + p := pass + err := process.Run(ctx, t.FFmpeg, EncodeArgs(v, s, input, passlog, out, pass), process.Options{Dir: dir, Log: log, Line: func(line string) { + if strings.HasPrefix(line, "out_time_us=") { + us, _ := strconv.ParseFloat(strings.TrimPrefix(line, "out_time_us="), 64) + if progress != nil { + progress(math.Min(1, (float64(p-1)+us/1e6/v.Duration)/2)) } - }}) - if err != nil { - return v, err } + }}) + if err != nil { + return v, err } } // A complete decode catches truncated streams before they become reusable checkpoints. diff --git a/internal/media/encode_test.go b/internal/media/encode_test.go index d1472da..d2725eb 100644 --- a/internal/media/encode_test.go +++ b/internal/media/encode_test.go @@ -36,7 +36,7 @@ func TestAudioAndDVDArgs(t *testing.T) { s := model.DefaultSettings(t.TempDir()) v := model.Video{DAR: 4.0 / 3, Width: 720, Height: 576, Duration: 10, VideoStream: 2, AudioStream: -1} args := strings.Join(EncodeArgs(v, s, "source", "pass", "video.mpg", 2), " ") - for _, want := range []string{"-pass 2", "-map 0:2", "anullsrc", "-map 1:a:0", "-af apad", "-b:v 8000k", "-maxrate:v 9000k", "-b:a 256k", "-f dvd", "-g 15"} { + for _, want := range []string{"-pass 2", "-map 0:2", "anullsrc", "-map 1:a:0", "-af apad", "-b:v 9000k", "-maxrate:v 9000k", "-b:a 448k", "-f dvd", "-g 15"} { if !strings.Contains(args, want) { t.Fatal(want, args) } diff --git a/internal/media/ffmpeg.go b/internal/media/ffmpeg.go index fb4b743..66aed35 100644 --- a/internal/media/ffmpeg.go +++ b/internal/media/ffmpeg.go @@ -76,7 +76,7 @@ func validateFFmpeg(ctx context.Context, pair FFmpegPair, run commandOutput) (FF checks := []struct { arg string names []string - }{{"-encoders", []string{"mpeg2video", "ac3", "mjpeg", "ffv1"}}, {"-decoders", []string{"mpeg2video", "ac3", "png"}}, {"-filters", []string{"scale", "pad", "setsar", "fps", "bwdif", "apad", "anullsrc", "crop", "bbox", "format"}}, {"-muxers", []string{"dvd", "null", "image2", "matroska"}}} + }{{"-encoders", []string{"mpeg2video", "ac3", "mjpeg"}}, {"-decoders", []string{"mpeg2video", "ac3", "png"}}, {"-filters", []string{"scale", "pad", "setsar", "fps", "bwdif", "apad", "anullsrc", "crop", "bbox", "format"}}, {"-muxers", []string{"dvd", "null", "image2"}}} for _, check := range checks { out, e := run(ctx, pair.FFmpeg, []string{"-hide_banner", check.arg}) if e != nil { diff --git a/internal/media/ffmpeg_test.go b/internal/media/ffmpeg_test.go index 91699b6..3397607 100644 --- a/internal/media/ffmpeg_test.go +++ b/internal/media/ffmpeg_test.go @@ -21,7 +21,7 @@ func fakeCapabilities(ff, probe, missing string) commandOutput { } return "ffmpeg version " + ff + "-build\n", nil case "-encoders": - return " V.S..D mpeg2video MPEG-2\n A....D ac3 AC3\n V....D mjpeg MJPEG\n V....D ffv1 FFV1\n", nil + return " V.S..D mpeg2video MPEG-2\n A....D ac3 AC3\n V....D mjpeg MJPEG\n", nil case "-decoders": return " V..... mpeg2video MPEG-2\n A..... ac3 AC3\n V..... png PNG\n", nil case "-filters": @@ -34,7 +34,7 @@ func fakeCapabilities(ff, probe, missing string) commandOutput { } return out, nil case "-muxers": - return " E dvd DVD\n E null NULL\n E image2 images\n E matroska Matroska\n", nil + return " E dvd DVD\n E null NULL\n E image2 images\n", nil } return "", fmt.Errorf("unexpected command") } diff --git a/internal/media/hcenc.go b/internal/media/hcenc.go deleted file mode 100644 index ba8ab65..0000000 --- a/internal/media/hcenc.go +++ /dev/null @@ -1,213 +0,0 @@ -package media - -import ( - "context" - "debug/pe" - "easydvd/internal/model" - "easydvd/internal/platform" - "easydvd/internal/process" - "fmt" - "io" - "math" - "os" - "path/filepath" - "regexp" - "strconv" - "strings" -) - -func (t Tools) HCencFolder(s model.Settings) string { - if s.HCencDir != "" { - return s.HCencDir - } - if folder := os.Getenv("EASYDVD_HCENC"); folder != "" { - if absolute, err := filepath.Abs(folder); err == nil { - return absolute - } - return folder - } - exe, _ := os.Executable() - cwd, _ := os.Getwd() - for _, folder := range []string{filepath.Join(filepath.Dir(exe), "tools", "hcenc"), filepath.Join(cwd, ".tools", "hcenc", "bin")} { - if _, err := os.Stat(filepath.Join(folder, "HCenc_028.exe")); err == nil { - return folder - } - } - return "" -} - -func (t Tools) RequireEncoder(s model.Settings) error { - if s.Encoder() != "HCenc" { - return nil - } - folder := t.HCencFolder(s) - if folder == "" { - return fmt.Errorf("HCenc setup required: choose the HCenc folder in Settings (HCenc_028.exe, 32-bit AviSynth.dll and ffms2.dll), set EASYDVD_HCENC, or select FFmpeg as video encoder") - } - for _, name := range []string{"HCenc_028.exe", "AviSynth.dll", "ffms2.dll"} { - file, err := pe.Open(filepath.Join(folder, name)) - if err != nil { - return fmt.Errorf("HCenc setup: %s: %w", name, err) - } - machine := file.Machine - file.Close() - if machine != pe.IMAGE_FILE_MACHINE_I386 { - return fmt.Errorf("HCenc setup: %s must be 32-bit (x86)", name) - } - } - return nil -} - -func (t Tools) EncoderStatus(s model.Settings) ToolStatus { - status := ToolStatus{Name: "Video encoder", Version: s.Encoder() + " · two-pass MPEG-2"} - if s.Encoder() == "HCenc" { - status.Path = t.HCencFolder(s) - if err := t.RequireEncoder(s); err != nil { - status.Error = err.Error() - } - } else { - status.Path = t.FFmpeg - } - return status -} - -// HCenc performs both VBR passes in one invocation. No one-pass/CQ directives -// may be added here. FFmpeg only prepares lossless frames and encodes audio. -func HCencINI(v model.Video, s model.Settings) string { - _, interlaced := VideoFilter(v, s) - mode := "*PROGRESSIVE\n*PROG_SEQ\n" - if interlaced { - mode = "*INTERLACED\n*TFF\n" - if v.FieldOrder == "bb" || v.FieldOrder == "bt" { - mode = "*INTERLACED\n*BFF\n" - } - } - colour := 5 - if s.Standard == "NTSC" { - colour = 6 - } - return fmt.Sprintf("*INFILE source.avs\n*OUTFILE video.m2v\n*LOGFILE hcenc.log\n*BITRATE 8000\n*MAXBITRATE 9000\n*PROFILE BEST\n*ASPECT %s\n*AUTOGOP %s\n*CLOSEDGOPS\n*DC_PREC 10\n*CHROMAFORMAT 420\n*COLOUR %d\n%s*SILENT\n*WAIT 0\n", v.Aspect(), s.GOP(), colour, mode) -} - -func (t Tools) encodeHCenc(ctx context.Context, v model.Video, s model.Settings, input, dir string, log io.Writer, progress func(float64)) error { - if err := t.RequireEncoder(s); err != nil { - return err - } - // Use ASCII relative names in the legacy encoder's script and INI. Go and - // FFmpeg still handle Unicode source/work paths through Windows' Unicode APIs. - frames := filepath.Join(dir, "frames.mkv") - plugin := filepath.Join(dir, "ffms2.dll") - for _, name := range []string{"video.m2v", "hcenc.log"} { - if err := os.Remove(filepath.Join(dir, name)); err != nil && !os.IsNotExist(err) { - return err - } - } - defer os.Remove(frames) - defer os.Remove(plugin) - defer os.Remove(filepath.Join(dir, "video.m2v")) - sourcePlugin, err := os.Open(filepath.Join(t.HCencFolder(s), "ffms2.dll")) - if err != nil { - return err - } - destPlugin, err := os.Create(plugin) - if err != nil { - sourcePlugin.Close() - return err - } - _, copyErr := io.Copy(destPlugin, sourcePlugin) - sourcePlugin.Close() - closeErr := destPlugin.Close() - if copyErr != nil { - return copyErr - } - if closeErr != nil { - return closeErr - } - filter, interlaced := VideoFilter(v, s) - preparedFrames := 0 - args := []string{"-hide_banner", "-nostdin", "-y", "-xerror", "-err_detect", "explode", "-i", input, "-map", fmt.Sprintf("0:%d", v.VideoStream), "-vf", filter, "-an", "-sn", "-dn", "-c:v", "ffv1", "-level", "3", "-pix_fmt", "yuv420p", "-progress", "pipe:1", "-nostats", frames} - if err = process.Run(ctx, t.FFmpeg, args, process.Options{Log: log, Line: func(line string) { - if strings.HasPrefix(line, "frame=") { - preparedFrames, _ = strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(line, "frame="))) - } - if progress != nil && strings.HasPrefix(line, "out_time_us=") { - var us float64 - fmt.Sscanf(line, "out_time_us=%f", &us) - progress(math.Min(.25, .25*us/1e6/v.Duration)) - } - }}); err != nil { - return err - } - script := "LoadPlugin(\"ffms2.dll\")\nFFVideoSource(\"frames.mkv\", cache=false)\n" - if interlaced { - if v.FieldOrder == "bb" || v.FieldOrder == "bt" { - script += "AssumeBFF()\n" - } else { - script += "AssumeTFF()\n" - } - } else { - script += "AssumeFrameBased()\n" - } - if err = os.WriteFile(filepath.Join(dir, "source.avs"), []byte(script), 0644); err != nil { - return err - } - if err = os.WriteFile(filepath.Join(dir, "HC.ini"), []byte(HCencINI(v, s)), 0644); err != nil { - return err - } - if progress != nil { - progress(.25) - } - toolDir, cleanup, err := platform.LegacyWorkingDir(dir) - if err != nil { - return err - } - defer cleanup() - err = process.Run(ctx, filepath.Join(t.HCencFolder(s), "HCenc_028.exe"), []string{"-ini", "HC.ini"}, process.Options{Dir: toolDir, Log: log, Stdout: log}) - // HCenc can return success after an input/configuration error. Require its - // elementary stream as well as successful decode/metadata validation below. - hcLog, _ := os.ReadFile(filepath.Join(dir, "hcenc.log")) - if log != nil { - _, _ = log.Write(hcLog) - } - if err != nil { - return fmt.Errorf("HCenc: %w", err) - } - if err = validateHCencLog(string(hcLog), preparedFrames); err != nil { - return err - } - video := filepath.Join(dir, "video.m2v") - if st, e := os.Stat(video); e != nil || st.Size() == 0 { - return fmt.Errorf("HCenc produced no video; check the 32-bit AviSynth runtime and FFMS2 plugin: %s", hcLog) - } - if progress != nil { - progress(.85) - } - args = []string{"-hide_banner", "-nostdin", "-y", "-xerror", "-i", video, "-i", input} - audio := fmt.Sprintf("1:%d", v.AudioStream) - if v.AudioStream < 0 { - args = append(args, "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo") - audio = "2:a:0" - } - args = append(args, "-map", "0:v:0", "-map", audio, "-c:v", "copy", "-c:a", "ac3", "-ar", "48000", "-ac", "2", "-b:a", "256k", "-af", "apad", "-shortest", "-t", fmt.Sprintf("%.6f", v.Duration), "-f", "dvd", "-muxrate", "10080k", "-packetsize", "2048", filepath.Join(dir, "video.part.mpg")) - if err = process.Run(ctx, t.FFmpeg, args, process.Options{Log: log}); err != nil { - return err - } - if progress != nil { - progress(1) - } - return nil -} - -var hcFrameCount = regexp.MustCompile(`(?m)^nr\. of frames:\s+(\d+)\s*$`) - -func validateHCencLog(log string, preparedFrames int) error { - frames := hcFrameCount.FindStringSubmatch(log) - count := 0 - if len(frames) > 1 { - count, _ = strconv.Atoi(frames[1]) - } - if preparedFrames <= 0 || count != preparedFrames || !strings.Contains(log, "encoding - pass 1") || !strings.Contains(log, "encoding - pass 2") { - return fmt.Errorf("HCenc did not complete both passes for all %d prepared frames; inspect the job log", preparedFrames) - } - return nil -} diff --git a/internal/media/hcenc_test.go b/internal/media/hcenc_test.go deleted file mode 100644 index fbf2dc8..0000000 --- a/internal/media/hcenc_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package media - -import ( - "easydvd/internal/model" - "strings" - "testing" -) - -func TestHCencDVDSettings(t *testing.T) { - s := model.DefaultSettings(t.TempDir()) - v := model.Video{DAR: 16.0 / 9, FPS: 25, FieldOrder: "bb"} - ini := HCencINI(v, s) - for _, want := range []string{"*PROFILE BEST", "*BITRATE 8000", "*MAXBITRATE 9000", "*AUTOGOP 15", "*CLOSEDGOPS", "*ASPECT 16:9", "*INTERLACED\n*BFF", "*COLOUR 5", "*SILENT", "*WAIT 0"} { - if !strings.Contains(ini, want) { - t.Fatal(want, ini) - } - } - s.Standard = "NTSC" - ini = HCencINI(v, s) - if !strings.Contains(ini, "*AUTOGOP 18") || !strings.Contains(ini, "*PROGRESSIVE\n*PROG_SEQ") || strings.Contains(ini, "*INTERLACED") || !strings.Contains(ini, "*COLOUR 6") { - t.Fatal(ini) - } - for _, forbidden := range []string{"*CQ", "*1PASS", "*LOSSLESS"} { - if strings.Contains(ini, forbidden) { - t.Fatal(ini) - } - } -} - -func TestHCencMustCompleteBothPassesAndEveryFrame(t *testing.T) { - valid := "encoding - pass 1\nencoding - pass 2\nnr. of frames: 50\r\n" - if err := validateHCencLog(valid, 50); err != nil { - t.Fatal(err) - } - for _, log := range []string{"", strings.ReplaceAll(valid, "pass 2", "pass failed"), strings.ReplaceAll(valid, "50", "49")} { - if err := validateHCencLog(log, 50); err == nil { - t.Fatal("incomplete encode was accepted", log) - } - } - s := model.DefaultSettings(t.TempDir()) - if s.Encoder() != "HCenc" { - t.Fatal("new jobs must default to HCenc") - } - key := s.EncodingKey() - s.VideoEncoder = "FFmpeg" - if s.EncodingKey() == key { - t.Fatal("encoder changes must invalidate cache") - } - s.VideoEncoder = "" - if s.Encoder() != "FFmpeg" || s.EncodingKey() != model.Hash("mpeg2-v2-8000-9000-ac3-256-2pass-PAL") { - t.Fatal("legacy jobs lost their encoding profile") - } -} diff --git a/internal/model/model.go b/internal/model/model.go index c179648..8e9452b 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -4,6 +4,7 @@ import ( "crypto/rand" "crypto/sha256" "encoding/hex" + "encoding/json" "fmt" "path/filepath" "strings" @@ -30,8 +31,6 @@ type Settings struct { TitlesPerPage int `json:"titles_per_page"` StageLocally bool `json:"stage_locally"` Encoders int `json:"encoders"` - VideoEncoder string `json:"video_encoder,omitempty"` - HCencDir string `json:"hcenc_dir,omitempty"` OutputDir string `json:"output_dir"` WorkDir string `json:"work_dir"` Theme string `json:"theme"` @@ -41,16 +40,26 @@ type Settings struct { } func DefaultSettings(base string) Settings { - return Settings{Standard: "PAL", Media: "DVD-5", Packing: "Strict order", Layout: "Text", TitlesPerPage: 10, StageLocally: true, Encoders: 2, VideoEncoder: "HCenc", OutputDir: filepath.Join(base, "easyDVD Output"), WorkDir: filepath.Join(base, "easyDVD Work"), Theme: "System", Menu: DefaultMenuStyle()} + return Settings{Standard: "PAL", Media: "DVD-5", Packing: "Strict order", Layout: "Text", TitlesPerPage: 10, StageLocally: true, Encoders: 2, OutputDir: filepath.Join(base, "easyDVD Output"), WorkDir: filepath.Join(base, "easyDVD Work"), Theme: "System", Menu: DefaultMenuStyle()} } -func (s Settings) Validate() error { - if s.Encoder() != "HCenc" && s.Encoder() != "FFmpeg" { - return fmt.Errorf("choose HCenc or FFmpeg as video encoder") +// Read old preview queues without retaining the removed backend configuration. +func (s *Settings) UnmarshalJSON(data []byte) error { + type settings Settings + legacy := struct { + *settings + VideoEncoder string `json:"video_encoder"` + }{settings: (*settings)(s)} + if err := json.Unmarshal(data, &legacy); err != nil { + return err } - if s.HCencDir != "" && !filepath.IsAbs(s.HCencDir) { - return fmt.Errorf("HCenc folder must be an absolute path") + if legacy.VideoEncoder == "HCenc" && s.Encoders > 2 { + s.Encoders = 2 } + return nil +} + +func (s Settings) Validate() error { if s.Standard != "PAL" && s.Standard != "NTSC" { return fmt.Errorf("choose PAL or NTSC") } @@ -70,8 +79,8 @@ func (s Settings) Validate() error { if s.TitlesPerPage < 1 || s.TitlesPerPage > max { return fmt.Errorf("titles per page must be 1–%d for this layout", max) } - if s.Encoders < 1 || s.Encoders > s.MaxEncoders() { - return fmt.Errorf("use 1–%d encoding workers with %s", s.MaxEncoders(), s.Encoder()) + if s.Encoders < 1 || s.Encoders > 2 { + return fmt.Errorf("use one or two encoding workers") } if !filepath.IsAbs(s.OutputDir) || !filepath.IsAbs(s.WorkDir) { return fmt.Errorf("output and work folders must be absolute paths") @@ -110,25 +119,7 @@ func (s Settings) GOP() string { // Only settings affecting an encoded title belong here. Menu edits and packing do not re-encode. func (s Settings) EncodingKey() string { - if s.VideoEncoder == "" { - return Hash("mpeg2-v2-8000-9000-ac3-256-2pass-" + s.Standard) - } - return Hash("mpeg2-v4-pillarbox-bounds-8000-9000-ac3-256-2pass-" + s.Encoder() + "-" + s.Standard) -} - -// Empty identifies queues saved before encoder selection existed. -func (s Settings) Encoder() string { - if s.VideoEncoder == "" { - return "FFmpeg" - } - return s.VideoEncoder -} - -func (s Settings) MaxEncoders() int { - if s.Encoder() == "HCenc" { - return 4 - } - return 2 + return Hash("mpeg2-v5-quality-ceiling-ac3-448-2pass-" + s.Standard) } func (v Video) ArtifactKey(s Settings) string { @@ -181,7 +172,7 @@ func (v Video) OriginalLabel() string { } func (v Video) Fingerprint() string { return Hash(fmt.Sprintf("%s:%d:%d", v.Path, v.Size, v.ModTime)) } -func (v Video) EstimatedBytes() int64 { return int64(v.Duration * 8256000 / 8 * 1.035) } +func (v Video) EstimatedBytes() int64 { return int64(v.Duration * 9448000 / 8 * 1.035) } func (v Video) Aspect() string { if v.ContentDAR() >= 1.55 { return "16:9" diff --git a/internal/model/model_test.go b/internal/model/model_test.go index 2adf286..625df99 100644 --- a/internal/model/model_test.go +++ b/internal/model/model_test.go @@ -1,7 +1,9 @@ package model import ( + "encoding/json" "path/filepath" + "strings" "testing" ) @@ -15,6 +17,26 @@ func TestSnapshotIsIndependent(t *testing.T) { } } +func TestRemovedBackendPreferencesMigrate(t *testing.T) { + s := DefaultSettings(t.TempDir()) + if err := json.Unmarshal([]byte(`{"video_encoder":"HCenc","hcenc_dir":"old location","encoders":4,"standard":"NTSC"}`), &s); err != nil { + t.Fatal(err) + } + if s.Encoders != 2 || s.Standard != "NTSC" { + t.Fatal(s) + } + if err := s.Validate(); err != nil { + t.Fatal(err) + } + data, err := json.Marshal(s) + if err != nil || strings.Contains(string(data), "hcenc") || strings.Contains(string(data), "video_encoder") { + t.Fatal(string(data), err) + } + if s.EncodingKey() == Hash("mpeg2-v4-pillarbox-bounds-8000-9000-ac3-256-2pass-FFmpeg-NTSC") { + t.Fatal("old encoding quality checkpoint was accepted") + } +} + func TestOriginalVideoLabel(t *testing.T) { v := Video{Path: filepath.Join("clips", "Family.trip.1999.mp4"), Label: "Renamed title"} if v.OriginalLabel() != "Family.trip.1999" { @@ -46,19 +68,3 @@ func TestEncodingKeyAndSettings(t *testing.T) { t.Fatal("illegal menu density accepted") } } - -func TestWorkerLimitsFollowEncoder(t *testing.T) { - s := DefaultSettings(t.TempDir()) - s.Encoders = 4 - if err := s.Validate(); err != nil { - t.Fatal(err) - } - s.VideoEncoder = "FFmpeg" - if err := s.Validate(); err == nil { - t.Fatal("four FFmpeg workers should not be allowed") - } - s.Encoders = 2 - if err := s.Validate(); err != nil { - t.Fatal(err) - } -} diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 1b95422..22ef8e1 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -424,28 +424,8 @@ func (u *window) settingsDialog(id string, s model.Settings) { if !s.NoMenu && (id == "" || u.selectedJob() == nil || len(u.selectedJob().ActiveVideos()) != 1) { noMenu.Disable() } - workerOptions := []string{"1", "2"} - if s.Encoder() == "HCenc" { - workerOptions = append(workerOptions, "3", "4") - } - workers := widget.NewSelect(workerOptions, nil) + workers := widget.NewSelect([]string{"1", "2"}, nil) workers.SetSelected(strconv.Itoa(s.Encoders)) - encoder := widget.NewSelect([]string{"HCenc", "FFmpeg"}, nil) - encoder.SetSelected(s.Encoder()) - encoder.OnChanged = func(value string) { - count, _ := strconv.Atoi(workers.Selected) - options := []string{"1", "2"} - if value == "HCenc" { - options = append(options, "3", "4") - } else if count > 2 { - count = 2 - } - workers.SetOptions(options) - workers.SetSelected(strconv.Itoa(max(1, count))) - } - hcencFolder := widget.NewEntry() - hcencFolder.SetText(s.HCencDir) - hcencFolder.SetPlaceHolder("Choose the HCenc installation folder, or leave blank for automatic detection") output := widget.NewEntry() output.SetText(s.OutputDir) work := widget.NewEntry() @@ -466,13 +446,11 @@ func (u *window) settingsDialog(id string, s model.Settings) { appearance.SetSelected(s.Theme) form := widget.NewForm(widget.NewFormItem("TV standard", standard), widget.NewFormItem("Disc capacity", medium), widget.NewFormItem("File allocation", packingMode), widget.NewFormItem("Menu layout", menuLayout), widget.NewFormItem("Titles per page", perPage), widget.NewFormItem("Encoding workers", workers), widget.NewFormItem("Output folder", folder(output)), widget.NewFormItem("Local work folder", folder(work)), widget.NewFormItem("Appearance", appearance)) form.Append("Playback", noMenu) - form.Append("Video encoder", encoder) - form.Append("HCenc folder", folder(hcencFolder)) note := "Applies to new and pending jobs. Started jobs retain their settings." if id != "" { note = "Settings for this folder. Locked when processing starts." } - heading := widget.NewLabel(note + "\nQuality: two-pass MPEG-2, 8 Mbps average / 9 Mbps peak.") + heading := widget.NewLabel(note + "\nQuality: two-pass MPEG-2, 9 Mbps target / peak, AC-3 448 kbps.") heading.Wrapping = fyne.TextWrapWord var d dialog.Dialog save := func() { @@ -488,8 +466,6 @@ func (u *window) settingsDialog(id string, s model.Settings) { next.Layout = menuLayout.Selected next.TitlesPerPage = n next.Encoders, _ = strconv.Atoi(workers.Selected) - next.VideoEncoder = encoder.Selected - next.HCencDir = strings.TrimSpace(hcencFolder.Text) next.StageLocally = stage.Checked next.KeepWork = keep.Checked next.NoMenu = noMenu.Checked @@ -548,7 +524,6 @@ func (u *window) diagnostics() { defer cancel() tools := u.engine.Tools() statuses := tools.Check(ctx) - statuses = append(statuses, tools.EncoderStatus(u.engine.Snapshot().Settings)) var text strings.Builder for _, s := range statuses { fmt.Fprintf(&text, "%s\n%s\n%s\n", s.Name, s.Path, s.Version) diff --git a/scripts/package.ps1 b/scripts/package.ps1 index 024e609..bc8d182 100644 --- a/scripts/package.ps1 +++ b/scripts/package.ps1 @@ -36,8 +36,6 @@ foreach ($file in $documentation) { Copy-Item -LiteralPath (Join-Path $ProjectRoot $file) -Destination $target } Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'tools.lock.json') -Destination $bundle -New-Item -ItemType Directory -Force -Path (Join-Path $bundle 'scripts') | Out-Null -Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'prepare-hcenc.ps1') -Destination (Join-Path $bundle 'scripts') $Version | Set-Content -LiteralPath (Join-Path $bundle 'VERSION') -Encoding utf8 @{version=$Version; repository=(Get-Content -LiteralPath (Join-Path $ProjectRoot 'RELEASE_REPOSITORY') -Raw).Trim(); publicRelease=[bool]$PublicRelease; offline=[bool]$IncludeFFmpeg; authoringToolchain=$ToolLock.authoring.id; commit=(& git -C $ProjectRoot rev-parse --verify HEAD 2>$null)} | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $bundle 'release.json') -Encoding utf8 Use-DevTools diff --git a/scripts/prepare-hcenc.ps1 b/scripts/prepare-hcenc.ps1 deleted file mode 100644 index 403d83b..0000000 --- a/scripts/prepare-hcenc.ps1 +++ /dev/null @@ -1,44 +0,0 @@ -param([string]$OutputDir, [string]$CacheDir, [string]$SevenZip) -$ErrorActionPreference = 'Stop' -$setupRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) -if (-not $OutputDir) { - $OutputDir = if (Test-Path -LiteralPath (Join-Path $setupRoot 'go.mod')) { Join-Path $setupRoot '.tools/hcenc/bin' } else { Join-Path $setupRoot 'tools/hcenc' } -} -if (-not $CacheDir) { $CacheDir = Join-Path ([IO.Path]::GetTempPath()) 'easyDVD-hcenc-setup' } -$OutputDir = [IO.Path]::GetFullPath($OutputDir) -$CacheDir = [IO.Path]::GetFullPath($CacheDir) -if (-not $SevenZip) { - $found = Get-Command 7z.exe -ErrorAction SilentlyContinue - if ($found) { $SevenZip = $found.Source } - elseif (Test-Path -LiteralPath 'C:/Program Files/7-Zip/7z.exe') { $SevenZip = 'C:/Program Files/7-Zip/7z.exe' } - else { throw 'Install 7-Zip or pass -SevenZip with the path to 7z.exe.' } -} -New-Item -ItemType Directory -Force -Path $CacheDir,$OutputDir | Out-Null -$packages = @( - @{name='hcenc'; url='http://hank315.nl/files/HC_028/HC028_21-12-2015.zip'; sha256='ed392df990120cd5430454bec68555dd444f1193f930e021c42b1871f5e245a7'}, - @{name='avisynth'; url='https://github.com/AviSynth/AviSynthPlus/releases/download/v3.7.5/AviSynthPlus_3.7.5_20250420-filesonly.7z'; sha256='4db18a1b3787b46ed99e810fa41cdc238f7f6ac82ffa6ed84d53fa8cefb5146f'}, - @{name='ffms2'; url='https://github.com/FFMS/ffms2/releases/download/2.40/ffms2-2.40-msvc.7z'; sha256='0da7454faaab87fc1515d72ffc2edeaee0e6090fa2f27a8986bdebed06197457'} -) -foreach ($package in $packages) { - $archive = Join-Path $CacheDir ($package.name + [IO.Path]::GetExtension($package.url)) - if (-not (Test-Path -LiteralPath $archive) -or (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLowerInvariant() -ne $package.sha256) { - & curl.exe --fail --location --retry 2 --silent --show-error $package.url --output $archive - if ($LASTEXITCODE -ne 0) { throw "Download failed: $($package.name)" } - } - if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLowerInvariant() -ne $package.sha256) { throw "Checksum mismatch: $archive" } - & $SevenZip x $archive "-o$CacheDir/$($package.name)" -y | Out-Null - if ($LASTEXITCODE -ne 0) { throw "Extraction failed: $($package.name)" } -} -$files = @( - @{source='hcenc/HC028_21-12-2015/HCenc_028.exe'; target='HCenc_028.exe'}, - @{source='hcenc/HC028_21-12-2015/misc/HC028.pdf'; target='HC028.pdf'}, - @{source='avisynth/AviSynthPlus_3.7.5_20250420-filesonly/x86/AviSynth.dll'; target='AviSynth.dll'}, - @{source='avisynth/AviSynthPlus_3.7.5_20250420-filesonly/gpl.txt'; target='AviSynth-GPL.txt'}, - @{source='avisynth/AviSynthPlus_3.7.5_20250420-filesonly/lgpl_for_used_libs.txt'; target='AviSynth-LGPL.txt'}, - @{source='ffms2/ffms2-2.40-msvc/x86/ffms2.dll'; target='ffms2.dll'}, - @{source='ffms2/ffms2-2.40-msvc/COPYING'; target='FFMS2-COPYING.txt'} -) -foreach ($file in $files) { Copy-Item -LiteralPath (Join-Path $CacheDir $file.source) -Destination (Join-Path $OutputDir $file.target) -Force } -$packages | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $OutputDir 'downloads.json') -Encoding UTF8 -Write-Host "HCenc runtime ready: $OutputDir" -Write-Host 'Choose this folder in Settings / HCenc folder, or pass -hcenc-dir to the CLI.' diff --git a/validation/ENCODER-PERFORMANCE-2026-10-29.md b/validation/ENCODER-PERFORMANCE-2026-10-29.md index c43046e..3a20e53 100644 --- a/validation/ENCODER-PERFORMANCE-2026-10-29.md +++ b/validation/ENCODER-PERFORMANCE-2026-10-29.md @@ -1,5 +1,9 @@ # Encoder performance and pillarbox follow-up — 2026-10-29 +Historical comparison: the final application uses FFmpeg alone with a revised +quality profile. See [the subsequent quality report](FFMPEG-QUALITY-2026-10-29.md). +The measurements below describe the earlier profiles and remain unchanged. + Measured on an AMD Ryzen 7 9800X3D (8 cores / 16 logical processors), Windows, FFmpeg 9.0.2 and HCenc 0.28.0.2 BEST. Inputs came from a read-only real film-scan fixture: H.264, 1280×720, 18 fps, with baked-in black side borders. All benchmark diff --git a/validation/FFMPEG-QUALITY-2026-10-29.json b/validation/FFMPEG-QUALITY-2026-10-29.json new file mode 100644 index 0000000..ffd3206 --- /dev/null +++ b/validation/FFMPEG-QUALITY-2026-10-29.json @@ -0,0 +1,1486 @@ +{ + "date": "2026-10-29", + "host": "Windows; AMD Ryzen 7 9800X3D; 8 cores / 16 logical processors", + "ffmpeg": "9.0.2", + "standard": "PAL 720x576 25 fps 4:3", + "method": "20-second prepared progressive DVD-resolution references. Two movement/grain scenes from one H.264 film scan; a third scene from a separate ProRes film scan. Two passes, eight threads, sequential candidates. Decode-to-reference PSNR and SSIM. Times exclude preparation, quality metrics and authoring.", + "common_options": [ + "-c:v", + "mpeg2video", + "-pix_fmt", + "yuv420p", + "-maxrate:v", + "9000k", + "-minrate:v", + "0", + "-bufsize:v", + "1835008", + "-g", + "15", + "-bf", + "2", + "-flags", + "+cgop", + "-sc_threshold", + "1000000000", + "-dc", + "10", + "-aspect", + "4:3", + "-threads", + "8" + ], + "sweep": [ + { + "scene": "movement", + "profile": "baseline8", + "options": [ + "-b:v", + "8000k" + ], + "seconds": 0.4086569999999483, + "failed": false, + "bytes": 16841715, + "mbps": 6.736686, + "vbv_diagnostics": [], + "ssim": 0.973753, + "psnr": 43.899443, + "experiment": "sweep" + }, + { + "scene": "movement", + "profile": "ceiling9", + "options": [ + "-b:v", + "9000k" + ], + "seconds": 0.4008747000043513, + "failed": false, + "bytes": 16841715, + "mbps": 6.736686, + "vbv_diagnostics": [], + "ssim": 0.973753, + "psnr": 43.899443, + "experiment": "sweep" + }, + { + "scene": "movement", + "profile": "ceiling9-q1", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118" + ], + "seconds": 0.4426967000035802, + "failed": false, + "bytes": 22587264, + "mbps": 9.0349056, + "vbv_diagnostics": [], + "ssim": 0.976269, + "psnr": 44.330802, + "experiment": "sweep" + }, + { + "scene": "movement", + "profile": "rd-trellis", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1" + ], + "seconds": 2.798550100000284, + "failed": false, + "bytes": 22350665, + "mbps": 8.940266, + "vbv_diagnostics": [], + "ssim": 0.979, + "psnr": 44.946209, + "experiment": "sweep" + }, + { + "scene": "movement", + "profile": "rd-search", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-precmp", + "satd", + "-dia_size", + "2", + "-pre_dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd+qp_rd" + ], + "seconds": 4.658328600002278, + "failed": false, + "bytes": 19081348, + "mbps": 7.6325392, + "vbv_diagnostics": [], + "ssim": 0.978102, + "psnr": 44.771391, + "experiment": "sweep" + }, + { + "scene": "movement", + "profile": "rd-nonlinear", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-qmax", + "28", + "-mbd", + "rd", + "-trellis", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-precmp", + "satd", + "-dia_size", + "2", + "-pre_dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd+qp_rd", + "-non_linear_quant", + "1", + "-intra_vlc", + "1" + ], + "seconds": 6.734314099994663, + "failed": false, + "bytes": 18440803, + "mbps": 7.3763212000000005, + "vbv_diagnostics": [], + "ssim": 0.977673, + "psnr": 44.667631, + "experiment": "sweep" + }, + { + "scene": "grain", + "profile": "baseline8", + "options": [ + "-b:v", + "8000k" + ], + "seconds": 0.450617800001055, + "failed": false, + "bytes": 19519866, + "mbps": 7.8079464000000005, + "vbv_diagnostics": [], + "ssim": 0.976103, + "psnr": 44.121851, + "experiment": "sweep" + }, + { + "scene": "grain", + "profile": "ceiling9", + "options": [ + "-b:v", + "9000k" + ], + "seconds": 0.4521701999983634, + "failed": false, + "bytes": 19511164, + "mbps": 7.8044655999999994, + "vbv_diagnostics": [], + "ssim": 0.976069, + "psnr": 44.116949, + "experiment": "sweep" + }, + { + "scene": "grain", + "profile": "ceiling9-q1", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118" + ], + "seconds": 0.4738022000019555, + "failed": false, + "bytes": 22500847, + "mbps": 9.000338800000002, + "vbv_diagnostics": [], + "ssim": 0.976695, + "psnr": 44.167908, + "experiment": "sweep" + }, + { + "scene": "grain", + "profile": "rd-trellis", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1" + ], + "seconds": 2.473886899999343, + "failed": false, + "bytes": 22480529, + "mbps": 8.9922116, + "vbv_diagnostics": [], + "ssim": 0.979805, + "psnr": 44.877824, + "experiment": "sweep" + }, + { + "scene": "grain", + "profile": "rd-search", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-precmp", + "satd", + "-dia_size", + "2", + "-pre_dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd+qp_rd" + ], + "seconds": 4.519013700002688, + "failed": false, + "bytes": 21386259, + "mbps": 8.5545036, + "vbv_diagnostics": [], + "ssim": 0.980216, + "psnr": 45.003467, + "experiment": "sweep" + }, + { + "scene": "grain", + "profile": "rd-nonlinear", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-qmax", + "28", + "-mbd", + "rd", + "-trellis", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-precmp", + "satd", + "-dia_size", + "2", + "-pre_dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd+qp_rd", + "-non_linear_quant", + "1", + "-intra_vlc", + "1" + ], + "seconds": 6.315121100000397, + "failed": false, + "bytes": 20777203, + "mbps": 8.3108812, + "vbv_diagnostics": [], + "ssim": 0.980059, + "psnr": 44.965375, + "experiment": "sweep" + }, + { + "scene": "movement", + "profile": "rd-base-2", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1" + ], + "seconds": 2.805315099998552, + "failed": false, + "bytes": 22350665, + "mbps": 8.940266, + "vbv_diagnostics": [], + "ssim": 0.979, + "psnr": 44.946209, + "experiment": "sweep-extra" + }, + { + "scene": "movement", + "profile": "rd-cbp", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-mpv_flags", + "+mv0+cbp_rd" + ], + "seconds": 3.0841085000065505, + "failed": false, + "bytes": 22337432, + "mbps": 8.9349728, + "vbv_diagnostics": [], + "ssim": 0.978961, + "psnr": 44.937925, + "experiment": "sweep-extra" + }, + { + "scene": "movement", + "profile": "rd-search-no-qp", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-precmp", + "satd", + "-dia_size", + "2", + "-pre_dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd" + ], + "seconds": 3.554754899996624, + "failed": false, + "bytes": 22337320, + "mbps": 8.934928, + "vbv_diagnostics": [], + "ssim": 0.979148, + "psnr": 44.982372, + "experiment": "sweep-extra" + }, + { + "scene": "movement", + "profile": "rd-intravlc", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1" + ], + "seconds": 2.8845423000020673, + "failed": false, + "bytes": 22344784, + "mbps": 8.9379136, + "vbv_diagnostics": [], + "ssim": 0.979247, + "psnr": 44.997839, + "experiment": "sweep-extra" + }, + { + "scene": "movement", + "profile": "rd-nonlinear-no-qp", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-qmax", + "28", + "-non_linear_quant", + "1", + "-intra_vlc", + "1" + ], + "seconds": 5.487474300003669, + "failed": false, + "bytes": 22332214, + "mbps": 8.932885599999999, + "vbv_diagnostics": [], + "ssim": 0.975625, + "psnr": 44.38209, + "experiment": "sweep-extra" + }, + { + "scene": "movement", + "profile": "rd-bidir", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-bidir_refine", + "2", + "-mpv_flags", + "+mv0+cbp_rd" + ], + "seconds": 3.280958700001065, + "failed": false, + "bytes": 22345559, + "mbps": 8.938223599999999, + "vbv_diagnostics": [], + "ssim": 0.979008, + "psnr": 44.948524, + "experiment": "sweep-extra" + }, + { + "scene": "grain", + "profile": "rd-base-2", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1" + ], + "seconds": 2.48127370000293, + "failed": false, + "bytes": 22480529, + "mbps": 8.9922116, + "vbv_diagnostics": [], + "ssim": 0.979805, + "psnr": 44.877824, + "experiment": "sweep-extra" + }, + { + "scene": "grain", + "profile": "rd-cbp", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-mpv_flags", + "+mv0+cbp_rd" + ], + "seconds": 2.729152600004454, + "failed": false, + "bytes": 22454732, + "mbps": 8.9818928, + "vbv_diagnostics": [], + "ssim": 0.979944, + "psnr": 44.91646, + "experiment": "sweep-extra" + }, + { + "scene": "grain", + "profile": "rd-search-no-qp", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-precmp", + "satd", + "-dia_size", + "2", + "-pre_dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd" + ], + "seconds": 3.245404299996153, + "failed": false, + "bytes": 22458917, + "mbps": 8.9835668, + "vbv_diagnostics": [], + "ssim": 0.980293, + "psnr": 45.004495, + "experiment": "sweep-extra" + }, + { + "scene": "grain", + "profile": "rd-intravlc", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1" + ], + "seconds": 2.4860362999970675, + "failed": false, + "bytes": 22479229, + "mbps": 8.9916916, + "vbv_diagnostics": [], + "ssim": 0.980231, + "psnr": 44.985486, + "experiment": "sweep-extra" + }, + { + "scene": "grain", + "profile": "rd-nonlinear-no-qp", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-qmax", + "28", + "-non_linear_quant", + "1", + "-intra_vlc", + "1" + ], + "seconds": 4.631700899997668, + "failed": false, + "bytes": 22476500, + "mbps": 8.9906, + "vbv_diagnostics": [], + "ssim": 0.975941, + "psnr": 44.150489, + "experiment": "sweep-extra" + }, + { + "scene": "grain", + "profile": "rd-bidir", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-bidir_refine", + "2", + "-mpv_flags", + "+mv0+cbp_rd" + ], + "seconds": 2.9512957999977516, + "failed": false, + "bytes": 22456469, + "mbps": 8.9825876, + "vbv_diagnostics": [], + "ssim": 0.980056, + "psnr": 44.938696, + "experiment": "sweep-extra" + }, + { + "scene": "movement", + "profile": "baseline-final", + "options": [ + "-b:v", + "8000k" + ], + "seconds": 0.44679570000153035, + "failed": false, + "bytes": 16841715, + "mbps": 6.736686, + "vbv_diagnostics": [], + "ssim": 0.973753, + "psnr": 43.899443, + "experiment": "sweep-final" + }, + { + "scene": "movement", + "profile": "final-search", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd", + "-profile:v", + "4", + "-level:v", + "8" + ], + "seconds": 3.855890700004238, + "failed": false, + "bytes": 22344053, + "mbps": 8.937621199999999, + "vbv_diagnostics": [], + "ssim": 0.979373, + "psnr": 45.028009, + "experiment": "sweep-final" + }, + { + "scene": "movement", + "profile": "final-prepass", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd", + "-profile:v", + "4", + "-level:v", + "8", + "-mepre", + "1", + "-precmp", + "satd", + "-pre_dia_size", + "2" + ], + "seconds": 3.845232200001192, + "failed": false, + "bytes": 22323595, + "mbps": 8.929438, + "vbv_diagnostics": [], + "ssim": 0.979392, + "psnr": 45.033452, + "experiment": "sweep-final" + }, + { + "scene": "movement", + "profile": "final-bidir", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd", + "-profile:v", + "4", + "-level:v", + "8", + "-bidir_refine", + "2" + ], + "seconds": 4.038607900001807, + "failed": false, + "bytes": 22332301, + "mbps": 8.9329204, + "vbv_diagnostics": [], + "ssim": 0.979489, + "psnr": 45.055155, + "experiment": "sweep-final" + }, + { + "scene": "grain", + "profile": "baseline-final", + "options": [ + "-b:v", + "8000k" + ], + "seconds": 0.47837190000427654, + "failed": false, + "bytes": 19519866, + "mbps": 7.8079464000000005, + "vbv_diagnostics": [], + "ssim": 0.976103, + "psnr": 44.121851, + "experiment": "sweep-final" + }, + { + "scene": "grain", + "profile": "final-search", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd", + "-profile:v", + "4", + "-level:v", + "8" + ], + "seconds": 3.5954010999994352, + "failed": false, + "bytes": 22462613, + "mbps": 8.9850452, + "vbv_diagnostics": [], + "ssim": 0.980526, + "psnr": 45.056922, + "experiment": "sweep-final" + }, + { + "scene": "grain", + "profile": "final-prepass", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd", + "-profile:v", + "4", + "-level:v", + "8", + "-mepre", + "1", + "-precmp", + "satd", + "-pre_dia_size", + "2" + ], + "seconds": 3.5361934999964433, + "failed": false, + "bytes": 22456409, + "mbps": 8.982563599999999, + "vbv_diagnostics": [], + "ssim": 0.980745, + "psnr": 45.118886, + "experiment": "sweep-final" + }, + { + "scene": "grain", + "profile": "final-bidir", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd", + "-profile:v", + "4", + "-level:v", + "8", + "-bidir_refine", + "2" + ], + "seconds": 3.7241456999981892, + "failed": false, + "bytes": 22459294, + "mbps": 8.9837176, + "vbv_diagnostics": [], + "ssim": 0.980561, + "psnr": 45.067136, + "experiment": "sweep-final" + }, + { + "scene": "prores", + "profile": "baseline-final", + "options": [ + "-b:v", + "8000k" + ], + "seconds": 0.4710057999982382, + "failed": false, + "bytes": 10957536, + "mbps": 4.3830144, + "vbv_diagnostics": [], + "ssim": 0.981661, + "psnr": 45.631881, + "experiment": "sweep-final" + }, + { + "scene": "prores", + "profile": "final-search", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd", + "-profile:v", + "4", + "-level:v", + "8" + ], + "seconds": 4.006132100003015, + "failed": false, + "bytes": 22204433, + "mbps": 8.8817732, + "vbv_diagnostics": [], + "ssim": 0.989891, + "psnr": 48.601752, + "experiment": "sweep-final" + }, + { + "scene": "prores", + "profile": "final-prepass", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd", + "-profile:v", + "4", + "-level:v", + "8", + "-mepre", + "1", + "-precmp", + "satd", + "-pre_dia_size", + "2" + ], + "seconds": 4.027833000000101, + "failed": false, + "bytes": 22199417, + "mbps": 8.8797668, + "vbv_diagnostics": [], + "ssim": 0.989907, + "psnr": 48.608952, + "experiment": "sweep-final" + }, + { + "scene": "prores", + "profile": "final-bidir", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd", + "-profile:v", + "4", + "-level:v", + "8", + "-bidir_refine", + "2" + ], + "seconds": 4.250905599998077, + "failed": false, + "bytes": 22198422, + "mbps": 8.8793688, + "vbv_diagnostics": [], + "ssim": 0.989894, + "psnr": 48.602465, + "experiment": "sweep-final" + }, + { + "scene": "movement", + "profile": "selected", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd", + "-profile:v", + "4", + "-level:v", + "8", + "-mepre", + "1", + "-precmp", + "satd", + "-pre_dia_size", + "2", + "-bidir_refine", + "2" + ], + "seconds": 4.038508199999342, + "failed": false, + "bytes": 22344109, + "mbps": 8.9376436, + "vbv_diagnostics": [], + "ssim": 0.979444, + "psnr": 45.043522, + "experiment": "sweep-selected" + }, + { + "scene": "grain", + "profile": "selected", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd", + "-profile:v", + "4", + "-level:v", + "8", + "-mepre", + "1", + "-precmp", + "satd", + "-pre_dia_size", + "2", + "-bidir_refine", + "2" + ], + "seconds": 3.7604926000058185, + "failed": false, + "bytes": 22478218, + "mbps": 8.991287199999999, + "vbv_diagnostics": [], + "ssim": 0.98079, + "psnr": 45.123995, + "experiment": "sweep-selected" + }, + { + "scene": "prores", + "profile": "selected", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-dia_size", + "2", + "-last_pred", + "3", + "-mpv_flags", + "+mv0+cbp_rd", + "-profile:v", + "4", + "-level:v", + "8", + "-mepre", + "1", + "-precmp", + "satd", + "-pre_dia_size", + "2", + "-bidir_refine", + "2" + ], + "seconds": 4.198114999999234, + "failed": false, + "bytes": 22197779, + "mbps": 8.8791116, + "vbv_diagnostics": [], + "ssim": 0.989915, + "psnr": 48.611838, + "experiment": "sweep-selected" + } + ], + "production_60s": { + "input": "Complete 60-second H.264 sample, original decoding/scaling included, production two-pass path and test ISO per run.", + "repeats": 3, + "logical_cpus": 16, + "results": [ + { + "Run": 1, + "Status": "authored", + "Seconds": 12.4108192, + "CPUSeconds": 94, + "CPUPercent": 47.33772932571607, + "EncodingSeconds": 12.207460099999999, + "EncodingCPUPercent": 47.23034073238544, + "EncodingFPS": 122.87568320620603, + "Bytes": 67359483, + "PSNR": "44.739913", + "SSIM": "0.978379" + }, + { + "Run": 2, + "Status": "authored", + "Seconds": 12.5299856, + "CPUSeconds": 91.84375, + "CPUPercent": 45.81197902573806, + "EncodingSeconds": 12.3266455, + "EncodingCPUPercent": 46.08442793702472, + "EncodingFPS": 121.68760754902866, + "Bytes": 67355648, + "PSNR": "44.728587", + "SSIM": "0.978342" + }, + { + "Run": 3, + "Status": "authored", + "Seconds": 12.4791223, + "CPUSeconds": 92.546875, + "CPUPercent": 46.35085343702417, + "EncodingSeconds": 12.2377387, + "EncodingCPUPercent": 46.57084850161085, + "EncodingFPS": 122.57166432226569, + "Bytes": 67356496, + "PSNR": "44.751230", + "SSIM": "0.978430" + } + ] + }, + "limitations": [ + "Objective metrics support a source-specific choice; they are not a universal subjective quality guarantee.", + "No physical DVD player was tested.", + "20-second sweep timings are single observations; repeated timings use the separate 60-second source.", + "Earlier historical encoder timings used the old FFmpeg quality profile." + ], + "bitstream_checks": { + "production_60s_run_1": { + "frames": 1500, + "gops": 116, + "maximum_gop": 13, + "closed_gops": true, + "maximum_consecutive_B_pictures": 2, + "sequence_headers": [ + [ + 720, + 576, + 2, + 3, + 9000000, + 1835008 + ] + ], + "profile_level_indication": [ + 72 + ], + "rate_envelope_minimum_credit_bits": 37800 + }, + "production_60s_run_2": { + "frames": 1500, + "gops": 116, + "maximum_gop": 13, + "closed_gops": true, + "maximum_consecutive_B_pictures": 2, + "sequence_headers": [ + [ + 720, + 576, + 2, + 3, + 9000000, + 1835008 + ] + ], + "profile_level_indication": [ + 72 + ], + "rate_envelope_minimum_credit_bits": 134328 + }, + "production_60s_run_3": { + "frames": 1500, + "gops": 116, + "maximum_gop": 13, + "closed_gops": true, + "maximum_consecutive_B_pictures": 2, + "sequence_headers": [ + [ + 720, + 576, + 2, + 3, + 9000000, + 1835008 + ] + ], + "profile_level_indication": [ + 72 + ], + "rate_envelope_minimum_credit_bits": 48904 + }, + "full-file": { + "frames": 19877, + "gops": 1529, + "maximum_gop": 13, + "closed_gops": true, + "maximum_consecutive_B_pictures": 2, + "sequence_headers": [ + [ + 720, + 576, + 2, + 3, + 9000000, + 1835008 + ] + ], + "profile_level_indication": [ + 72 + ], + "rate_envelope_minimum_credit_bits": 1112 + }, + "ntsc": { + "frames": 599, + "gops": 38, + "maximum_gop": 16, + "closed_gops": true, + "maximum_consecutive_B_pictures": 2, + "sequence_headers": [ + [ + 720, + 480, + 2, + 4, + 9000000, + 1835008 + ] + ], + "profile_level_indication": [ + 72 + ], + "rate_envelope_minimum_credit_bits": 311268 + } + }, + "dvd_checks": { + "full-file": { + "source_duration": 795.111111, + "crop_left": 158, + "crop_right": 158, + "dvd_duration": 795.12, + "video": { + "codec_name": "mpeg2video", + "width": 720, + "height": 576, + "display_aspect_ratio": "4:3", + "r_frame_rate": "25/1", + "pix_fmt": "yuv420p" + }, + "audio": { + "codec_name": "ac3", + "sample_rate": "48000", + "channels": 2, + "bit_rate": "448000" + }, + "iso_bytes": 955922432, + "iso_sha256": "49c47727987520dbbd567f3d9209b617a36072d5a88b3d0f0f162ddea11f5239", + "decode_exit_code": 0, + "decode_stderr_bytes": 92, + "decode_diagnostics": [ + "libdvdnav ISO name-block diagnostic; no video/audio decoding errors" + ] + }, + "ntsc": { + "source_duration": 20, + "crop_left": 0, + "crop_right": 0, + "dvd_duration": 19.966667, + "video": { + "codec_name": "mpeg2video", + "width": 720, + "height": 480, + "display_aspect_ratio": "4:3", + "r_frame_rate": "30000/1001", + "pix_fmt": "yuv420p" + }, + "audio": { + "codec_name": "ac3", + "sample_rate": "48000", + "channels": 2, + "bit_rate": "448000" + }, + "iso_bytes": 24096768, + "iso_sha256": "a32a51dd8e9945095f7f56570197df21d061665330eb285a8293561b8d36be8e", + "decode_exit_code": 0, + "decode_stderr_bytes": 92, + "decode_diagnostics": [ + "libdvdnav ISO name-block diagnostic; no video/audio decoding errors" + ] + } + } +} diff --git a/validation/FFMPEG-QUALITY-2026-10-29.md b/validation/FFMPEG-QUALITY-2026-10-29.md new file mode 100644 index 0000000..4e46879 --- /dev/null +++ b/validation/FFMPEG-QUALITY-2026-10-29.md @@ -0,0 +1,105 @@ +# FFmpeg-only DVD quality — 2026-10-29 + +HCenc, its AviSynth/FFMS2 preparation path, setup script, settings, CLI flags, +benchmark candidates and CI installation have been removed. FFmpeg/FFprobe +remain external in the normal portable package. The only bundled executables +beside the app/CLI/benchmark are the three existing DVD authoring helpers. +Old preview preferences/queues import without retaining backend paths; a saved +three/four-worker backend setting becomes two workers. The new encoding key +prevents reuse of the old quality profile for unfinished jobs. + +## Selected profile + +Two-pass software MPEG-2, Main Profile / Main Level, 4:2:0, **9 Mbps target and +peak**, 1,835,008-bit VBV, closed GOPs (15 PAL / 18 NTSC maximum), two B pictures, +10-bit intra DC precision. PAL/NTSC raster, cadence, aspect and field handling +remain intact. Stereo AC-3 is now **448 kbps at 48 kHz**, up from 256 kbps. +Mux rate remains 10,080 kbps with 2,048-byte DVD packets. + +Finer quantization (`qmin 1`, `lmin 118`), rate-distortion macroblock decisions, +trellis, intra VLC and tested SATD/motion-search options are enabled in both +passes. Full arguments and processing order are in [the encoding guide](../docs/ENCODERS.md). +There is no denoising, sharpening or custom quantization matrix. + +Packing uses actual encoded sizes, adds discs rather than reducing bitrate, +and checks the mastered ISO size. The initial size estimate now accounts for +9 Mbps video plus 448 kbps audio. Short programmes cannot fill a whole disc +with useful picture data once the DVD rate/quantization ceiling is reached. + +## Measurements + +Windows, Ryzen 7 9800X3D (8 cores / 16 logical CPUs), FFmpeg 9.0.2. Three +20-second progressive PAL references were prepared once at 720×576, 25 fps, +4:3, YUV420P. Two scenes come from one H.264 film scan; the third is from a +separate ProRes film scan. Each candidate ran two passes with eight threads. +Quality compares decoded MPEG-2 against these identical SD reference frames. +All media, full paths, raw logs and ISOs stay in isolated local scratch space; +[deidentified results](FFMPEG-QUALITY-2026-10-29.json) record all 39 trials. + +| Scene | Old → selected video Mbps | Old → selected PSNR dB | Old → selected SSIM | Old → selected two-pass seconds | +|---|---:|---:|---:|---:| +| Movement | 6.737 → 8.938 | 43.899 → 45.044 | 0.973753 → 0.979444 | 0.447 → 4.039 | +| Grain | 7.808 → 8.991 | 44.122 → 45.124 | 0.976103 → 0.980790 | 0.478 → 3.760 | +| ProRes scene | 4.383 → 8.879 | 45.632 → 48.612 | 0.981661 → 0.989915 | 0.471 → 4.198 | + +Sweep timings are single observations and exclude preparation, metrics, audio +and DVD authoring. The objective improvement is consistent across these scenes; +it is not a guarantee of a universal subjective optimum. Native-resolution +reference/old/selected frame crops were also inspected: the selected output +retains finer texture and edges without adding sharpening or stretching. + +Raising the old 8 Mbps target to 9 Mbps alone barely changed the output: the +default quantizer floor was the limiting factor. Allowing quantizer 1 increased +useful bitrate; RD/trellis and the selected search/VLC settings further improved +metrics. Nonlinear quantization regressed both initial scenes substantially; +quantizer RD search also regressed the movement scene and underused the budget. +Those options were omitted. Every trial completed without logged buffer +underflow/overflow diagnostics. + +Three sequential production runs on a complete 60-second original H.264 sample +included decoding, crop/resize/cadence conversion, both MPEG-2 passes, AC-3/mux, +full decode validation and checkpoint hashing. Median elapsed time was **12.48 s**, +with **12.24 s** in the two MPEG-2 passes and **46.6%** mean CPU utilization during +those passes (normalized to all 16 logical CPUs). Each run authored a test ISO. +The previous fast FFmpeg profile took 2.02 s in the earlier comparison, so the +quality gain has a clear throughput cost. The new profile still encoded this +sample at approximately 4.8 times real time. The earlier HCenc comparison used +the old profiles and should not be read as a comparison at the new quality. + +## Validation scope + +- All-package Go tests and vet, plus race checks for media, model, engine, + process, Windows platform helpers and store. +- Actual PAL/NTSC pipelines check MPEG-2 Main Profile / Main Level, YUV420P, + cadence, 48 kHz / 448 kbps stereo AC-3, mixed aspect ratios, retained matching + interlacing and cross-standard deinterlacing. DVD's IFO-derived probe omits + sequence profile/level, so those are checked on the encoded MPG itself. +- Menus, thumbnails, autoplay, Unicode work paths, scan/exclusion recovery, + checkpoint reuse/publication recovery and 36/99-title authoring pass. +- Three 60-second streams contain 1,500 frames each, closed GOPs of at most + 13 pictures and at most two consecutive B pictures. Sequence headers declare + 9 Mbps, the 1,835,008-bit buffer and Main Profile / Main Level. An elementary + packet/DTS token-bucket check stays within that rate/buffer envelope; this is + an additional sanity check, not a complete DVD/VBV conformance certification. +- The complete 795.111-second pillarboxed H.264 fixture was regenerated with + this profile. The saved crop retains the full 964-pixel picture, removing + 158 pixels per side. MPG and authored DVD report 4:3; the DVD duration is + 795.12 s. Its 19,877 encoded pictures use closed GOPs of at most 13 pictures, + two B pictures maximum and the same rate/buffer envelope. The 955,922,432-byte + ISO hash matches the manifest, and the entire DVD title decodes successfully. +- A separate 20-second prepared film reference completed the NTSC CLI pipeline + and full DVD-title decode: 720×480, 30000/1001 fps, 4:3, closed GOPs of at most + 16 pictures, 448 kbps stereo AC-3, matching ISO/manifest hash. Both DVD decode + logs contain only libdvdnav's ISO name-block diagnostic, with no video/audio + decode errors; the decoder exits successfully with `-xerror`. +- The final benchmark binary passed a separate reference/offset/metrics/ISO + smoke run. Local build version: `0.1.0-preview.8-quality.1`. + +Physical-player playback has not been tested. The quality choice is supported +by these film samples and software checks; it does not promise perfection for +every source or standalone player. + +The bitrate/mux/buffer envelope and AC-3 ceiling follow +[FFmpeg's DVD target](https://ffmpeg.org/ffmpeg.html#target). +Quality options are described by [FFmpeg](https://ffmpeg.org/ffmpeg-codecs.html) +and the [MPlayer/MEncoder manual](https://www.mplayerhq.hu/DOCS/HTML/en/MPlayer.html). diff --git a/validation/GITHUB-ISSUES-2026-10-29.md b/validation/GITHUB-ISSUES-2026-10-29.md index 1cca7fb..6b445d8 100644 --- a/validation/GITHUB-ISSUES-2026-10-29.md +++ b/validation/GITHUB-ISSUES-2026-10-29.md @@ -1,5 +1,9 @@ # GitHub issue validation — 2026-10-29 +Historical implementation record: the encoder work for issue #7 was subsequently +superseded by the [FFmpeg-only quality profile](FFMPEG-QUALITY-2026-10-29.md). +The other issue fixes and regression checks remain in place. + Follow-up: [performance measurements and the additional H.264 pillarbox regression](ENCODER-PERFORMANCE-2026-10-29.md). That report records the stricter boundary check's failure on the user's additional fixture and its correction. From db1158706642e7f2ec1583a40911e9d3254f5a12 Mon Sep 17 00:00:00 2001 From: maghofer <327971135+maghofer@users.noreply.github.com> Date: Thu, 29 Oct 2026 23:18:40 +0100 Subject: [PATCH 6/7] Add default Balanced encoding profile and per-job selector --- README.md | 6 +- cmd/easydvd-benchmark/main.go | 7 +- docs/ENCODERS.md | 65 +- internal/app/cli.go | 2 + internal/engine/engine.go | 4 +- internal/integration/issues_test.go | 44 + internal/integration/pipeline_test.go | 17 +- internal/media/encode.go | 21 +- internal/media/encode_test.go | 1 + internal/model/model.go | 70 +- internal/model/model_test.go | 33 + internal/ui/job_header.go | 20 +- internal/ui/job_header_test.go | 28 + internal/ui/menu_settings.go | 2 +- internal/ui/ui.go | 8 +- validation/BALANCED-SCOPE-2026-10-29.json | 1030 +++++++++++++++++++++ validation/BALANCED-SCOPE-2026-10-29.md | 124 +++ validation/FFMPEG-QUALITY-2026-10-29.md | 3 + 18 files changed, 1437 insertions(+), 48 deletions(-) create mode 100644 validation/BALANCED-SCOPE-2026-10-29.json create mode 100644 validation/BALANCED-SCOPE-2026-10-29.md diff --git a/README.md b/README.md index 690666f..c6ef558 100644 --- a/README.md +++ b/README.md @@ -52,8 +52,10 @@ using easyDVD. 3. Choose your TV standard, disc capacity and menu style, then select **Start / resume**. Finished ISO files appear in your output folder. -FFmpeg performs high-quality two-pass MPEG-2 encoding, targeting 9 Mbps video -with 448 kbps AC-3 audio. easyDVD adds discs instead of reducing the bitrate to +FFmpeg performs two-pass MPEG-2 encoding. **Balanced** is the default, targeting +7.5 Mbps video with 256 kbps AC-3 audio for speed and smaller files. Choose +**Quality** in the job header for 9 Mbps video, 448 kbps audio and more detailed +analysis. easyDVD adds discs instead of reducing the chosen profile's bitrate to squeeze more footage onto one disc. FFmpeg remains an external dependency; first run can locate it or download a private copy. See [Encoding quality](docs/ENCODERS.md). For a single included video, **Job settings → Playback → No menu** creates a diff --git a/cmd/easydvd-benchmark/main.go b/cmd/easydvd-benchmark/main.go index 4b63e77..6ab4aa0 100644 --- a/cmd/easydvd-benchmark/main.go +++ b/cmd/easydvd-benchmark/main.go @@ -49,6 +49,7 @@ type Report struct { Reference string ReferenceSHA256 string Standard string + Profile string Duration float64 Tools []media.ToolStatus Results []Result @@ -72,6 +73,7 @@ func run() error { input := flag.String("input", "", "Representative source video") output := flag.String("output", "", "New directory for references, encoded samples, ISOs and report") standard := flag.String("standard", "PAL", "PAL or NTSC") + profile := flag.String("profile", model.ProfileBalanced, "Balanced or Quality production encoding") seconds := flag.Float64("seconds", 10, "Maximum sample duration") offset := flag.Float64("offset", 0, "Start time in seconds for the sample") repeats := flag.Int("repeats", 1, "Number of sequential production encoder runs") @@ -102,6 +104,7 @@ func run() error { } s := model.DefaultSettings(dir) s.Standard = *standard + s.EncodingProfile = *profile s.WorkDir = filepath.Join(dir, "work") s.OutputDir = filepath.Join(dir, "output") s.Encoders = 1 @@ -157,11 +160,11 @@ func run() error { if original.Aspect() == "16:9" { ref.DAR = 16.0 / 9 } - report := Report{Source: source, Reference: reference, Standard: s.Standard, Duration: duration, Tools: tools.Check(ctx), + report := Report{Source: source, Reference: reference, Standard: s.Standard, Profile: s.Profile(), Duration: duration, Tools: tools.Check(ctx), LogicalCPUs: runtime.NumCPU(), Repeats: *repeats, Preparation: preparation, InputMode: "DVD-resolution prepared progressive reference", Notes: []string{ - "The production two-pass FFmpeg profile targets 9 Mbps video with a 9 Mbps peak and 448 kbps stereo AC-3. Video sizes exclude audio and DVD muxing.", + fmt.Sprintf("The %s two-pass FFmpeg profile targets %d kbps video with a 9 Mbps peak and %d kbps stereo AC-3. Video sizes exclude audio and DVD muxing.", s.Profile(), s.VideoBitrate()/1000, s.AudioBitrate()/1000), "Seconds includes production encoding, audio/mux, complete decode validation and checkpoint hashing; EncodingSeconds isolates both MPEG-2 passes. Reference preparation, quality measurements and authoring are outside these timings.", "CPU percentages divide process CPU seconds by wall seconds and all logical CPUs. Runs are sequential.", "SSIM/PSNR compare decoded output against the DVD-resolution reference. Visual assessment and physical-player compatibility still require separate review.", diff --git a/docs/ENCODERS.md b/docs/ENCODERS.md index 78f9074..6269187 100644 --- a/docs/ENCODERS.md +++ b/docs/ENCODERS.md @@ -4,23 +4,40 @@ FFmpeg is the sole video encoder. The normal package keeps FFmpeg/FFprobe external: locate a compatible installation or accept the app's private download. There is no separate encoder runtime to install. +**Balanced is the default for new jobs.** Choose Balanced or Quality directly +in the job header before processing starts. The choice is saved per job; started +jobs keep their locked profile. Settings also offers the default for new/pending +jobs. CLI and benchmark accept `-profile Balanced` or `-profile Quality`. + +| Profile | Video target / peak | Stereo AC-3 | Intended use | +|---|---|---|---| +| Balanced (default) | 7,500 / 9,000 kbps | 256 kbps / 48 kHz | Faster encoding, smaller files, good DVD quality | +| Quality | 9,000 / 9,000 kbps | 448 kbps / 48 kHz | More detail analysis and the full conservative rate budget | + +Both profiles use two passes, RD macroblock decisions and intra VLC. Balanced +uses a quantizer floor of 2 and the fast default motion search without trellis +or the extra searches in Quality. On the measured 60-second film sample it +encoded in 2.96 s versus 12.47 s for Quality, with 20% less video data. See +[the Balanced measurements and Scope check](../validation/BALANCED-SCOPE-2026-10-29.md). + ## Bitrate and disc space -Every title uses two-pass VBR with a **9,000 kbps target and maximum**. easyDVD -never lowers a title's bitrate to fit more footage on a disc: it packs the actual +Each profile has its own VBR target and a **9,000 kbps maximum**. easyDVD +never lowers the selected profile's bitrate to fit more footage on a disc: it packs the actual encoded sizes and uses additional discs when needed. A title that cannot fit whole on the selected medium is reported; choose DVD-9 or split the source. -The ceiling follows FFmpeg's DVD target, leaving room for 448 kbps AC-3, +The ceiling follows FFmpeg's DVD target, leaving room for AC-3, navigation and multiplexing within the 10,080 kbps programme-stream mux rate. The DVD video buffer is 1,835,008 bits. A short programme may leave much of a disc empty: exceeding the bitrate ceiling or adding padding cannot improve it. -Very simple material can also use fewer bits after reaching quantizer 1. +Very simple material can also use fewer bits after reaching the profile's +minimum quantizer. ISO size checks and packing reserves remain authoritative for disc capacity. -## Production profile +## Quality profile -Both passes use the same quality settings: +Both passes use these quality settings: ```text -c:v mpeg2video -profile:v 4 -level:v 8 -pix_fmt yuv420p @@ -46,11 +63,26 @@ bits. Nonlinear quantization and quantizer RD search were tested but omitted because they regressed some of the supplied film samples. Pass one writes statistics without audio. Pass two encodes the selected audio -track to stereo AC-3 at **448 kbps / 48 kHz**, pads short audio, and creates silence +track to stereo AC-3 at **448 kbps / 48 kHz** in Quality or **256 kbps / 48 kHz** +in Balanced, pads short audio, and creates silence when needed. DVD muxing uses `-f dvd -muxrate 10080k -packetsize 2048`. The source duration limits the result; every encoded MPG is fully decoded and hashed before it can become a reusable checkpoint. A profile version change -invalidates old encoded checkpoints when an unfinished job resumes. +invalidates incompatible encoded checkpoints when an unfinished job resumes. +Existing Quality encodes retain their cache identity; saved jobs predating the +profile selector retain Quality. Switching profiles produces a different key. + +Balanced replaces the target with `-b:v 7500k` and uses these analysis options: + +```text +-qmin 2 -lmin 236 -mbd rd -intra_vlc 1 +``` + +Trellis, SATD searches, motion prepass, larger search patterns, extra predictors, +bidirectional refinement and `mpv_flags` overrides are left at FFmpeg defaults. +The DVD raster, peak rate, VBV, GOPs, aspect and field handling are shared. +The quantizer floor avoids spending unnecessary bits on clean/simple scenes; +Quality permits quantizer 1 when its slower analysis can preserve more detail. Resizing uses Lanczos and BT.601 limited-range output, with BT.709 input assumed for HD and BT.601 for SD. PAL tags are `bt470bg`, NTSC tags `smpte170m`, with @@ -77,6 +109,21 @@ The check uses per-pixel luminance with a two-level tolerance above nominal keep the original frame. This adds a decoding pass to new 16:9 encodes; completed compatible checkpoints are reused. +## Scope footage and playback windows + +A 1920×796 source has a 2.41:1 frame. DVD-Video stores this inside a 16:9 frame, +with top/bottom letterboxing. PAL uses the full 720-pixel width and 424 picture +lines in the 576-line frame. The output signals 16:9 with 64:45 sample aspect. +The picture is not cropped or stretched horizontally. + +In a playback window wider than 16:9, the player fits the whole DVD frame by +height, leaving side bars around it. The original 2.41:1 frame can instead fit +by width and look larger. This can produce visible bars on all four sides even +when the encoded picture reaches both horizontal edges. Zooming/cropping the +letterbox during playback can fill that window; a 2.41:1 DVD display-aspect flag +would not be a compatible DVD-Video solution. The supported aspect flags are +documented by [dvdauthor](https://github.com/ldo/dvdauthor/blob/master/doc/dvdauthor.sgml). + ## Repeatable benchmark `easydvd-benchmark` prepares a progressive DVD-resolution YUV4MPEG reference, @@ -87,7 +134,7 @@ from the reported elementary video size. Preparation, metrics and authoring are excluded from the encode timing. ```powershell -./bin/easydvd-benchmark.exe -input C:\Scans\sample.mov -output C:\Benchmarks\trial-01 -seconds 20 -repeats 3 +./bin/easydvd-benchmark.exe -input C:\Scans\sample.mov -output C:\Benchmarks\trial-01 -profile Balanced -seconds 20 -repeats 3 ``` Use `-offset` for another scene. For a complete short progressive source, diff --git a/internal/app/cli.go b/internal/app/cli.go index 9cb17c1..2af65b7 100644 --- a/internal/app/cli.go +++ b/internal/app/cli.go @@ -74,6 +74,7 @@ func CLI(args []string) error { downloadFFmpeg := fs.Bool("download-ffmpeg", false, "Download and remember the recommended private FFmpeg installation") resume := fs.Bool("resume", false, "Resume saved queue") workers := fs.Int("encoders", 2, "Parallel encoders (1–2)") + profile := fs.String("profile", model.ProfileBalanced, "Encoding profile: Balanced or Quality") if err := fs.Parse(args); err != nil { return err } @@ -149,6 +150,7 @@ func CLI(args []string) error { defaults.KeepWork = *keep defaults.NoMenu = *noMenu defaults.Encoders = *workers + defaults.EncodingProfile = *profile defaults.TitlesPerPage = *perPage if *efficient { defaults.Packing = "Space efficiency" diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 5e6e54f..43bee3d 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -386,7 +386,7 @@ func (e *Engine) estimateLocked(j *model.Job) { var items []packing.Item for i, v := range j.Videos { if !v.Excluded && v.Error == "" { - items = append(items, packing.Item{ID: v.ID, Bytes: v.EstimatedBytes(), Order: i}) + items = append(items, packing.Item{ID: v.ID, Bytes: v.EstimatedBytes(j.Settings), Order: i}) } } r, err := packing.Plan(context.Background(), items, j.Settings.Capacity(), j.Settings.Packing == "Space efficiency", 0) @@ -886,7 +886,7 @@ func checkSpace(ctx context.Context, s model.Settings, videos []model.Video) err var remaining, stage int64 for _, v := range videos { if v.Encoded == "" { - remaining += v.EstimatedBytes() + remaining += v.EstimatedBytes(s) } if v.Size > stage { stage = v.Size diff --git a/internal/integration/issues_test.go b/internal/integration/issues_test.go index bc22e4c..1568406 100644 --- a/internal/integration/issues_test.go +++ b/internal/integration/issues_test.go @@ -12,11 +12,55 @@ import ( "fmt" "os" "path/filepath" + "regexp" "strings" "testing" "time" ) +func TestScopeFillsDVDWidth(t *testing.T) { + tools, ctx := issueTools(t) + dir := t.TempDir() + source := filepath.Join(dir, "scope.mp4") + filter := "testsrc2=s=1920x796:r=24,drawbox=x=0:y=0:w=16:h=ih:color=white:t=fill,drawbox=x=iw-16:y=0:w=16:h=ih:color=white:t=fill" + if err := process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-y", "-f", "lavfi", "-i", filter, "-t", "2", "-c:v", "libx264", source}, process.Options{}); err != nil { + t.Fatal(err) + } + original, err := tools.Probe(ctx, source, "scope.mp4") + if err != nil { + t.Fatal(err) + } + for _, profile := range []string{model.ProfileBalanced, model.ProfileQuality} { + for _, standard := range []string{"PAL", "NTSC"} { + t.Run(profile+"/"+standard, func(t *testing.T) { + s := model.DefaultSettings(dir) + s.EncodingProfile, s.Standard, s.Encoders = profile, standard, 1 + v, err := tools.Encode(ctx, original, s, source, filepath.Join(dir, profile+standard), nil, nil) + if err != nil { + t.Fatal(err) + } + out, err := tools.Probe(ctx, v.Encoded, "out.mpg") + if err != nil || out.Aspect() != "16:9" || out.Width != 720 || out.Height != s.Height() { + t.Fatal(out, err) + } + var evidence bytes.Buffer + if err = process.Run(ctx, tools.FFmpeg, []string{"-hide_banner", "-i", v.Encoded, "-vf", "bbox=min_val=32", "-an", "-f", "null", "-"}, process.Options{Log: &evidence}); err != nil { + t.Fatal(err) + } + matches := regexp.MustCompile(`crop=(\d+):\d+:(\d+):\d+`).FindAllStringSubmatch(evidence.String(), -1) + if len(matches) == 0 { + t.Fatal("no visible-picture evidence", evidence.String()) + } + for _, bounds := range matches { + if bounds[1] != "720" || bounds[2] != "0" { + t.Fatal("scope encoding introduced side borders", bounds) + } + } + }) + } + } +} + func issueTools(t *testing.T) (media.Tools, context.Context) { t.Helper() if os.Getenv("EASYDVD_INTEGRATION") != "1" { diff --git a/internal/integration/pipeline_test.go b/internal/integration/pipeline_test.go index 261a413..9b181c0 100644 --- a/internal/integration/pipeline_test.go +++ b/internal/integration/pipeline_test.go @@ -90,12 +90,17 @@ func TestPipeline(t *testing.T) { } original[f.name] = h } - for _, standard := range []string{"PAL", "NTSC"} { - t.Run(standard, func(t *testing.T) { + for _, tc := range []struct{ profile, standard string }{ + {model.ProfileBalanced, "PAL"}, {model.ProfileBalanced, "NTSC"}, + {model.ProfileQuality, "PAL"}, {model.ProfileQuality, "NTSC"}, + } { + profile, standard := tc.profile, tc.standard + t.Run(profile+"/"+standard, func(t *testing.T) { s := model.DefaultSettings(dir) s.Standard = standard - s.OutputDir = filepath.Join(dir, "output-"+standard) - s.WorkDir = filepath.Join(dir, "work-"+standard) + s.EncodingProfile = profile + s.OutputDir = filepath.Join(dir, "output-"+profile+"-"+standard) + s.WorkDir = filepath.Join(dir, "work-"+profile+"-"+standard) s.TitlesPerPage = 2 s.KeepWork = true s.Encoders = 1 @@ -106,7 +111,7 @@ func TestPipeline(t *testing.T) { s.Media = "DVD-9" s.Packing = "Space efficiency" } - st, err := store.Open(filepath.Join(dir, standard+".db")) + st, err := store.Open(filepath.Join(dir, profile+"-"+standard+".db")) if err != nil { t.Fatal(err) } @@ -249,7 +254,7 @@ func TestPipeline(t *testing.T) { if len(p.Streams) < 2 || p.Streams[0].Codec != "mpeg2video" || p.Streams[0].Height != s.Height() || p.Streams[1].Codec != "ac3" || p.Streams[1].Channels != 2 { t.Fatal(b.String()) } - if p.Streams[0].Pixel != "yuv420p" || media.Ratio(p.Streams[0].Rate) != media.Ratio(s.FPS()) || p.Streams[1].BitRate != "448000" || p.Streams[1].SampleRate != "48000" { + if p.Streams[0].Pixel != "yuv420p" || media.Ratio(p.Streams[0].Rate) != media.Ratio(s.FPS()) || p.Streams[1].BitRate != fmt.Sprint(s.AudioBitrate()) || p.Streams[1].SampleRate != "48000" { t.Fatal("DVD profile, frame rate or audio constraints violated", b.String()) } // dvdvideo exposes IFO properties but does not report the MPEG-2 diff --git a/internal/media/encode.go b/internal/media/encode.go index 2ec46ca..abef1b4 100644 --- a/internal/media/encode.go +++ b/internal/media/encode.go @@ -110,15 +110,20 @@ func EncodeArgs(v model.Video, s model.Settings, input, passlog, output string, if threads > 8 { threads = 8 } - // Use the DVD target's conservative peak for the average too: packing adds - // discs instead of lowering quality. qmin AND lmin permit quantizer 1; - // raising the bitrate alone leaves easy material capped at quantizer 2. + // Balanced retains the old quantizer floor to avoid spending unnecessary + // bits on easy material. Quality allows finer quantization and adds the + // costly searches. Both keep inexpensive RD macroblock decisions. args = append(args, "-map", fmt.Sprintf("0:%d", v.VideoStream), "-vf", filter, "-c:v", "mpeg2video", "-profile:v", "4", "-level:v", "8", "-pix_fmt", "yuv420p", - "-b:v", "9000k", "-maxrate:v", "9000k", "-minrate:v", "0", "-bufsize:v", "1835008", - "-qmin", "1", "-lmin", "118", "-mbd", "rd", "-trellis", "1", "-intra_vlc", "1", - "-cmp", "satd", "-subcmp", "satd", "-mepre", "1", "-precmp", "satd", - "-dia_size", "2", "-pre_dia_size", "2", "-last_pred", "3", "-bidir_refine", "2", "-mpv_flags", "+mv0+cbp_rd", + "-b:v", fmt.Sprintf("%dk", s.VideoBitrate()/1000), "-maxrate:v", "9000k", "-minrate:v", "0", "-bufsize:v", "1835008", + "-mbd", "rd", "-intra_vlc", "1") + if s.Profile() == model.ProfileQuality { + args = append(args, "-qmin", "1", "-lmin", "118", "-trellis", "1", "-cmp", "satd", "-subcmp", "satd", "-mepre", "1", "-precmp", "satd", + "-dia_size", "2", "-pre_dia_size", "2", "-last_pred", "3", "-bidir_refine", "2", "-mpv_flags", "+mv0+cbp_rd") + } else { + args = append(args, "-qmin", "2", "-lmin", "236") + } + args = append(args, "-g", s.GOP(), "-bf", "2", "-flags", flags, "-sc_threshold", "1000000000", "-dc", "10", "-aspect", v.Aspect(), "-threads", strconv.Itoa(threads), "-pass", strconv.Itoa(pass), "-passlogfile", passlog, "-sn", "-dn", "-progress", "pipe:1", "-nostats") @@ -141,7 +146,7 @@ func EncodeArgs(v model.Video, s model.Settings, input, passlog, output string, if v.AudioStream < 0 { audio = "1:a:0" } - args = append(args, "-map", audio, "-c:a", "ac3", "-ar", "48000", "-ac", "2", "-b:a", "448k", "-af", "apad", "-shortest", "-t", fmt.Sprintf("%.6f", v.Duration), "-f", "dvd", "-muxrate", "10080k", "-packetsize", "2048", output) + args = append(args, "-map", audio, "-c:a", "ac3", "-ar", "48000", "-ac", "2", "-b:a", fmt.Sprintf("%dk", s.AudioBitrate()/1000), "-af", "apad", "-shortest", "-t", fmt.Sprintf("%.6f", v.Duration), "-f", "dvd", "-muxrate", "10080k", "-packetsize", "2048", output) } return args } diff --git a/internal/media/encode_test.go b/internal/media/encode_test.go index d2725eb..fa0e099 100644 --- a/internal/media/encode_test.go +++ b/internal/media/encode_test.go @@ -34,6 +34,7 @@ func TestAspectAndInterlace(t *testing.T) { } func TestAudioAndDVDArgs(t *testing.T) { s := model.DefaultSettings(t.TempDir()) + s.EncodingProfile = model.ProfileQuality v := model.Video{DAR: 4.0 / 3, Width: 720, Height: 576, Duration: 10, VideoStream: 2, AudioStream: -1} args := strings.Join(EncodeArgs(v, s, "source", "pass", "video.mpg", 2), " ") for _, want := range []string{"-pass 2", "-map 0:2", "anullsrc", "-map 1:a:0", "-af apad", "-b:v 9000k", "-maxrate:v 9000k", "-b:a 448k", "-f dvd", "-g 15"} { diff --git a/internal/model/model.go b/internal/model/model.go index 8e9452b..88c3cc1 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -23,24 +23,30 @@ const ( Complete State = "Complete" ) +const ( + ProfileBalanced = "Balanced" + ProfileQuality = "Quality" +) + type Settings struct { - Standard string `json:"standard"` - Media string `json:"media"` - Packing string `json:"packing"` - Layout string `json:"layout"` - TitlesPerPage int `json:"titles_per_page"` - StageLocally bool `json:"stage_locally"` - Encoders int `json:"encoders"` - OutputDir string `json:"output_dir"` - WorkDir string `json:"work_dir"` - Theme string `json:"theme"` - KeepWork bool `json:"keep_work"` - NoMenu bool `json:"no_menu,omitempty"` - Menu MenuStyle `json:"menu"` + Standard string `json:"standard"` + Media string `json:"media"` + Packing string `json:"packing"` + Layout string `json:"layout"` + TitlesPerPage int `json:"titles_per_page"` + StageLocally bool `json:"stage_locally"` + Encoders int `json:"encoders"` + EncodingProfile string `json:"encoding_profile"` + OutputDir string `json:"output_dir"` + WorkDir string `json:"work_dir"` + Theme string `json:"theme"` + KeepWork bool `json:"keep_work"` + NoMenu bool `json:"no_menu,omitempty"` + Menu MenuStyle `json:"menu"` } func DefaultSettings(base string) Settings { - return Settings{Standard: "PAL", Media: "DVD-5", Packing: "Strict order", Layout: "Text", TitlesPerPage: 10, StageLocally: true, Encoders: 2, OutputDir: filepath.Join(base, "easyDVD Output"), WorkDir: filepath.Join(base, "easyDVD Work"), Theme: "System", Menu: DefaultMenuStyle()} + return Settings{Standard: "PAL", Media: "DVD-5", Packing: "Strict order", Layout: "Text", TitlesPerPage: 10, StageLocally: true, Encoders: 2, EncodingProfile: ProfileBalanced, OutputDir: filepath.Join(base, "easyDVD Output"), WorkDir: filepath.Join(base, "easyDVD Work"), Theme: "System", Menu: DefaultMenuStyle()} } // Read old preview queues without retaining the removed backend configuration. @@ -60,6 +66,9 @@ func (s *Settings) UnmarshalJSON(data []byte) error { } func (s Settings) Validate() error { + if s.Profile() != ProfileBalanced && s.Profile() != ProfileQuality { + return fmt.Errorf("choose Balanced or Quality encoding") + } if s.Standard != "PAL" && s.Standard != "NTSC" { return fmt.Errorf("choose PAL or NTSC") } @@ -119,9 +128,36 @@ func (s Settings) GOP() string { // Only settings affecting an encoded title belong here. Menu edits and packing do not re-encode. func (s Settings) EncodingKey() string { + if s.Profile() == ProfileBalanced { + return Hash("mpeg2-v2-balanced-7500-9000-rd-q2-ac3-256-2pass-" + s.Standard) + } return Hash("mpeg2-v5-quality-ceiling-ac3-448-2pass-" + s.Standard) } +func (s Settings) Profile() string { + // Saved jobs without a profile used Quality. Preferences decode over the + // current defaults instead, so new jobs adopt Balanced while old jobs keep + // their effective profile and reusable checkpoints. + if s.EncodingProfile == "" { + return ProfileQuality + } + return s.EncodingProfile +} + +func (s Settings) VideoBitrate() int { + if s.Profile() == ProfileBalanced { + return 7500000 + } + return 9000000 +} + +func (s Settings) AudioBitrate() int { + if s.Profile() == ProfileBalanced { + return 256000 + } + return 448000 +} + func (v Video) ArtifactKey(s Settings) string { key := s.EncodingKey() + v.Fingerprint() if v.CropLeft+v.CropRight > 0 { @@ -171,8 +207,10 @@ func (v Video) OriginalLabel() string { return strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)) } -func (v Video) Fingerprint() string { return Hash(fmt.Sprintf("%s:%d:%d", v.Path, v.Size, v.ModTime)) } -func (v Video) EstimatedBytes() int64 { return int64(v.Duration * 9448000 / 8 * 1.035) } +func (v Video) Fingerprint() string { return Hash(fmt.Sprintf("%s:%d:%d", v.Path, v.Size, v.ModTime)) } +func (v Video) EstimatedBytes(s Settings) int64 { + return int64(v.Duration * float64(s.VideoBitrate()+s.AudioBitrate()) / 8 * 1.035) +} func (v Video) Aspect() string { if v.ContentDAR() >= 1.55 { return "16:9" diff --git a/internal/model/model_test.go b/internal/model/model_test.go index 625df99..1494463 100644 --- a/internal/model/model_test.go +++ b/internal/model/model_test.go @@ -37,6 +37,39 @@ func TestRemovedBackendPreferencesMigrate(t *testing.T) { } } +func TestProfilesPersistAndRetainLegacyQuality(t *testing.T) { + s := DefaultSettings(t.TempDir()) + if s.Profile() != ProfileBalanced { + t.Fatal("new jobs must default to Balanced") + } + balancedKey := s.EncodingKey() + balancedEstimate := (Video{Duration: 3600}).EstimatedBytes(s) + s.EncodingProfile = ProfileQuality + qualityKey := s.EncodingKey() + if qualityKey == balancedKey || qualityKey != Hash("mpeg2-v5-quality-ceiling-ac3-448-2pass-PAL") { + t.Fatal("quality checkpoint identity changed", qualityKey) + } + if (Video{Duration: 3600}).EstimatedBytes(s) <= balancedEstimate { + t.Fatal("profile ignored in space estimate") + } + data, err := json.Marshal(s) + if err != nil { + t.Fatal(err) + } + var saved Settings + if err = json.Unmarshal(data, &saved); err != nil || saved.Profile() != ProfileQuality || saved.EncodingKey() != qualityKey { + t.Fatal(saved, err) + } + var legacy Settings + if err = json.Unmarshal([]byte(`{"standard":"PAL"}`), &legacy); err != nil || legacy.Profile() != ProfileQuality || legacy.EncodingKey() != qualityKey { + t.Fatal("legacy job profile changed", legacy, err) + } + defaults := DefaultSettings(t.TempDir()) + if err = json.Unmarshal([]byte(`{"standard":"NTSC"}`), &defaults); err != nil || defaults.Profile() != ProfileBalanced { + t.Fatal("old preferences overrode new default", defaults, err) + } +} + func TestOriginalVideoLabel(t *testing.T) { v := Video{Path: filepath.Join("clips", "Family.trip.1999.mp4"), Label: "Renamed title"} if v.OriginalLabel() != "Family.trip.1999" { diff --git a/internal/ui/job_header.go b/internal/ui/job_header.go index 9327d9c..ce3e933 100644 --- a/internal/ui/job_header.go +++ b/internal/ui/job_header.go @@ -51,6 +51,19 @@ func (u *window) buildJobHeader() *fyne.Container { u.menuSettings(j.ID) } }) + u.profileToggle = widget.NewRadioGroup([]string{model.ProfileBalanced, model.ProfileQuality}, func(value string) { + if u.profileSync { + return + } + j := u.selectedJob() + if j == nil || j.Locked || j.State == model.Complete || j.State == model.Running || u.snapshot.Clearing { + return + } + next, id := j.Settings, j.ID + next.EncodingProfile = value + u.action(func() error { return u.engine.SetSettings(id, next) }) + }) + u.profileToggle.Horizontal, u.profileToggle.Required = true, true open := widget.NewButtonWithIcon("Open output", theme.FolderOpenIcon(), func() { if j := u.selectedJob(); j != nil { path := j.OutputPath @@ -63,7 +76,7 @@ func (u *window) buildJobHeader() *fyne.Container { u.headerInfo = container.NewVBox(u.source, u.meta, u.stage, container.NewHBox(rename, u.settings)) u.headerInfo.Hide() titleRow := container.NewBorder(nil, nil, nil, container.NewHBox(u.jobState, u.jobWarning, u.headerToggle), u.title) - summaryRow := container.NewBorder(nil, nil, nil, container.NewHBox(u.preview, open), u.jobSummary) + summaryRow := container.NewBorder(nil, nil, nil, container.NewHBox(u.profileToggle, u.preview, open), u.jobSummary) u.jobHeader = container.NewVBox(titleRow, summaryRow, u.activity, u.progress, u.scanProgress, u.headerInfo, widget.NewSeparator()) return u.jobHeader } @@ -86,6 +99,7 @@ func (u *window) setHeaderExpanded(expanded bool) { func (u *window) refreshJobHeader(j *model.Job) { if j == nil { + u.profileToggle.Disable() u.headerJob = "" u.setHeaderExpanded(false) u.progress.Hide() @@ -99,6 +113,10 @@ func (u *window) refreshJobHeader(j *model.Job) { u.setHeaderExpanded(false) } u.title.SetText(j.Title) + u.profileSync = true + u.profileToggle.SetSelected(j.Settings.Profile()) + u.profileSync = false + enabled(u.profileToggle, !j.Locked && j.State != model.Complete && j.State != model.Running && !u.snapshot.Clearing) u.jobState.SetText(string(j.State)) u.source.SetText(j.Folder) discs := fmt.Sprintf("~%d DVDs", j.EstimatedDiscs) diff --git a/internal/ui/job_header_test.go b/internal/ui/job_header_test.go index 8184e76..c0f0ede 100644 --- a/internal/ui/job_header_test.go +++ b/internal/ui/job_header_test.go @@ -75,6 +75,34 @@ func TestJobHeaderProgressFollowsActivity(t *testing.T) { } } +func TestJobHeaderProfilePersistsAndLocks(t *testing.T) { + u := fileListFixture(t) + if u.profileToggle.Selected != model.ProfileBalanced || u.profileToggle.Disabled() { + t.Fatal("Balanced toggle is not available") + } + u.profileToggle.SetSelected(model.ProfileQuality) + deadline := time.Now().Add(3 * time.Second) + for u.engine.Snapshot().Jobs[0].Settings.Profile() != model.ProfileQuality { + if time.Now().After(deadline) { + t.Fatal("job profile was not saved") + } + time.Sleep(5 * time.Millisecond) + } + if u.engine.Snapshot().Settings.Profile() != model.ProfileBalanced { + t.Fatal("job toggle changed defaults") + } + u.snapshot = u.engine.Snapshot() + u.refresh() + if u.profileToggle.Selected != model.ProfileQuality { + t.Fatal("refresh lost the selected profile") + } + u.snapshot.Jobs[0].Locked = true + u.refresh() + if !u.profileToggle.Disabled() { + t.Fatal("started job still allows profile changes") + } +} + func TestClearQueueConfirmationAndEmptyState(t *testing.T) { u := fileListFixture(t) u.setFileSelected("0", true) diff --git a/internal/ui/menu_settings.go b/internal/ui/menu_settings.go index d980318..ea12403 100644 --- a/internal/ui/menu_settings.go +++ b/internal/ui/menu_settings.go @@ -54,7 +54,7 @@ func (u *window) menuSettings(id string) fyne.Window { var items []packing.Item for i, v := range job.Videos { if !v.Excluded && v.Error == "" { - items = append(items, packing.Item{ID: v.ID, Bytes: v.EstimatedBytes(), Order: i}) + items = append(items, packing.Item{ID: v.ID, Bytes: v.EstimatedBytes(base), Order: i}) } } if plan, err := packing.Plan(ctx, items, base.Capacity(), base.Packing == "Space efficiency", 0); err == nil { diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 22ef8e1..7af770b 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -76,6 +76,8 @@ type window struct { headerInfo, jobHeader *fyne.Container jobSummary, jobState, activity *widget.Label headerToggle, jobWarning, clear *widget.Button + profileToggle *widget.RadioGroup + profileSync bool details *fyne.Container empty *fyne.Container start, pause, cancel, retry, settings, preview, remove, up, down *widget.Button @@ -426,6 +428,8 @@ func (u *window) settingsDialog(id string, s model.Settings) { } workers := widget.NewSelect([]string{"1", "2"}, nil) workers.SetSelected(strconv.Itoa(s.Encoders)) + profile := widget.NewSelect([]string{model.ProfileBalanced, model.ProfileQuality}, nil) + profile.SetSelected(s.Profile()) output := widget.NewEntry() output.SetText(s.OutputDir) work := widget.NewEntry() @@ -446,11 +450,12 @@ func (u *window) settingsDialog(id string, s model.Settings) { appearance.SetSelected(s.Theme) form := widget.NewForm(widget.NewFormItem("TV standard", standard), widget.NewFormItem("Disc capacity", medium), widget.NewFormItem("File allocation", packingMode), widget.NewFormItem("Menu layout", menuLayout), widget.NewFormItem("Titles per page", perPage), widget.NewFormItem("Encoding workers", workers), widget.NewFormItem("Output folder", folder(output)), widget.NewFormItem("Local work folder", folder(work)), widget.NewFormItem("Appearance", appearance)) form.Append("Playback", noMenu) + form.Append("Encoding profile", profile) note := "Applies to new and pending jobs. Started jobs retain their settings." if id != "" { note = "Settings for this folder. Locked when processing starts." } - heading := widget.NewLabel(note + "\nQuality: two-pass MPEG-2, 9 Mbps target / peak, AC-3 448 kbps.") + heading := widget.NewLabel(note + "\nBalanced: faster encoding and smaller files. Quality: higher bitrate and more detailed analysis.") heading.Wrapping = fyne.TextWrapWord var d dialog.Dialog save := func() { @@ -466,6 +471,7 @@ func (u *window) settingsDialog(id string, s model.Settings) { next.Layout = menuLayout.Selected next.TitlesPerPage = n next.Encoders, _ = strconv.Atoi(workers.Selected) + next.EncodingProfile = profile.Selected next.StageLocally = stage.Checked next.KeepWork = keep.Checked next.NoMenu = noMenu.Checked diff --git a/validation/BALANCED-SCOPE-2026-10-29.json b/validation/BALANCED-SCOPE-2026-10-29.json new file mode 100644 index 0000000..3eca5e6 --- /dev/null +++ b/validation/BALANCED-SCOPE-2026-10-29.json @@ -0,0 +1,1030 @@ +{ + "date": "2026-10-29", + "host": "Windows; Ryzen 7 9800X3D; 8 cores / 16 logical CPUs", + "ffmpeg": "9.0.2", + "method": "Prepared 20-second progressive PAL reference scenes; two MPEG-2 passes, eight threads. Movement and grain share an H.264 film source; ProRes and Scope are separate sources. Objective metrics use identical SD reference frames. Timings exclude reference preparation and metrics. Production trials run sequentially with original decoding/scaling, audio/mux, full decode and hashing.", + "sweep": [ + { + "scene": "movement", + "profile": "old8", + "options": [ + "-b:v", + "8000k" + ], + "seconds": 0.4015609999996741, + "failed": false, + "bytes": 16841715, + "mbps": 6.736686, + "vbv_diagnostics": [], + "ssim": 0.973753, + "psnr": 43.899443, + "experiment": "sweep" + }, + { + "scene": "movement", + "profile": "fast8-vlc", + "options": [ + "-b:v", + "8000k", + "-intra_vlc", + "1" + ], + "seconds": 0.39616250000017317, + "failed": false, + "bytes": 16804450, + "mbps": 6.72178, + "vbv_diagnostics": [], + "ssim": 0.973753, + "psnr": 43.899442, + "experiment": "sweep" + }, + { + "scene": "movement", + "profile": "fast7-q1-vlc", + "options": [ + "-b:v", + "7000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1" + ], + "seconds": 0.40140080000037415, + "failed": false, + "bytes": 17480952, + "mbps": 6.992380799999999, + "vbv_diagnostics": [], + "ssim": 0.974091, + "psnr": 43.951347, + "experiment": "sweep" + }, + { + "scene": "movement", + "profile": "fast7-mbd2", + "options": [ + "-b:v", + "7000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1", + "-mbd", + "rd" + ], + "seconds": 0.6972975999997288, + "failed": false, + "bytes": 17444746, + "mbps": 6.9778984, + "vbv_diagnostics": [], + "ssim": 0.975224, + "psnr": 44.147454, + "experiment": "sweep" + }, + { + "scene": "movement", + "profile": "fast7-trellis", + "options": [ + "-b:v", + "7000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1", + "-trellis", + "1" + ], + "seconds": 0.9812071999995169, + "failed": false, + "bytes": 17558208, + "mbps": 7.0232832, + "vbv_diagnostics": [], + "ssim": 0.974428, + "psnr": 44.054014, + "experiment": "sweep" + }, + { + "scene": "movement", + "profile": "fast8-q1-vlc", + "options": [ + "-b:v", + "8000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1" + ], + "seconds": 0.41513599999962025, + "failed": false, + "bytes": 19997055, + "mbps": 7.998822, + "vbv_diagnostics": [], + "ssim": 0.975656, + "psnr": 44.240289, + "experiment": "sweep" + }, + { + "scene": "movement", + "profile": "quality9", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-mepre", + "1", + "-precmp", + "satd", + "-dia_size", + "2", + "-pre_dia_size", + "2", + "-last_pred", + "3", + "-bidir_refine", + "2", + "-mpv_flags", + "+mv0+cbp_rd" + ], + "seconds": 3.7731089999997494, + "failed": false, + "bytes": 22338482, + "mbps": 8.9353928, + "vbv_diagnostics": [], + "ssim": 0.97946, + "psnr": 45.0455, + "experiment": "sweep" + }, + { + "scene": "grain", + "profile": "old8", + "options": [ + "-b:v", + "8000k" + ], + "seconds": 0.44330360000003566, + "failed": false, + "bytes": 19519866, + "mbps": 7.8079464000000005, + "vbv_diagnostics": [], + "ssim": 0.976103, + "psnr": 44.121851, + "experiment": "sweep" + }, + { + "scene": "grain", + "profile": "fast8-vlc", + "options": [ + "-b:v", + "8000k", + "-intra_vlc", + "1" + ], + "seconds": 0.4519630999993751, + "failed": false, + "bytes": 19452127, + "mbps": 7.7808508, + "vbv_diagnostics": [], + "ssim": 0.976177, + "psnr": 44.139846, + "experiment": "sweep" + }, + { + "scene": "grain", + "profile": "fast7-q1-vlc", + "options": [ + "-b:v", + "7000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1" + ], + "seconds": 0.44293500000003405, + "failed": false, + "bytes": 17560688, + "mbps": 7.0242752, + "vbv_diagnostics": [], + "ssim": 0.973275, + "psnr": 43.554472, + "experiment": "sweep" + }, + { + "scene": "grain", + "profile": "fast7-mbd2", + "options": [ + "-b:v", + "7000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1", + "-mbd", + "rd" + ], + "seconds": 0.7322054000005664, + "failed": false, + "bytes": 17525514, + "mbps": 7.0102056, + "vbv_diagnostics": [], + "ssim": 0.975241, + "psnr": 43.884637, + "experiment": "sweep" + }, + { + "scene": "grain", + "profile": "fast7-trellis", + "options": [ + "-b:v", + "7000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1", + "-trellis", + "1" + ], + "seconds": 0.9009264999995139, + "failed": false, + "bytes": 17522566, + "mbps": 7.009026400000001, + "vbv_diagnostics": [], + "ssim": 0.974274, + "psnr": 43.783861, + "experiment": "sweep" + }, + { + "scene": "grain", + "profile": "fast8-q1-vlc", + "options": [ + "-b:v", + "8000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1" + ], + "seconds": 0.4525372000007337, + "failed": false, + "bytes": 19984743, + "mbps": 7.9938972, + "vbv_diagnostics": [], + "ssim": 0.976228, + "psnr": 44.112821, + "experiment": "sweep" + }, + { + "scene": "grain", + "profile": "quality9", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-mepre", + "1", + "-precmp", + "satd", + "-dia_size", + "2", + "-pre_dia_size", + "2", + "-last_pred", + "3", + "-bidir_refine", + "2", + "-mpv_flags", + "+mv0+cbp_rd" + ], + "seconds": 3.588476200000514, + "failed": false, + "bytes": 22474247, + "mbps": 8.989698800000001, + "vbv_diagnostics": [], + "ssim": 0.980747, + "psnr": 45.113819, + "experiment": "sweep" + }, + { + "scene": "prores", + "profile": "old8", + "options": [ + "-b:v", + "8000k" + ], + "seconds": 0.3616394999999102, + "failed": false, + "bytes": 10957536, + "mbps": 4.3830144, + "vbv_diagnostics": [], + "ssim": 0.981661, + "psnr": 45.631881, + "experiment": "sweep" + }, + { + "scene": "prores", + "profile": "fast8-vlc", + "options": [ + "-b:v", + "8000k", + "-intra_vlc", + "1" + ], + "seconds": 0.3608921000004557, + "failed": false, + "bytes": 10957242, + "mbps": 4.3828968, + "vbv_diagnostics": [], + "ssim": 0.981661, + "psnr": 45.631818, + "experiment": "sweep" + }, + { + "scene": "prores", + "profile": "fast7-q1-vlc", + "options": [ + "-b:v", + "7000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1" + ], + "seconds": 0.38625409999986005, + "failed": false, + "bytes": 17652752, + "mbps": 7.0611008, + "vbv_diagnostics": [], + "ssim": 0.985762, + "psnr": 46.883719, + "experiment": "sweep" + }, + { + "scene": "prores", + "profile": "fast7-mbd2", + "options": [ + "-b:v", + "7000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1", + "-mbd", + "rd" + ], + "seconds": 0.6738470999998754, + "failed": false, + "bytes": 17656199, + "mbps": 7.0624796, + "vbv_diagnostics": [], + "ssim": 0.986646, + "psnr": 47.16341, + "experiment": "sweep" + }, + { + "scene": "prores", + "profile": "fast7-trellis", + "options": [ + "-b:v", + "7000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1", + "-trellis", + "1" + ], + "seconds": 0.928988699999536, + "failed": false, + "bytes": 17578983, + "mbps": 7.0315932000000005, + "vbv_diagnostics": [], + "ssim": 0.987131, + "psnr": 47.463437, + "experiment": "sweep" + }, + { + "scene": "prores", + "profile": "fast8-q1-vlc", + "options": [ + "-b:v", + "8000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1" + ], + "seconds": 0.39685949999966397, + "failed": false, + "bytes": 20007586, + "mbps": 8.0030344, + "vbv_diagnostics": [], + "ssim": 0.987213, + "psnr": 47.435251, + "experiment": "sweep" + }, + { + "scene": "prores", + "profile": "quality9", + "options": [ + "-b:v", + "9000k", + "-qmin", + "1", + "-lmin", + "118", + "-mbd", + "rd", + "-trellis", + "1", + "-intra_vlc", + "1", + "-cmp", + "satd", + "-subcmp", + "satd", + "-mepre", + "1", + "-precmp", + "satd", + "-dia_size", + "2", + "-pre_dia_size", + "2", + "-last_pred", + "3", + "-bidir_refine", + "2", + "-mpv_flags", + "+mv0+cbp_rd" + ], + "seconds": 3.89727430000039, + "failed": false, + "bytes": 22189443, + "mbps": 8.8757772, + "vbv_diagnostics": [], + "ssim": 0.989908, + "psnr": 48.609096, + "experiment": "sweep" + }, + { + "scene": "movement", + "profile": "rd75", + "options": [ + "-b:v", + "7500k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1", + "-mbd", + "rd" + ], + "seconds": 0.7510263000003761, + "failed": false, + "bytes": 18719952, + "mbps": 7.4879808, + "vbv_diagnostics": [], + "ssim": 0.976121, + "psnr": 44.322003, + "experiment": "sweep-extra" + }, + { + "scene": "movement", + "profile": "rd8", + "options": [ + "-b:v", + "8000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1", + "-mbd", + "rd" + ], + "seconds": 0.7356224000004659, + "failed": false, + "bytes": 19989823, + "mbps": 7.9959292, + "vbv_diagnostics": [], + "ssim": 0.976927, + "psnr": 44.479243, + "experiment": "sweep-extra" + }, + { + "scene": "movement", + "profile": "rd75-q2", + "options": [ + "-b:v", + "7500k", + "-intra_vlc", + "1", + "-mbd", + "rd" + ], + "seconds": 0.684084299999995, + "failed": false, + "bytes": 16445601, + "mbps": 6.5782404, + "vbv_diagnostics": [], + "ssim": 0.974568, + "psnr": 44.03442, + "experiment": "sweep-extra" + }, + { + "scene": "grain", + "profile": "rd75", + "options": [ + "-b:v", + "7500k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1", + "-mbd", + "rd" + ], + "seconds": 0.7533062000002246, + "failed": false, + "bytes": 18741396, + "mbps": 7.4965584000000005, + "vbv_diagnostics": [], + "ssim": 0.976854, + "psnr": 44.210477, + "experiment": "sweep-extra" + }, + { + "scene": "grain", + "profile": "rd8", + "options": [ + "-b:v", + "8000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1", + "-mbd", + "rd" + ], + "seconds": 0.7709679999998116, + "failed": false, + "bytes": 20021094, + "mbps": 8.008437599999999, + "vbv_diagnostics": [], + "ssim": 0.977994, + "psnr": 44.466489, + "experiment": "sweep-extra" + }, + { + "scene": "grain", + "profile": "rd75-q2", + "options": [ + "-b:v", + "7500k", + "-intra_vlc", + "1", + "-mbd", + "rd" + ], + "seconds": 0.7504422000001796, + "failed": false, + "bytes": 18751566, + "mbps": 7.500626400000001, + "vbv_diagnostics": [], + "ssim": 0.977127, + "psnr": 44.297937, + "experiment": "sweep-extra" + }, + { + "scene": "prores", + "profile": "rd75", + "options": [ + "-b:v", + "7500k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1", + "-mbd", + "rd" + ], + "seconds": 0.7594981000002008, + "failed": false, + "bytes": 18793979, + "mbps": 7.517591599999999, + "vbv_diagnostics": [], + "ssim": 0.987498, + "psnr": 47.503099, + "experiment": "sweep-extra" + }, + { + "scene": "prores", + "profile": "rd8", + "options": [ + "-b:v", + "8000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1", + "-mbd", + "rd" + ], + "seconds": 0.7195220999992671, + "failed": false, + "bytes": 20051868, + "mbps": 8.0207472, + "vbv_diagnostics": [], + "ssim": 0.988214, + "psnr": 47.792364, + "experiment": "sweep-extra" + }, + { + "scene": "prores", + "profile": "rd75-q2", + "options": [ + "-b:v", + "7500k", + "-intra_vlc", + "1", + "-mbd", + "rd" + ], + "seconds": 0.5944079000000784, + "failed": false, + "bytes": 10988463, + "mbps": 4.3953852, + "vbv_diagnostics": [], + "ssim": 0.982153, + "psnr": 45.752347, + "experiment": "sweep-extra" + }, + { + "scene": "scope", + "profile": "rd75", + "options": [ + "-b:v", + "7500k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1", + "-mbd", + "rd" + ], + "seconds": 0.7336996000003637, + "failed": false, + "bytes": 18813809, + "mbps": 7.5255236, + "vbv_diagnostics": [], + "ssim": 0.994371, + "psnr": 50.140599, + "experiment": "sweep-extra" + }, + { + "scene": "scope", + "profile": "rd8", + "options": [ + "-b:v", + "8000k", + "-qmin", + "1", + "-lmin", + "118", + "-intra_vlc", + "1", + "-mbd", + "rd" + ], + "seconds": 0.7717363000001569, + "failed": false, + "bytes": 20074744, + "mbps": 8.0298976, + "vbv_diagnostics": [], + "ssim": 0.994605, + "psnr": 50.402778, + "experiment": "sweep-extra" + }, + { + "scene": "scope", + "profile": "rd75-q2", + "options": [ + "-b:v", + "7500k", + "-intra_vlc", + "1", + "-mbd", + "rd" + ], + "seconds": 0.5474371000000247, + "failed": false, + "bytes": 7720667, + "mbps": 3.0882668, + "vbv_diagnostics": [], + "ssim": 0.989863, + "psnr": 47.077304, + "experiment": "sweep-extra" + } + ], + "production_60s": { + "balanced": { + "profile": "Balanced", + "repeats": 3, + "logical_cpus": 16, + "results": [ + { + "Run": 1, + "Status": "authored", + "Seconds": 2.9423496, + "CPUSeconds": 32.5625, + "CPUPercent": 69.16772398494047, + "EncodingSeconds": 2.7535664, + "EncodingCPUPercent": 71.42725430554353, + "EncodingFPS": 544.7480765308583, + "Bytes": 54033007, + "PSNR": "44.005520", + "SSIM": "0.974649", + "MPGBytes": 56985600 + }, + { + "Run": 2, + "Status": "authored", + "Seconds": 2.9825226000000002, + "CPUSeconds": 31.984375, + "CPUPercent": 67.02458641889251, + "EncodingSeconds": 2.7931628, + "EncodingCPUPercent": 68.63159524750938, + "EncodingFPS": 537.0256255739909, + "Bytes": 54033007, + "PSNR": "44.005520", + "SSIM": "0.974649", + "MPGBytes": 56985600 + }, + { + "Run": 3, + "Status": "authored", + "Seconds": 2.9621141, + "CPUSeconds": 31.90625, + "CPUPercent": 67.32153312392659, + "EncodingSeconds": 2.773705, + "EncodingCPUPercent": 69.42992315332741, + "EncodingFPS": 540.7929105654711, + "Bytes": 54033007, + "PSNR": "44.005520", + "SSIM": "0.974649", + "MPGBytes": 56985600 + } + ] + }, + "quality": { + "profile": "Quality", + "repeats": 3, + "logical_cpus": 16, + "results": [ + { + "Run": 1, + "Status": "authored", + "Seconds": 12.45991, + "CPUSeconds": 92.640625, + "CPUPercent": 46.469348996100294, + "EncodingSeconds": 12.2584595, + "EncodingCPUPercent": 46.42839705919002, + "EncodingFPS": 122.36447817933403, + "Bytes": 67357990, + "PSNR": "44.733858", + "SSIM": "0.978375", + "MPGBytes": 71954432 + }, + { + "Run": 2, + "Status": "authored", + "Seconds": 12.4665742, + "CPUSeconds": 92.515625, + "CPUPercent": 46.38184050996143, + "EncodingSeconds": 12.2700853, + "EncodingCPUPercent": 46.51970767065491, + "EncodingFPS": 122.24853889157559, + "Bytes": 67365343, + "PSNR": "44.742265", + "SSIM": "0.978390", + "MPGBytes": 71946240 + }, + { + "Run": 3, + "Status": "authored", + "Seconds": 12.5498141, + "CPUSeconds": 93.15625, + "CPUPercent": 46.393241992325606, + "EncodingSeconds": 12.349950799999998, + "EncodingCPUPercent": 46.511445414017366, + "EncodingFPS": 121.45797374350676, + "Bytes": 67351073, + "PSNR": "44.737096", + "SSIM": "0.978365", + "MPGBytes": 71936000 + } + ] + } + }, + "limitations": [ + "Single observations per sweep candidate; production timings are three repeats per profile.", + "Quality metrics support the source-specific selection rather than a universal subjective guarantee.", + "No physical DVD player was tested." + ], + "full_scope": { + "Balanced": { + "source_duration": 422.125, + "crop_left": 0, + "crop_right": 0, + "mpg_video": { + "profile": "Main", + "width": 720, + "height": 576, + "sample_aspect_ratio": "64:45", + "display_aspect_ratio": "16:9", + "level": 8, + "side_data_list": [ + {} + ] + }, + "dvd_streams": [ + { + "codec_name": "mpeg2video", + "sample_aspect_ratio": "64:45", + "display_aspect_ratio": "16:9", + "side_data_list": [ + {} + ] + }, + { + "codec_name": "ac3", + "sample_rate": "48000", + "bit_rate": "256000" + } + ], + "dvd_duration": 422.12, + "iso_bytes": 162930688, + "iso_sha256": "fa193f1b3adedb8e8bab7ee12e42b25e2c1f67e3997fb5a5ef1e9a2d24708336", + "dvd_decode_exit_code": 0, + "visible_bounds_at_20s": [ + 717, + 424, + 2, + 76 + ] + }, + "Quality": { + "source_duration": 422.125, + "crop_left": 0, + "crop_right": 0, + "mpg_video": { + "profile": "Main", + "width": 720, + "height": 576, + "sample_aspect_ratio": "64:45", + "display_aspect_ratio": "16:9", + "level": 8, + "side_data_list": [ + {} + ] + }, + "dvd_streams": [ + { + "codec_name": "mpeg2video", + "sample_aspect_ratio": "64:45", + "display_aspect_ratio": "16:9", + "side_data_list": [ + {} + ] + }, + { + "codec_name": "ac3", + "sample_rate": "48000", + "bit_rate": "448000" + } + ], + "dvd_duration": 422.12, + "iso_bytes": 317564928, + "iso_sha256": "f6a9a1a71213ac71f05de638354b5e36a72c5c26047fe31a402efeb2b43302a4", + "dvd_decode_exit_code": 0, + "visible_bounds_at_20s": [ + 717, + 424, + 2, + 76 + ] + } + }, + "screenshot_measurements": [ + { + "window": [ + 1872, + 966 + ], + "picture_bounds": [ + 2, + 95, + 1870, + 871 + ] + }, + { + "window": [ + 1869, + 967 + ], + "picture_bounds": [ + 76, + 127, + 1797, + 843 + ] + } + ], + "selected_sweep_profile": "rd75-q2", + "profile_settings": { + "Balanced": { + "target_bps": 7500000, + "peak_bps": 9000000, + "audio_bps": 256000, + "qmin": 2, + "lmin": 236, + "options": [ + "-mbd", + "rd", + "-intra_vlc", + "1" + ] + }, + "Quality": { + "target_bps": 9000000, + "peak_bps": 9000000, + "audio_bps": 448000, + "qmin": 1, + "lmin": 118, + "analysis": "Unchanged full Quality profile" + } + }, + "experimental_note": "The qmin=1/lmin=118 Balanced candidate used 384137216 ISO bytes on the complete Scope film versus 317564928 for Quality. The selected qmin=2/lmin=236 avoids those unnecessary bits on clean material; selected Balanced Scope ISO is 162930688 bytes." +} diff --git a/validation/BALANCED-SCOPE-2026-10-29.md b/validation/BALANCED-SCOPE-2026-10-29.md new file mode 100644 index 0000000..b661131 --- /dev/null +++ b/validation/BALANCED-SCOPE-2026-10-29.md @@ -0,0 +1,124 @@ +# Balanced profile and Scope playback — 2026-10-29 + +Balanced is the default for new jobs. The job header has an always-visible +Balanced / Quality choice, saved per job and disabled once processing locks +the settings. Global settings also provides the new/pending-job default. +CLI and benchmark accept `-profile Balanced` or `-profile Quality`. +Existing jobs without a profile retain Quality, including their compatible +saved encodes. Preferences loaded over current defaults adopt Balanced for new +jobs. Profile-specific cache keys and size estimates prevent cross-profile +checkpoint reuse and incorrect disc/work-space estimates. + +## Selected settings + +| | Balanced | Quality | +|---|---|---| +| Video target / peak | 7,500 / 9,000 kbps | 9,000 / 9,000 kbps | +| Stereo AC-3 | 256 kbps, 48 kHz | 448 kbps, 48 kHz | +| Minimum quantizer / lambda | 2 / 236 | 1 / 118 | +| Macroblock decision / intra VLC | RD / enabled | RD / enabled | +| Trellis and additional motion search | FFmpeg defaults | Existing full Quality analysis | + +Both use two passes, MPEG-2 Main Profile/Main Level, YUV420P, the same DVD VBV, +closed GOP limits, aspect, scaling and field handling. Neither applies denoising +or sharpening. Packing uses the chosen profile and actual encoded sizes; it +does not lower the selected target to force more content onto a disc. +Exact shared and Quality options are in [the encoding guide](../docs/ENCODERS.md). + +## Measurements + +Windows, Ryzen 7 9800X3D, 8 cores / 16 logical processors, FFmpeg 9.0.2. +Thirty-three candidate/scene trials used identical 20-second progressive PAL +references. Movement and grain share an H.264 film source; ProRes and Scope are +separate sources. The inexpensive RD decision consistently improved the old +profile, while trellis and the full motion searches cost much more time. +The [deidentified JSON](BALANCED-SCOPE-2026-10-29.json) records the candidates, +settings, metrics and timings. Raw media, file paths and logs remain local. + +| 20-second scene | Old fast profile PSNR / SSIM | Balanced PSNR / SSIM | Quality PSNR / SSIM | +|---|---|---|---| +| Movement | 43.899 / 0.973753 | 44.034 / 0.974568 | 45.046 / 0.979460 | +| Grain | 44.122 / 0.976103 | 44.298 / 0.977127 | 45.114 / 0.980747 | +| ProRes scene | 45.632 / 0.981661 | 45.752 / 0.982153 | 48.609 / 0.989908 | + +Balanced video rates were 6.578, 7.501 and 4.395 Mbps respectively, versus +6.737, 7.808 and 4.383 Mbps in the old fast profile. The quantizer floor lets +simple material use fewer bits instead of forcing the nominal target. These +metrics support decent quality with improved coding efficiency on these scenes; +they are not a universal subjective quality guarantee. + +An earlier candidate allowed quantizer 1 in Balanced. On the complete clean +Scope film it used more bits than Quality's slower analysis needed. Retaining +the old floor of 2 reduced that unnecessary bitrate substantially while still +improving the old fast profile's measured quality in all three film scenes. + +Three sequential production runs per selected profile used the same complete +60-second H.264 source, with source decoding/resizing, both passes, AC-3/mux, +full decode validation and hashing. Reference/crop analysis, quality metrics +and ISO authoring are outside the timing; each run also authored a test ISO. + +| Median | Balanced | Quality | +|---|---:|---:| +| Encode path | 2.96 s | 12.47 s | +| Elementary video bytes | 54,033,007 | 67,357,990 | +| MPG bytes | 56,985,600 | 71,946,240 | + +Balanced was approximately **4.2 times faster**, with **20% less video data** +and **21% smaller MPG files** on this sample. The old fast profile's earlier +2.02-second timing remains historical; Balanced deliberately spends a little +more effort on RD decisions. Sizes and speed depend on the source. + +## Scope investigation + +The supplied full source is 1920×796, square pixels, 24 fps, 2.412:1, lasting +422.125 s. Both profiles were encoded and authored with the normal menu path. +The complete titles decode successfully through the DVD demuxer with `-xerror`, +and both output ISO hashes match their manifests. Sources were read only; +isolated CLI queues were used, preserving the user's GUI queue/preferences. + +Both MPG and DVD titles report 720×576, 16:9 display aspect and 64:45 sample +aspect. The conversion scales the source to **720×424**, then adds **76 lines +above and below**. It does not add horizontal padding or crop the source. +At the sampled title frame, visible bounds are 717×424 at x=2, y=76 in both +profiles; the few dark edge pixels belong to the source vignette/compression, +not the large side margins in the playback screenshot. + +The screenshots show the same picture proportions at different scales: +one picture is 1,868×776 inside a 1,872×966 viewport; the smaller one is +1,721×716 inside a 1,869×967 viewport. Those picture ratios are both about +2.41:1. Fitting the complete 16:9 DVD frame by height in that approximately +1.93:1 window leaves side bars. The original 2.41:1 frame can instead fit by +width. The visible windowboxing follows from the compliant DVD frame and +player fit behavior, rather than encoded side padding. + +A compatible DVD cannot signal a 2.41:1 display aspect. Player zoom/cropping of +the letterbox can fill a wider playback window. The encode retains the full +picture and correct proportions for ordinary 16:9 playback. + +| Complete Scope film | Balanced | Quality | +|---|---:|---:| +| Authored DVD duration | 422.12 s | 422.12 s | +| ISO bytes | 162,930,688 | 317,564,928 | + +## Checks + +- All-package functional tests and vet; headless CI-tag checks. +- Both profiles in actual PAL/NTSC pipelines, including frame rate, profile/ + level, pixel format, audio rate, matching interlace and cross-standard conversion. +- New Scope regression checks every decoded frame's horizontal picture bounds + in both profiles/standards, using an edge-marked 1920×796/24 fps source. +- Header selection/persistence/default isolation and started-job locking; + legacy profile/cache migration; profile-aware estimates. +- Existing scan/exclusion, menus, autoplay, Unicode folders, recovery and + 36/99-title authoring checks. Header previews inspected at normal window size. +- Race checks on media/model/engine/process/platform/store and the job-header + tests pass. A broader UI race run reports existing timer-driven hover/menu + preview test races with Fyne's headless driver; the same failures reproduce + on the unmodified preceding commit. They are outside this profile change. + +No physical standalone DVD player was tested. + +References: [dvdauthor video attributes](https://github.com/ldo/dvdauthor/blob/master/doc/dvdauthor.sgml), +[FFmpeg codec options](https://ffmpeg.org/ffmpeg-codecs.html), +[scaling/aspect filters](https://ffmpeg.org/ffmpeg-filters.html#scale), and +[DVD target defaults](https://ffmpeg.org/ffmpeg.html#target). diff --git a/validation/FFMPEG-QUALITY-2026-10-29.md b/validation/FFMPEG-QUALITY-2026-10-29.md index 4e46879..5b31ffd 100644 --- a/validation/FFMPEG-QUALITY-2026-10-29.md +++ b/validation/FFMPEG-QUALITY-2026-10-29.md @@ -1,5 +1,8 @@ # FFmpeg-only DVD quality — 2026-10-29 +The profile below is now selectable as Quality; Balanced is the new-job default. +See [the profile comparison and Scope investigation](BALANCED-SCOPE-2026-10-29.md). + HCenc, its AviSynth/FFMS2 preparation path, setup script, settings, CLI flags, benchmark candidates and CI installation have been removed. FFmpeg/FFprobe remain external in the normal portable package. The only bundled executables From 7184d7612ca831ff0a2336e9da955f80dbb08421 Mon Sep 17 00:00:00 2001 From: maghofer <327971135+maghofer@users.noreply.github.com> Date: Fri, 30 Oct 2026 01:23:29 +0100 Subject: [PATCH 7/7] Finish queue controls and multi-title autoplay for preview 9 --- README.md | 19 +- VERSION | 2 +- cmd/easydvd-navcheck/main_windows.go | 19 +- docs/ENCODERS.md | 4 +- docs/MENUS.md | 12 +- internal/app/cli.go | 2 +- internal/engine/engine.go | 95 +++++--- internal/engine/engine_test.go | 65 ++++-- internal/engine/menu.go | 4 + internal/engine/queue_settings_test.go | 113 ++++++++++ internal/integration/autoplay_test.go | 95 ++++++++ internal/media/author.go | 35 ++- internal/media/encode_test.go | 14 ++ internal/model/model.go | 5 + internal/model/model_test.go | 5 +- internal/ui/details.go | 11 +- internal/ui/files.go | 109 ++++------ internal/ui/files_test.go | 46 ++-- internal/ui/header_layout.go | 92 ++++++++ internal/ui/job_header.go | 136 +++--------- internal/ui/job_header_test.go | 173 ++++++++------- internal/ui/jobs.go | 286 +++++++++++++++++++++++++ internal/ui/jobs_test.go | 163 ++++++++++++++ internal/ui/menu_settings.go | 2 +- internal/ui/menu_settings_test.go | 3 - internal/ui/playback_test.go | 51 ++++- internal/ui/read_only_text.go | 28 +++ internal/ui/read_only_text_test.go | 118 ++++++++++ internal/ui/selection.go | 53 +++++ internal/ui/selection_test.go | 114 ++++++++++ internal/ui/settings.go | 160 ++++++++++++++ internal/ui/settings_test.go | 129 +++++++++++ internal/ui/status.go | 96 +++++++++ internal/ui/ui.go | 255 +++++----------------- internal/ui/ui_test.go | 2 +- validation/PLAYBACK-UI.md | 25 +++ 36 files changed, 1998 insertions(+), 543 deletions(-) create mode 100644 internal/engine/queue_settings_test.go create mode 100644 internal/integration/autoplay_test.go create mode 100644 internal/ui/header_layout.go create mode 100644 internal/ui/jobs.go create mode 100644 internal/ui/jobs_test.go create mode 100644 internal/ui/read_only_text.go create mode 100644 internal/ui/read_only_text_test.go create mode 100644 internal/ui/selection.go create mode 100644 internal/ui/selection_test.go create mode 100644 internal/ui/settings.go create mode 100644 internal/ui/settings_test.go create mode 100644 internal/ui/status.go create mode 100644 validation/PLAYBACK-UI.md diff --git a/README.md b/README.md index c6ef558..1ee7f08 100644 --- a/README.md +++ b/README.md @@ -52,14 +52,27 @@ using easyDVD. 3. Choose your TV standard, disc capacity and menu style, then select **Start / resume**. Finished ISO files appear in your output folder. +Save **Default settings** for future jobs. Each new job takes a copy; existing +jobs keep their settings. Use **Job settings** to override the TV standard, +disc capacity, output folder and menu options for one job. Menu layout and +titles per page live in **Menu**. + +Job tiles show status and completion percentage. Click a tile to select it; +Ctrl-click toggles additional jobs and Shift-click selects a +range. Files use the same selection behavior. Use **Remove selected** or **Delete**. +The X on a tile removes that job. Removing active jobs asks to stop them first; +source and output files are kept. Overall progress appears in the bottom bar. + FFmpeg performs two-pass MPEG-2 encoding. **Balanced** is the default, targeting 7.5 Mbps video with 256 kbps AC-3 audio for speed and smaller files. Choose -**Quality** in the job header for 9 Mbps video, 448 kbps audio and more detailed +**Quality** in Job settings for 9 Mbps video, 448 kbps audio and more detailed analysis. easyDVD adds discs instead of reducing the chosen profile's bitrate to squeeze more footage onto one disc. FFmpeg remains an external dependency; first run can locate it or download a private copy. See [Encoding quality](docs/ENCODERS.md). -For a single included video, **Job settings → Playback → No menu** creates a -disc that starts automatically and stops at the end. +Single-video jobs default to automatic playback without a menu; multi-video +jobs default to a menu. Override either choice in **Job settings → Playback**. +With **No menu**, every disc plays its included videos in order and stops at +the end. Menu editing is disabled until menus are enabled again. For more on menu appearance and presets, see [Menu settings](docs/MENUS.md). Report problems or suggest changes through [GitHub Issues](https://github.com/maghofer/easyDVD/issues). diff --git a/VERSION b/VERSION index e418c31..2f619f0 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.0-preview.8 +0.1.0-preview.9 diff --git a/cmd/easydvd-navcheck/main_windows.go b/cmd/easydvd-navcheck/main_windows.go index e6e9fc3..cab8341 100644 --- a/cmd/easydvd-navcheck/main_windows.go +++ b/cmd/easydvd-navcheck/main_windows.go @@ -9,13 +9,14 @@ import ( "os" "path/filepath" "runtime" + "strconv" "time" "unsafe" ) func main() { - if len(os.Args) != 3 && !(len(os.Args) == 4 && os.Args[3] == "--autoplay") { - fmt.Fprintln(os.Stderr, "Usage: easydvd-navcheck VLC_DIRECTORY FIXTURE.iso [--autoplay] (otherwise: 3 titles, 2 menu entries per page)") + if len(os.Args) != 3 && !((len(os.Args) == 4 || len(os.Args) == 5) && os.Args[3] == "--autoplay") { + fmt.Fprintln(os.Stderr, "Usage: easydvd-navcheck VLC_DIRECTORY FIXTURE.iso [--autoplay [TITLE_COUNT]] (otherwise: 3 titles, 2 menu entries per page)") os.Exit(2) } root, _ := filepath.Abs(os.Args[1]) @@ -65,9 +66,21 @@ func main() { time.Sleep(120 * time.Millisecond) } call("libvlc_media_player_play", player) - if len(os.Args) == 4 { + if len(os.Args) >= 4 { + count := 1 + if len(os.Args) == 5 { + var err error + count, err = strconv.Atoi(os.Args[4]) + if err != nil || count < 1 || count > 99 { + panic("TITLE_COUNT must be 1–99") + } + } waitTitle(1, 5*time.Second) fmt.Println("Automatic first play: title", title()) + for i := 2; i <= count; i++ { + waitTitle(i, 5*time.Second) + fmt.Println("Automatic next title:", title()) + } end := time.Now().Add(15 * time.Second) for time.Now().Before(end) { if state() == 6 { diff --git a/docs/ENCODERS.md b/docs/ENCODERS.md index 6269187..6b16e0c 100644 --- a/docs/ENCODERS.md +++ b/docs/ENCODERS.md @@ -5,8 +5,8 @@ external: locate a compatible installation or accept the app's private download. There is no separate encoder runtime to install. **Balanced is the default for new jobs.** Choose Balanced or Quality directly -in the job header before processing starts. The choice is saved per job; started -jobs keep their locked profile. Settings also offers the default for new/pending +in Job settings before processing starts. The choice is saved per job; started +jobs keep their locked profile. Default settings also offers the default for new jobs. CLI and benchmark accept `-profile Balanced` or `-profile Quality`. | Profile | Video target / peak | Stereo AC-3 | Intended use | diff --git a/docs/MENUS.md b/docs/MENUS.md index cd68544..877b674 100644 --- a/docs/MENUS.md +++ b/docs/MENUS.md @@ -1,6 +1,7 @@ # Menu settings -Choose **Menu** on a folder job, or **Settings → Menu settings** for defaults. +Choose **Job settings → Menu → Edit menu**, or +**Default settings → Menu defaults** for defaults. The window contains parameters and an automatic preview, with DVD and page selectors. It is not a freeform editor. Only the requested page is rendered; typing and sliders use a short debounce. Thumbnail extraction happens in the @@ -29,10 +30,15 @@ Validated assets are copied into local application data so a removed or changed original does not break queued jobs or presets. Keep these assets with application data; they are persistent, unlike generated menu graphics in the work directory. -**Apply to job** updates a pending job. **Save as defaults** updates new and -unstarted jobs. Started/finished jobs keep their snapshot; their Menu window can +**Apply to job** updates a pending job. **Save as defaults** updates future jobs. +Existing jobs keep their snapshot; a Menu window opened for a started/finished set can preview alternative settings and save presets without rewriting their ISO files. Nothing changes until an Apply/Save action is selected. Finished output folders continue to contain only ISOs. +Single-video jobs default to no menu, and multi-video jobs default to a menu. +Both can be overridden in Job settings. With **No menu** selected, the menu +editor button is disabled, and each disc plays its included videos in order +before stopping. Uncheck **No menu** to enable the editor again. + The CLI accepts `-menu-aspect 4:3` or `-menu-aspect 16:9`. diff --git a/internal/app/cli.go b/internal/app/cli.go index 2af65b7..206f9af 100644 --- a/internal/app/cli.go +++ b/internal/app/cli.go @@ -65,7 +65,7 @@ func CLI(args []string) error { direct := fs.Bool("direct", false, "Read original sources directly") keep := fs.Bool("keep-work", false, "Retain intermediate media") thumbs := fs.Bool("thumbnails", false, "Thumbnail menus") - noMenu := fs.Bool("no-menu", false, "Start playback automatically; requires one included video per job") + noMenu := fs.Bool("no-menu", false, "Play all included videos automatically in order without a menu") combine := fs.Bool("combine-files", false, "Combine explicit video files into one DVD set") perPage := fs.Int("titles", 10, "Titles per page (1–12 text, 1–6 thumbnails)") tools := fs.Bool("check-tools", false, "Print tool diagnostics and exit") diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 43bee3d..362a270 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -84,6 +84,9 @@ func New(st *store.Store, defaults model.Settings, t media.Tools, options ...Opt j.State = model.Paused j.Stage = "Interrupted — resume to continue" } + if j.ScanComplete && !j.Locked { + applyAutomaticMenu(j) + } } if err = st.Save(e.jobs); err != nil { cancel() @@ -167,6 +170,10 @@ func (e *Engine) Add(folder string) error { } } j := model.Job{ID: model.ID(), Folder: absolute, Title: filepath.Base(absolute), State: model.Scanning, Stage: "Discovering videos", Settings: e.settings, Created: time.Now()} + if e.settings.NoMenu { + mode := true + j.NoMenuOverride = &mode + } e.jobs = append(e.jobs, j) e.persistLocked() e.scanLocked(j.ID) @@ -212,6 +219,10 @@ func (e *Engine) AddFiles(paths []string) error { title = filepath.Base(filepath.Dir(sources[0])) } j := model.Job{ID: model.ID(), Folder: filepath.Dir(sources[0]), Sources: sources, Title: title, State: model.Scanning, Stage: "Inspecting selected videos", Settings: e.settings, Created: time.Now()} + if e.settings.NoMenu { + mode := true + j.NoMenuOverride = &mode + } e.jobs = append(e.jobs, j) e.persistLocked() e.scanLocked(j.ID) @@ -361,6 +372,7 @@ func (e *Engine) scanLocked(id string) { j.State = model.Ready j.Stage = "Ready" j.Progress = 0 + applyAutomaticMenu(j) if err != nil { j.State = model.Blocked j.Error = err.Error() @@ -509,17 +521,45 @@ func (e *Engine) Remove(id string) error { // them. Source files, saved encodes and published output are left intact. Jobs // added while cancellation is underway are not part of this clear operation. func (e *Engine) ClearQueue() error { + return e.removeJobs(nil, true) +} + +// RemoveJobs stops and removes exactly the selected jobs, keeping their files. +func (e *Engine) RemoveJobs(ids []string) error { + return e.removeJobs(ids, false) +} + +func (e *Engine) removeJobs(jobIDs []string, all bool) error { e.mu.Lock() if e.clearing { e.mu.Unlock() return nil } + ids := make(map[string]bool, len(e.jobs)) + for _, id := range jobIDs { + if e.index(id) < 0 { + e.mu.Unlock() + return fmt.Errorf("selected job no longer exists") + } + ids[id] = true + } + if all { + for _, j := range e.jobs { + ids[j.ID] = true + } + } + if len(ids) == 0 { + e.mu.Unlock() + return nil + } + resume := e.enabled && !all e.clearing = true e.enabled = false - ids := make(map[string]bool, len(e.jobs)) for k := range e.jobs { j := &e.jobs[k] - ids[j.ID] = true + if !ids[j.ID] { + continue + } if cancel := e.cancels[j.ID]; cancel != nil { cancel() } @@ -528,7 +568,7 @@ func (e *Engine) ClearQueue() error { } if j.State != model.Complete { j.State = model.Canceled - j.Stage = "Stopping — clearing queue" + j.Stage = "Stopping — removing from queue" } } e.persistLocked() @@ -536,6 +576,9 @@ func (e *Engine) ClearQueue() error { defer func() { e.mu.Lock() e.clearing = false + if resume && e.ctx.Err() == nil && e.lastError == "" { + e.enabled = true + } e.signal() e.mu.Unlock() }() @@ -651,11 +694,22 @@ func (e *Engine) SetExcluded(id string, videoIDs []string, excluded bool) error return nil } +// The first inspected collection, and later inclusion changes, choose a useful +// default. A manual menu/no-menu choice takes precedence and survives rescans. +func applyAutomaticMenu(j *model.Job) { + if j.NoMenuOverride != nil { + j.Settings.NoMenu = *j.NoMenuOverride + return + } + j.Settings.NoMenu = len(j.ActiveVideos()) == 1 +} + func (e *Engine) refreshReadinessLocked(j *model.Job) { if !j.ScanComplete || (j.State != model.Ready && j.State != model.Blocked) { return } active := j.ActiveVideos() + applyAutomaticMenu(j) if len(active) == 0 { j.State, j.Error = model.Blocked, "No included video files" return @@ -666,14 +720,20 @@ func (e *Engine) refreshReadinessLocked(j *model.Job) { return } } - if j.Settings.NoMenu && len(active) != 1 { - j.State, j.Error = model.Blocked, "No menu requires exactly one included video; enable menus or exclude the other files" - return - } j.State, j.Stage, j.Error = model.Ready, "Ready", "" } func (e *Engine) SetSettings(id string, s model.Settings) error { + return e.setSettings(id, s, false) +} + +// SetJobSettings records a deliberate playback-mode choice, even if it matches +// the current automatic default for the job's number of included videos. +func (e *Engine) SetJobSettings(id string, s model.Settings) error { + return e.setSettings(id, s, true) +} + +func (e *Engine) setSettings(id string, s model.Settings, explicitPlayback bool) error { if err := s.Validate(); err != nil { return err } @@ -684,13 +744,6 @@ func (e *Engine) SetSettings(id string, s model.Settings) error { return err } e.settings = s - for i := range e.jobs { - if !e.jobs[i].Locked && e.jobs[i].State != model.Complete { - e.jobs[i].Settings = s - e.refreshReadinessLocked(&e.jobs[i]) - e.estimateLocked(&e.jobs[i]) - } - } } else { i := e.index(id) if i < 0 { @@ -699,6 +752,10 @@ func (e *Engine) SetSettings(id string, s model.Settings) error { if e.jobs[i].Locked { return fmt.Errorf("settings were locked when this job started; add the folder again for different encoding settings") } + if explicitPlayback || e.jobs[i].Settings.NoMenu != s.NoMenu { + mode := s.NoMenu + e.jobs[i].NoMenuOverride = &mode + } e.jobs[i].Settings = s e.refreshReadinessLocked(&e.jobs[i]) e.estimateLocked(&e.jobs[i]) @@ -770,13 +827,6 @@ func (e *Engine) loop() { break } j := e.jobs[i] - if j.Settings.NoMenu && len(j.ActiveVideos()) != 1 { - e.jobs[i].State = model.Blocked - e.jobs[i].Error = "No menu requires exactly one included video; enable menus or exclude the other files" - e.persistLocked() - e.mu.Unlock() - continue - } ctx, cancel := context.WithCancel(e.ctx) e.cancels[j.ID] = cancel delete(e.pauses, j.ID) @@ -935,9 +985,6 @@ func (e *Engine) run(ctx context.Context, j model.Job) error { if len(videos) == 0 { return fmt.Errorf("no included videos") } - if j.Settings.NoMenu && len(videos) != 1 { - return fmt.Errorf("no menu requires exactly one included video; enable menus or exclude the other files") - } for _, v := range videos { if v.Error != "" && v.Duration <= 0 { return fmt.Errorf("%s: %s", v.Relative, v.Error) diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.go index 646b2b3..cd88fe1 100644 --- a/internal/engine/engine_test.go +++ b/internal/engine/engine_test.go @@ -177,16 +177,15 @@ func TestExcludingFailedFilesUnblocksJob(t *testing.T) { } } -func TestInvalidNoMenuJobStaysEditable(t *testing.T) { +func TestAutomaticMenuDefaultsAndManualOverrides(t *testing.T) { st, err := store.Open(filepath.Join(t.TempDir(), "q.db")) if err != nil { t.Fatal(err) } defer st.Close() s := model.DefaultSettings(t.TempDir()) - s.NoMenu = true j := model.Job{ID: model.ID(), State: model.Ready, ScanComplete: true, Settings: s, Videos: []model.Video{{ID: "one", Duration: 10}, {ID: "two", Duration: 10}}} - if err = st.Save([]model.Job{j}); err != nil { + if err := st.Save([]model.Job{j}); err != nil { t.Fatal(err) } e, err := New(st, s, media.Tools{}) @@ -194,21 +193,51 @@ func TestInvalidNoMenuJobStaysEditable(t *testing.T) { t.Fatal(err) } defer e.Close() - e.Start() - deadline := time.Now().Add(time.Second) - for time.Now().Before(deadline) { - got := e.Snapshot().Jobs[0] - if got.State == model.Blocked { - if got.Locked { - t.Fatal("invalid no-menu choice locked settings") - } - return - } - time.Sleep(5 * time.Millisecond) + if err := e.SetExcluded(j.ID, []string{"two"}, true); err != nil { + t.Fatal(err) + } + if !e.Snapshot().Jobs[0].Settings.NoMenu { + t.Fatal("single-video default must be automatic playback") + } + if err := e.SetExcluded(j.ID, []string{"two"}, false); err != nil { + t.Fatal(err) + } + if e.Snapshot().Jobs[0].Settings.NoMenu { + t.Fatal("multi-video default must be a menu") + } + next := s + next.NoMenu = true + if err := e.SetJobSettings(j.ID, next); err != nil { + t.Fatal(err) + } + got := e.Snapshot().Jobs[0] + if got.State != model.Ready || !got.Settings.NoMenu || got.NoMenuOverride == nil { + t.Fatal("multi-video no-menu override was not accepted") + } + if err := e.SetExcluded(j.ID, []string{"two"}, true); err != nil { + t.Fatal(err) + } + if err := e.SetExcluded(j.ID, []string{"two"}, false); err != nil { + t.Fatal(err) + } + if !e.Snapshot().Jobs[0].Settings.NoMenu { + t.Fatal("automatic default replaced a manual choice") + } + if err := e.SetExcluded(j.ID, []string{"two"}, true); err != nil { + t.Fatal(err) + } + if err := e.SetMenu(j.ID, s.Menu, s.Layout, s.TitlesPerPage); err != nil { + t.Fatal(err) + } + got = e.Snapshot().Jobs[0] + if got.Settings.NoMenu || got.NoMenuOverride == nil || *got.NoMenuOverride { + t.Fatal("single video could not be given a menu explicitly") + } + saved, err := st.Load() + if err != nil || saved[0].NoMenuOverride == nil || *saved[0].NoMenuOverride { + t.Fatal("manual choice was not persisted", err) } - t.Fatal("invalid no-menu job was not blocked") } - func TestClearQueueStopsWorkersAndKeepsFiles(t *testing.T) { st, err := store.Open(filepath.Join(t.TempDir(), "q.db")) if err != nil { @@ -276,7 +305,7 @@ func TestClearQueueStopsWorkersAndKeepsFiles(t *testing.T) { default: } // A folder explicitly added during cancellation belongs to the next queue. - newFolder := t.TempDir() + newFolder := filepath.Clean(t.TempDir()) if err := e.Add(newFolder); err != nil { t.Fatal(err) } @@ -294,7 +323,7 @@ func TestClearQueueStopsWorkersAndKeepsFiles(t *testing.T) { } snapshot := e.Snapshot() if snapshot.Clearing || snapshot.Enabled || len(snapshot.Jobs) != 1 || snapshot.Jobs[0].Folder != newFolder { - t.Fatal("clear queue did not remove exactly the original jobs") + t.Fatalf("clear queue did not remove exactly the original jobs: clearing=%v enabled=%v jobs=%+v expectedFolder=%q", snapshot.Clearing, snapshot.Enabled, snapshot.Jobs, newFolder) } saved, err := st.Load() if err != nil || len(saved) != 1 || saved[0].Folder != newFolder { diff --git a/internal/engine/menu.go b/internal/engine/menu.go index 6f8891c..a72c6cc 100644 --- a/internal/engine/menu.go +++ b/internal/engine/menu.go @@ -33,6 +33,10 @@ func (e *Engine) SetMenu(id string, style model.MenuStyle, layout string, count s.Menu = style s.Layout = layout s.TitlesPerPage = count + if id != "" { + s.NoMenu = false + return e.SetJobSettings(id, s) + } return e.SetSettings(id, s) } diff --git a/internal/engine/queue_settings_test.go b/internal/engine/queue_settings_test.go new file mode 100644 index 0000000..ad66d6a --- /dev/null +++ b/internal/engine/queue_settings_test.go @@ -0,0 +1,113 @@ +package engine + +import ( + "context" + "path/filepath" + "testing" + "time" + + "easydvd/internal/media" + "easydvd/internal/model" + "easydvd/internal/store" +) + +func TestSavedDefaultsOnlyAffectNewJobs(t *testing.T) { + st, err := store.Open(filepath.Join(t.TempDir(), "q.db")) + if err != nil { + t.Fatal(err) + } + defer st.Close() + s := model.DefaultSettings(t.TempDir()) + custom := s + custom.Media, custom.OutputDir = "DVD-9", t.TempDir() + jobs := []model.Job{{ID: model.ID(), State: model.Ready, Settings: s}, {ID: model.ID(), State: model.Ready, Settings: custom}} + if err := st.Save(jobs); err != nil { + t.Fatal(err) + } + e, err := New(st, s, media.Tools{}) + if err != nil { + t.Fatal(err) + } + next := s + next.Standard, next.EncodingProfile, next.TitlesPerPage = "NTSC", model.ProfileQuality, 6 + if err := e.SetSettings("", next); err != nil { + t.Fatal(err) + } + if err := e.Add(t.TempDir()); err != nil { + t.Fatal(err) + } + snapshot := e.Snapshot() + if snapshot.Jobs[0].Settings != s || snapshot.Jobs[1].Settings != custom || snapshot.Jobs[2].Settings != next { + t.Fatal("saved defaults changed existing jobs or were not inherited by a new job") + } + e.Close() + e, err = New(st, s, media.Tools{}) + if err != nil { + t.Fatal(err) + } + defer e.Close() + snapshot = e.Snapshot() + if snapshot.Settings != next || snapshot.Jobs[0].Settings != s || snapshot.Jobs[1].Settings != custom { + t.Fatal("defaults and overrides did not survive restart independently") + } +} + +func TestRemoveSelectedJobsWaitsOnlyForTheirWorkers(t *testing.T) { + st, err := store.Open(filepath.Join(t.TempDir(), "q.db")) + if err != nil { + t.Fatal(err) + } + defer st.Close() + s := model.DefaultSettings(t.TempDir()) + jobs := []model.Job{{ID: model.ID(), State: model.Ready, Settings: s}, {ID: model.ID(), State: model.Ready, Settings: s}, {ID: model.ID(), State: model.Complete, Settings: s}} + if err := st.Save(jobs); err != nil { + t.Fatal(err) + } + e, err := New(st, s, media.Tools{}) + if err != nil { + t.Fatal(err) + } + defer e.Close() + if err := e.RemoveJobs([]string{jobs[0].ID, "missing"}); err == nil || len(e.Snapshot().Jobs) != 3 { + t.Fatal("stale selection was partially removed") + } + selected, cancelSelected := context.WithCancel(context.Background()) + defer cancelSelected() + other, cancelOther := context.WithCancel(context.Background()) + defer cancelOther() + e.mu.Lock() + e.jobs[0].State = model.Running + e.cancels[jobs[0].ID] = cancelSelected + e.scans[jobs[1].ID] = cancelOther + e.mu.Unlock() + done := make(chan error, 1) + go func() { done <- e.RemoveJobs([]string{jobs[0].ID, jobs[2].ID}) }() + select { + case <-selected.Done(): + case <-time.After(3 * time.Second): + t.Fatal("selected worker was not canceled") + } + if other.Err() != nil || len(e.Snapshot().Jobs) != 3 { + t.Fatal("removal canceled an unrelated worker or removed an active job too early") + } + select { + case <-done: + t.Fatal("removal did not wait for selected worker") + default: + } + e.mu.Lock() + delete(e.cancels, jobs[0].ID) + e.mu.Unlock() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + t.Fatal("removal waited for an unrelated worker") + } + saved, err := st.Load() + if err != nil || len(saved) != 1 || saved[0].ID != jobs[1].ID || other.Err() != nil { + t.Fatal("selected removal was not persisted correctly", err) + } +} diff --git a/internal/integration/autoplay_test.go b/internal/integration/autoplay_test.go new file mode 100644 index 0000000..f970229 --- /dev/null +++ b/internal/integration/autoplay_test.go @@ -0,0 +1,95 @@ +package integration + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "easydvd/internal/engine" + "easydvd/internal/model" + "easydvd/internal/process" + "easydvd/internal/store" +) + +func TestAutomaticMenuDefaultsAndMultiVideoAutoplay(t *testing.T) { + tools, ctx := issueTools(t) + dir := t.TempDir() + var paths []string + for i, size := range []string{"320x240", "426x240", "320x240"} { + path := filepath.Join(dir, fmt.Sprintf("film-%d.mp4", i+1)) + if err := process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=" + size + ":r=25", "-t", "2", "-c:v", "libx264", path}, process.Options{}); err != nil { + t.Fatal(err) + } + paths = append(paths, path) + } + s := model.DefaultSettings(dir) + s.KeepWork, s.Encoders = true, 1 + st, err := store.Open(filepath.Join(dir, "queue.db")) + if err != nil { + t.Fatal(err) + } + defer st.Close() + e, err := engine.New(st, s, tools) + if err != nil { + t.Fatal(err) + } + defer e.Close() + if err := e.AddFiles(paths); err != nil { + t.Fatal(err) + } + j := wait(t, e, func(s engine.Snapshot) bool { return s.Jobs[0].ScanComplete }).Jobs[0] + if j.Settings.NoMenu { + t.Fatal("multi-video job did not default to a menu") + } + next := j.Settings + next.NoMenu = true + if err := e.SetJobSettings(j.ID, next); err != nil { + t.Fatal(err) + } + e.Start() + j = wait(t, e, func(s engine.Snapshot) bool { + return s.Jobs[0].State == model.Complete || s.Jobs[0].State == model.Blocked + }).Jobs[0] + if j.State != model.Complete || len(j.Discs) != 1 { + t.Fatal("multi-video autoplay failed", j.Error) + } + authorDir := filepath.Join(s.WorkDir, "jobs", j.ID, "generation-"+j.Generation, "disc-001") + if pages, _ := filepath.Glob(filepath.Join(authorDir, "page-*")); len(pages) != 0 { + t.Fatal("autoplay rendered menu media", pages) + } + xml, err := os.ReadFile(filepath.Join(authorDir, "dvd.xml")) + if err != nil || strings.Contains(string(xml), "") != 3 { + t.Fatal(string(xml), err) + } + for i := 1; i <= 3; i++ { + if err := process.Run(ctx, tools.FFmpeg, []string{"-v", "error", "-xerror", "-f", "dvdvideo", "-title", fmt.Sprint(i), "-i", j.Discs[0].ISO, "-f", "null", "NUL"}, process.Options{}); err != nil { + t.Fatal(err) + } + } + if nav, vlc := os.Getenv("EASYDVD_NAVCHECK"), os.Getenv("EASYDVD_VLC_DIR"); nav != "" && vlc != "" { + var output bytes.Buffer + if err := process.Run(ctx, nav, []string{vlc, j.Discs[0].ISO, "--autoplay", "3"}, process.Options{Stdout: &output, Log: &output}); err != nil { + t.Fatal(output.String(), err) + } + t.Log(output.String()) + } + e.Pause() + if err := e.AddFiles(paths[:1]); err != nil { + t.Fatal(err) + } + second := wait(t, e, func(s engine.Snapshot) bool { return len(s.Jobs) == 2 && s.Jobs[1].ScanComplete }).Jobs[1] + if !second.Settings.NoMenu || second.NoMenuOverride != nil { + t.Fatal("single-video job did not default to automatic playback") + } + next = second.Settings + next.NoMenu = false + if err := e.SetJobSettings(second.ID, next); err != nil { + t.Fatal(err) + } + if e.Snapshot().Jobs[1].Settings.NoMenu { + t.Fatal("single-video menu override was not accepted") + } +} diff --git a/internal/media/author.go b/internal/media/author.go index bbecf3e..3f07c5e 100644 --- a/internal/media/author.go +++ b/internal/media/author.go @@ -20,6 +20,9 @@ func AuthorXML(videos []model.Video, pages []menu.Page, s model.Settings, dir st relative, _ := filepath.Rel(dir, v.Encoded) return fmt.Sprintf("jump title 1;\n", strings.ToLower(s.Standard), v.Aspect(), menu.Escape(filepath.ToSlash(relative))) } + if s.NoMenu { + return autoplayXML(videos, s, dir) + } var b strings.Builder b.WriteString("\ng0 = 0; g3 = 1024; jump vmgm menu 1;\n") aspect := s.Menu.Defaults().Aspect @@ -69,6 +72,35 @@ func AuthorXML(videos []model.Video, pages []menu.Page, s model.Settings, dir st return b.String() } +// Command-only VMGM chains route playback between titlesets, preserving mixed +// aspect ratios without a visible menu or any rendered menu media. Each chain +// contains one jump, so the DVD VM command limit does not grow with disc size. +func autoplayXML(videos []model.Video, s model.Settings, dir string) string { + var b strings.Builder + b.WriteString("jump title 1;") + fmt.Fprintf(&b, "") + for i, v := range videos { + relative, _ := filepath.Rel(dir, v.Encoded) + fmt.Fprintf(&b, "") + } + b.WriteString("\n") + return b.String() +} + func (t Tools) Author(ctx context.Context, j model.Job, disc model.Disc, total int, dir string, log io.Writer, stage func(string) error) (string, error) { if err := os.MkdirAll(dir, 0755); err != nil { return "", err @@ -90,9 +122,6 @@ func (t Tools) Author(ctx context.Context, j model.Job, disc model.Disc, total i if len(videos) == 0 { return "", fmt.Errorf("cannot author an empty disc") } - if j.Settings.NoMenu && (len(j.ActiveVideos()) != 1 || len(videos) != 1) { - return "", fmt.Errorf("no menu requires exactly one included video") - } var related []string for _, video := range videos { related = append(related, video.Encoded) diff --git a/internal/media/encode_test.go b/internal/media/encode_test.go index fa0e099..be448ba 100644 --- a/internal/media/encode_test.go +++ b/internal/media/encode_test.go @@ -87,3 +87,17 @@ func TestMenuFreeFirstPlay(t *testing.T) { t.Fatal(x) } } + +func TestMenuFreeMultipleTitlesKeepOrderAndAspect(t *testing.T) { + s := model.DefaultSettings(t.TempDir()) + s.NoMenu = true + x := AuthorXML([]model.Video{{Encoded: "a.mpg", DAR: 4.0 / 3}, {Encoded: "b.mpg", DAR: 16.0 / 9}, {Encoded: "c.mpg", DAR: 4.0 / 3}}, nil, s, ".") + for _, want := range []string{"jump title 1;", "
jump title 2;
", "
jump title 3;
", "call vmgm menu 2;", "call vmgm menu 3;", "exit;", "aspect=\"16:9\""} { + if !strings.Contains(x, want) { + t.Fatal(want, x) + } + } + if strings.Count(x, "") != 3 || strings.Contains(x, "= 0 && target >= 0 { - for i := min(anchor, target); i <= max(anchor, target); i++ { - // Shift always selects the inclusive range, even if the endpoint was selected. - u.selectedFiles[j.Videos[i].ID] = true - } - u.refreshFileSelection() - u.files.Refresh() - return - } - } +func (u *window) selectFile(id string) { u.selectFiles(id, selectionModifiers(u.app)) } + +func (u *window) selectFiles(id string, modifiers fyne.KeyModifier) { + j := u.selectedJob() + if j == nil { + return } - u.selectionAnchor = id - if selected { - u.selectedFiles[id] = true - } else { - delete(u.selectedFiles, id) + ids := make([]string, len(j.Videos)) + for i, v := range j.Videos { + ids[i] = v.ID + } + if !selectItems(ids, u.selectedFiles, &u.selectionAnchor, id, modifiers) { + return } + u.win.Canvas().Focus(u.files) u.refreshFileSelection() u.files.Refresh() } - func (u *window) refreshFileSelection() { j := u.selectedJob() jobID := "" @@ -140,10 +132,6 @@ func (u *window) refreshFileSelection() { } } u.selectionCount.SetText(fmt.Sprintf("%d selected", count)) - change := u.selectAll.OnChanged - u.selectAll.OnChanged = nil - u.selectAll.SetChecked(total > 0 && count == total) - u.selectAll.OnChanged = change enabled(u.selectAll, total > 0) enabled(u.excludeSelected, filesEditable(j) && !u.snapshot.Clearing && included > 0) enabled(u.includeSelected, filesEditable(j) && !u.snapshot.Clearing && excluded > 0) @@ -204,7 +192,6 @@ type fileRow struct { index int selected bool background *canvas.Rectangle - selectFile *widget.Check title, state, duration *widget.Label warning, edit, revert, toggle *fileAction content fyne.CanvasObject @@ -213,7 +200,6 @@ type fileRow struct { func newFileRow(u *window) *fileRow { r := &fileRow{u: u, background: canvas.NewRectangle(color.Transparent)} r.ExtendBaseWidget(r) - r.selectFile = widget.NewCheck("", nil) r.title = widget.NewLabel("Video title") r.title.Truncation = fyne.TextTruncateEllipsis r.state = widget.NewLabel("") @@ -225,7 +211,7 @@ func newFileRow(u *window) *fileRow { // Keep a fixed warning slot so actions stay aligned across healthy and failed rows. warningSlot := container.NewGridWrap(r.warning.MinSize(), r.warning) actions := container.NewHBox(r.state, r.duration, warningSlot, r.edit, r.revert, r.toggle) - r.content = container.NewStack(r.background, container.NewBorder(nil, nil, r.selectFile, actions, r.title)) + r.content = container.NewStack(r.background, container.NewBorder(nil, nil, nil, actions, r.title)) return r } @@ -234,7 +220,7 @@ func (r *fileRow) CreateRenderer() fyne.WidgetRenderer { } func (r *fileRow) Tapped(*fyne.PointEvent) { - r.u.setFileSelected(r.id, !r.u.selectedFiles[r.id]) + r.u.selectFile(r.id) } func (r *fileRow) update(j *model.Job, index int) { @@ -245,9 +231,6 @@ func (r *fileRow) update(j *model.Job, index int) { } } r.id, r.index, r.selected = v.ID, index, r.u.selectedFiles[v.ID] - r.selectFile.OnChanged = nil - r.selectFile.SetChecked(r.selected) - r.selectFile.OnChanged = func(checked bool) { r.u.setFileSelected(v.ID, checked) } r.title.SetText(v.Label) edited := v.Label != v.OriginalLabel() r.title.TextStyle = fyne.TextStyle{Italic: edited, Strikethrough: v.Excluded} diff --git a/internal/ui/files_test.go b/internal/ui/files_test.go index 07b1ec9..f418bfe 100644 --- a/internal/ui/files_test.go +++ b/internal/ui/files_test.go @@ -20,7 +20,7 @@ import ( "fyne.io/fyne/v2/widget" ) -func fileListFixture(t *testing.T) *window { +func fileListFixture(t *testing.T, extra ...model.Job) *window { t.Helper() a := test.NewApp() t.Cleanup(a.Quit) @@ -39,7 +39,15 @@ func fileListFixture(t *testing.T) *window { j.Videos[2].Excluded = true j.Videos[3].Error = "The video could not be inspected. The file is incomplete or damaged. Try a fresh copy of the source file, or exclude this file from the DVD set." j.Videos[3].Duration = 0 - if err := st.Save([]model.Job{j}); err != nil { + for i := range extra { + if extra[i].ID == "" { + extra[i].ID = model.ID() + } + if extra[i].Settings.Standard == "" { + extra[i].Settings = s + } + } + if err := st.Save(append([]model.Job{j}, extra...)); err != nil { t.Fatal(err) } e, err := engine.New(st, s, media.Tools{}) @@ -115,9 +123,9 @@ func TestCompactHeaderAndFileRows(t *testing.T) { if r.warning.Visible() || r.title.TextStyle.Italic || r.title.TextStyle.Strikethrough || r.state.Text != "" || !r.revert.Disabled() { t.Fatal("recycled healthy row retained old state") } - test.Tap(r.selectFile) + test.Tap(r) if !u.selectedFiles["0"] || u.selectedFiles["3"] { - t.Fatal("recycled checkbox selected the wrong file") + t.Fatal("recycled row selected the wrong file") } } @@ -126,7 +134,7 @@ func TestFileSelectionBulkAndPerRowActions(t *testing.T) { for _, index := range []int{0, 1} { r := newFileRow(u) r.update(u.selectedJob(), index) - test.Tap(r.selectFile) + u.selectFiles(r.id, fyne.KeyModifierControl) } if u.selectionCount.Text != "2 selected" || u.excludeSelected.Disabled() { t.Fatal("multi-selection did not enable bulk exclusion") @@ -158,11 +166,11 @@ func TestFileSelectionBulkAndPerRowActions(t *testing.T) { if len(u.selectedFiles) != len(u.selectedJob().Videos) { t.Fatal("select all missed files outside the visible rows") } - test.Tap(u.selectAll) - if len(u.selectedFiles) != 0 || !u.excludeSelected.Disabled() { - t.Fatal("deselect all did not clear the selection") + u.selectFiles("0", 0) + if len(u.selectedFiles) != 1 { + t.Fatal("plain click did not replace Select all") } - u.setFileSelected("0", true) + u.selectFiles("0", 0) u.snapshot.Jobs = append(u.snapshot.Jobs, model.Job{ID: "another", State: model.Ready}) u.selected = "another" u.refreshFileSelection() @@ -173,20 +181,20 @@ func TestFileSelectionBulkAndPerRowActions(t *testing.T) { func TestShiftSelectionUsesInclusiveAnchorAcrossRecycledRows(t *testing.T) { u := fileListFixture(t) - u.selectFileRange("4", true, false) - u.selectFileRange("16", true, true) + u.selectFiles("4", 0) + u.selectFiles("16", fyne.KeyModifierShift) if len(u.selectedFiles) != 13 { t.Fatal(u.selectedFiles) } - u.selectFileRange("1", true, true) - if len(u.selectedFiles) != 16 || u.selectionAnchor != "4" { + u.selectFiles("1", fyne.KeyModifierShift) + if len(u.selectedFiles) != 4 || u.selectionAnchor != "4" { t.Fatal("reverse range moved the anchor", u.selectedFiles) } - u.selectFileRange("10", false, false) - if u.selectedFiles["10"] || u.selectionAnchor != "10" { + u.selectFiles("10", 0) + if !u.selectedFiles["10"] || len(u.selectedFiles) != 1 || u.selectionAnchor != "10" { t.Fatal("plain click did not reset anchor") } - u.selectFileRange("12", false, true) + u.selectFiles("12", fyne.KeyModifierShift) if !u.selectedFiles["10"] || !u.selectedFiles["11"] || !u.selectedFiles["12"] { t.Fatal("selected endpoint toggled range off") } @@ -267,8 +275,8 @@ func TestFileListPreview(t *testing.T) { t.Skip("visual preview not requested") } u := fileListFixture(t) - u.setFileSelected("0", true) - u.setFileSelected("1", true) + u.selectFiles("0", 0) + u.selectFiles("1", fyne.KeyModifierControl) for _, appearance := range []string{"Light", "Dark"} { u.applyTheme(appearance) u.refresh() @@ -282,7 +290,7 @@ func TestFileListPreview(t *testing.T) { f.Close() // Also inspect unselected stripes, warnings and many recycled rows together. u.win.Resize(fyne.NewSize(1160, 980)) - u.selectAll.SetChecked(false) + clear(u.selectedFiles) u.refresh() f, err = os.Create(filepath.Join(dir, "file-list-"+appearance+"-expanded.png")) if err != nil { diff --git a/internal/ui/header_layout.go b/internal/ui/header_layout.go new file mode 100644 index 0000000..76b3855 --- /dev/null +++ b/internal/ui/header_layout.go @@ -0,0 +1,92 @@ +package ui + +import ( + "image/color" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/theme" + "fyne.io/fyne/v2/widget" +) + +// The header keeps the former collapsed height regardless of paths or state. +type fixedHeaderLayout struct{} + +func (fixedHeaderLayout) MinSize(objects []fyne.CanvasObject) fyne.Size { + width := float32(0) + for _, object := range objects { + width = max(width, object.MinSize().Width) + } + return fyne.NewSize(width, 80) +} + +// Keep the edit icon beside the visible title instead of at the far edge of +// the header. Long titles truncate before reaching the icon. +type titleEditLayout struct{ title *widget.Label } + +func (l titleEditLayout) MinSize(objects []fyne.CanvasObject) fyne.Size { + return fyne.NewSize(objects[0].MinSize().Width+32, 28) +} +func (l titleEditLayout) Layout(objects []fyne.CanvasObject, size fyne.Size) { + title, edit := objects[0], objects[1] + textWidth := fyne.MeasureText(l.title.Text, 14, l.title.TextStyle).Width + 1 + width := min(textWidth, max(0, size.Width-32)) + height := title.MinSize().Height + title.Move(fyne.NewPos(0, (size.Height-height)/2)) + title.Resize(fyne.NewSize(width, height)) + edit.Move(fyne.NewPos(width+4, (size.Height-28)/2)) + edit.Resize(fyne.NewSize(28, 28)) +} +func (fixedHeaderLayout) Layout(objects []fyne.CanvasObject, size fyne.Size) { + for _, object := range objects { + object.Resize(size) + } +} + +type tightHeaderLayout struct{} + +func (tightHeaderLayout) MinSize(objects []fyne.CanvasObject) fyne.Size { + size := fyne.NewSize(0, 0) + for i, object := range objects { + child := object.MinSize() + size.Width = max(size.Width, child.Width) + size.Height += child.Height + if i > 0 { + size.Height += 2 + } + } + size.Width += 8 + return size +} +func (l tightHeaderLayout) Layout(objects []fyne.CanvasObject, size fyne.Size) { + y := max(0, (size.Height-l.MinSize(objects).Height)/2) + for _, object := range objects { + height := object.MinSize().Height + object.Move(fyne.NewPos(8, y)) + object.Resize(fyne.NewSize(max(0, size.Width-8), height)) + y += height + 2 + } +} + +// Remove label padding only within the information column. Colors still +// follow the app theme, including a later light/dark appearance change. +type headerTextTheme struct{ size float32 } + +func (headerTextTheme) Color(n fyne.ThemeColorName, v fyne.ThemeVariant) color.Color { + return fyne.CurrentApp().Settings().Theme().Color(n, v) +} +func (headerTextTheme) Font(s fyne.TextStyle) fyne.Resource { + return fyne.CurrentApp().Settings().Theme().Font(s) +} +func (headerTextTheme) Icon(n fyne.ThemeIconName) fyne.Resource { + return fyne.CurrentApp().Settings().Theme().Icon(n) +} +func (h headerTextTheme) Size(n fyne.ThemeSizeName) float32 { + switch n { + case theme.SizeNameInnerPadding: + return 0 + case theme.SizeNameText: + return h.size + default: + return fyne.CurrentApp().Settings().Theme().Size(n) + } +} diff --git a/internal/ui/job_header.go b/internal/ui/job_header.go index ce3e933..0303bec 100644 --- a/internal/ui/job_header.go +++ b/internal/ui/job_header.go @@ -9,6 +9,7 @@ import ( "fyne.io/fyne/v2" "fyne.io/fyne/v2/container" "fyne.io/fyne/v2/dialog" + "fyne.io/fyne/v2/layout" "fyne.io/fyne/v2/theme" "fyne.io/fyne/v2/widget" ) @@ -16,109 +17,50 @@ import ( func (u *window) buildJobHeader() *fyne.Container { u.title = widget.NewLabelWithStyle("", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}) u.title.Truncation = fyne.TextTruncateEllipsis - u.jobState = widget.NewLabel("") + u.jobOutput = widget.NewLabel("") + u.jobOutput.Truncation = fyne.TextTruncateEllipsis u.jobSummary = widget.NewLabel("") u.jobSummary.Truncation = fyne.TextTruncateEllipsis u.source = widget.NewLabel("") u.source.Truncation = fyne.TextTruncateEllipsis - u.meta = widget.NewLabel("") - u.meta.Wrapping = fyne.TextWrapWord - u.stage = widget.NewLabel("") - u.stage.Wrapping = fyne.TextWrapWord - u.activity = widget.NewLabel("") - u.activity.Truncation = fyne.TextTruncateEllipsis - u.progress = widget.NewProgressBar() - u.progress.Hide() - u.scanProgress = widget.NewProgressBarInfinite() - u.scanProgress.Stop() - u.scanProgress.Hide() - u.activity.Hide() - u.headerToggle = widget.NewButtonWithIcon("More info", theme.MoveDownIcon(), func() { - u.setHeaderExpanded(!u.headerExpanded) - }) - u.headerToggle.Importance = widget.LowImportance u.jobWarning = widget.NewButtonWithIcon("Needs attention", theme.NewWarningThemedResource(theme.WarningIcon()), u.jobDetails) u.jobWarning.Importance = widget.LowImportance u.jobWarning.Hide() - rename := widget.NewButtonWithIcon("Set title", theme.DocumentCreateIcon(), u.rename) + u.renameJob = newFileAction(u, theme.DocumentCreateIcon(), "Edit job title") + u.renameJob.OnTapped = u.rename u.settings = widget.NewButton("Job settings", func() { if j := u.selectedJob(); j != nil { u.settingsDialog(j.ID, j.Settings) } }) - u.preview = widget.NewButtonWithIcon("Menu", theme.SettingsIcon(), func() { - if j := u.selectedJob(); j != nil { - u.menuSettings(j.ID) - } - }) - u.profileToggle = widget.NewRadioGroup([]string{model.ProfileBalanced, model.ProfileQuality}, func(value string) { - if u.profileSync { - return - } - j := u.selectedJob() - if j == nil || j.Locked || j.State == model.Complete || j.State == model.Running || u.snapshot.Clearing { - return - } - next, id := j.Settings, j.ID - next.EncodingProfile = value - u.action(func() error { return u.engine.SetSettings(id, next) }) - }) - u.profileToggle.Horizontal, u.profileToggle.Required = true, true open := widget.NewButtonWithIcon("Open output", theme.FolderOpenIcon(), func() { if j := u.selectedJob(); j != nil { - path := j.OutputPath - if path == "" { - path = j.Settings.OutputDir - } + path := jobOutputFolder(*j) u.action(func() error { return platform.OpenFolder(path) }) } }) - u.headerInfo = container.NewVBox(u.source, u.meta, u.stage, container.NewHBox(rename, u.settings)) - u.headerInfo.Hide() - titleRow := container.NewBorder(nil, nil, nil, container.NewHBox(u.jobState, u.jobWarning, u.headerToggle), u.title) - summaryRow := container.NewBorder(nil, nil, nil, container.NewHBox(u.profileToggle, u.preview, open), u.jobSummary) - u.jobHeader = container.NewVBox(titleRow, summaryRow, u.activity, u.progress, u.scanProgress, u.headerInfo, widget.NewSeparator()) + titleRow := container.New(titleEditLayout{title: u.title}, container.NewThemeOverride(u.title, headerTextTheme{size: 14}), u.renameJob) + info := container.New(tightHeaderLayout{}, + titleRow, + container.NewThemeOverride(u.source, headerTextTheme{size: 12}), + container.NewThemeOverride(u.jobOutput, headerTextTheme{size: 12}), + container.NewThemeOverride(u.jobSummary, headerTextTheme{size: 12})) + controls := container.NewGridWithRows(2, + container.NewHBox(layout.NewSpacer(), u.jobWarning), + container.NewHBox(u.settings, open)) + body := container.New(fixedHeaderLayout{}, container.NewBorder(nil, nil, nil, controls, info)) + u.jobHeader = container.NewVBox(body, widget.NewSeparator()) return u.jobHeader } -func (u *window) setHeaderExpanded(expanded bool) { - u.headerExpanded = expanded - if expanded { - u.headerInfo.Show() - u.headerToggle.SetText("Less info") - u.headerToggle.SetIcon(theme.MoveUpIcon()) - } else { - u.headerInfo.Hide() - u.headerToggle.SetText("More info") - u.headerToggle.SetIcon(theme.MoveDownIcon()) - } - if u.details != nil { - u.details.Refresh() - } -} - func (u *window) refreshJobHeader(j *model.Job) { if j == nil { - u.profileToggle.Disable() - u.headerJob = "" - u.setHeaderExpanded(false) - u.progress.Hide() - u.scanProgress.Stop() - u.scanProgress.Hide() - u.activity.Hide() return } - if u.headerJob != j.ID { - u.headerJob = j.ID - u.setHeaderExpanded(false) - } u.title.SetText(j.Title) - u.profileSync = true - u.profileToggle.SetSelected(j.Settings.Profile()) - u.profileSync = false - enabled(u.profileToggle, !j.Locked && j.State != model.Complete && j.State != model.Running && !u.snapshot.Clearing) - u.jobState.SetText(string(j.State)) + enabled(u.renameJob, filesEditable(j) && !u.snapshot.Clearing) u.source.SetText(j.Folder) + u.jobOutput.SetText("Output: " + jobOutputFolder(*j)) discs := fmt.Sprintf("~%d DVDs", j.EstimatedDiscs) if j.EstimatedDiscs == 1 { discs = "~1 DVD" @@ -130,20 +72,6 @@ func (u *window) refreshJobHeader(j *model.Job) { } } u.jobSummary.SetText(fmt.Sprintf("%d/%d videos · %s · %s", len(j.ActiveVideos()), len(j.Videos), model.DurationString(j.Duration()), discs)) - u.meta.SetText(fmt.Sprintf("%d included / %d inspected · %s · %s · %s\n%s · %s", len(j.ActiveVideos()), len(j.Videos), model.DurationString(j.Duration()), j.Settings.Standard, j.Settings.Media, discs, j.Settings.Packing)) - message := j.Stage - if j.Error != "" { - message += "\n" + j.Error - } - if runes := []rune(message); len(runes) > 300 { - message = string(runes[:300]) + "… (see Details)" - } - u.stage.SetText(message) - if message == "" { - u.stage.Hide() - } else { - u.stage.Show() - } issues := 0 for _, v := range j.Videos { if v.Error != "" && !v.Excluded { @@ -162,28 +90,16 @@ func (u *window) refreshJobHeader(j *model.Job) { } else { u.jobWarning.Hide() } - u.progress.SetValue(j.Progress) - if j.State == model.Running || (j.State == model.Paused && j.Progress > 0) { - u.progress.Show() - } else { - u.progress.Hide() - } - if j.State == model.Scanning { - u.scanProgress.Show() - u.scanProgress.Start() - } else { - u.scanProgress.Stop() - u.scanProgress.Hide() - } - if (j.State == model.Scanning || j.State == model.Running) && j.Stage != "" { - u.activity.SetText(j.Stage) - u.activity.Show() - } else { - u.activity.Hide() - } u.details.Refresh() } +func jobOutputFolder(j model.Job) string { + if j.OutputPath != "" { + return j.OutputPath + } + return j.Settings.OutputDir +} + func (u *window) clearQueue() { if len(u.snapshot.Jobs) == 0 || u.snapshot.Clearing { return diff --git a/internal/ui/job_header_test.go b/internal/ui/job_header_test.go index c0f0ede..9e68d34 100644 --- a/internal/ui/job_header_test.go +++ b/internal/ui/job_header_test.go @@ -14,98 +14,122 @@ import ( "fyne.io/fyne/v2/widget" ) -func TestJobHeaderCollapsedAndExpandable(t *testing.T) { +func TestJobHeaderHasFixedCompactInformation(t *testing.T) { u := fileListFixture(t) - if u.headerExpanded || u.headerInfo.Visible() || u.progress.Visible() || u.scanProgress.Visible() || u.activity.Visible() { - t.Fatal("ready job header does not start collapsed without progress") + height := u.jobHeader.Size().Height + if height > 100 || u.files.Size().Height < 300 { + t.Fatalf("header is too tall: %v", u.jobHeader.Size()) + } + if !u.source.Visible() || u.source.Text != u.selectedJob().Folder || !u.settings.Visible() || !u.renameJob.Visible() { + t.Fatal("compact header hides job information or actions") + } + if !u.jobOutput.Visible() || u.jobOutput.Text != "Output: "+u.selectedJob().Settings.OutputDir { + t.Fatal("output folder is not shown in the compact header") + } + titlePos := u.app.Driver().AbsolutePositionForObject(u.title) + penPos := u.app.Driver().AbsolutePositionForObject(u.renameJob) + gap := penPos.X - titlePos.X - u.title.Size().Width + if gap < 0 || gap > 8 { + t.Fatalf("title-edit icon is not beside the title: gap=%v", gap) + } + var openOutput bool + var outputButton *widget.Button + walkFileTestObjects(u.jobHeader, func(object fyne.CanvasObject) { + if b, ok := object.(*widget.Button); ok && b.Text == "Open output" { + openOutput = true + outputButton = b + } + if b, ok := object.(*widget.Button); ok && b.Text == "Menu" { + t.Fatal("redundant menu button is still in the header") + } + if _, ok := object.(*widget.RadioGroup); ok { + t.Fatal("encoding controls are still in the header") + } + if label, ok := object.(*widget.Label); ok && label.Text == string(u.selectedJob().State) { + t.Fatal("job status is repeated in the header") + } + }) + if !openOutput { + t.Fatal("output action has no text label") } - collapsed := u.jobHeader.MinSize().Height - if collapsed > 100 || u.files.Size().Height < 300 { - t.Fatalf("collapsed header consumes too much space: header=%v list=%v", u.jobHeader.MinSize(), u.files.Size()) + settingsPos := u.app.Driver().AbsolutePositionForObject(u.settings) + outputPos := u.app.Driver().AbsolutePositionForObject(outputButton) + if settingsPos.Y != outputPos.Y { + t.Fatal("Job settings and Open output are not on the same row") } if !u.jobWarning.Visible() || u.jobWarning.Text != "1 file issue" { - t.Fatal("collapsing the header hid the file issue") - } - test.Tap(u.headerToggle) - if !u.headerExpanded || !u.headerInfo.Visible() || u.jobHeader.MinSize().Height <= collapsed+100 || u.source.Text != u.selectedJob().Folder { - t.Fatal("expanded job information is missing") - } + t.Fatal("file issue was hidden") + } + u.snapshot.Jobs[0].Folder = "C:/A very long source path containing a family video collection and several nested folders" + u.snapshot.Jobs[0].Settings.Standard = "NTSC" + u.snapshot.Jobs[0].Settings.Media = "DVD-9" + u.snapshot.Jobs[0].Settings.Packing = "Space efficiency" + u.snapshot.Jobs[0].Error = "A detailed error that must never expand the job header" + u.snapshot.Jobs[0].OutputPath = filepath.Join(t.TempDir(), "completed-output") u.refresh() - if !u.headerExpanded { - t.Fatal("routine refresh collapsed the open header") + if u.jobOutput.Text != "Output: "+u.snapshot.Jobs[0].OutputPath { + t.Fatal("completed job does not show its actual output folder") } - test.Tap(u.headerToggle) - if u.headerExpanded || u.headerInfo.Visible() || u.jobHeader.Size().Height > 100 || u.files.Size().Height < 300 { - t.Fatal("header cannot collapse again") + if u.jobHeader.Size().Height != height { + t.Fatal("header resized or lost format information") } - test.Tap(u.headerToggle) other := u.snapshot.Jobs[0].Clone() other.ID = "another-job" u.snapshot.Jobs = append(u.snapshot.Jobs, other) u.selected = other.ID u.refresh() - if u.headerExpanded || u.headerInfo.Visible() { - t.Fatal("a newly selected job did not default to collapsed") + if u.jobHeader.Size().Height != height { + t.Fatal("selecting another job changed header height") } } -func TestJobHeaderProgressFollowsActivity(t *testing.T) { +func TestToolsUsesOnlyExclamationSymbol(t *testing.T) { + u := fileListFixture(t) + var symbol bool + walkFileTestObjects(u.win.Content(), func(object fyne.CanvasObject) { + if b, ok := object.(*fileAction); ok && b.hint == "Media tools" { + if b.Text != "!" || b.Icon != nil { + t.Fatal("tools control is not symbol-only") + } + symbol = true + } + if b, ok := object.(*widget.Button); ok && b.Text == "Tools" { + t.Fatal("old Tools label is still visible") + } + }) + if !symbol { + t.Fatal("media tools control missing") + } +} +func TestFooterProgressFollowsActivity(t *testing.T) { u := fileListFixture(t) for _, tc := range []struct { - state model.State - progress float64 - bar, scanning, activity bool + state model.State + progress float64 + visible bool }{ - {model.Scanning, 0, false, true, true}, - {model.Ready, 0, false, false, false}, - {model.Running, 0, true, false, true}, - {model.Running, .45, true, false, true}, - {model.Paused, .45, true, false, false}, - {model.Paused, 0, false, false, false}, - {model.Blocked, 0, false, false, false}, - {model.Canceled, .3, false, false, false}, - {model.Complete, 1, false, false, false}, + {model.Scanning, 0, true}, + {model.Ready, 0, false}, + {model.Running, 0, true}, + {model.Running, .45, true}, + {model.Paused, .45, true}, + {model.Paused, 0, false}, + {model.Blocked, 0, false}, + {model.Canceled, .3, false}, + {model.Complete, 1, false}, } { u.snapshot.Jobs[0].State = tc.state u.snapshot.Jobs[0].Progress = tc.progress u.refresh() - if u.progress.Visible() != tc.bar || u.scanProgress.Visible() != tc.scanning || u.scanProgress.Running() != tc.scanning || u.activity.Visible() != tc.activity { + if u.footerProgress.Visible() != tc.visible || u.jobHeader.Size().Height > 100 { t.Fatalf("incorrect progress visibility for %s at %v", tc.state, tc.progress) } } } -func TestJobHeaderProfilePersistsAndLocks(t *testing.T) { - u := fileListFixture(t) - if u.profileToggle.Selected != model.ProfileBalanced || u.profileToggle.Disabled() { - t.Fatal("Balanced toggle is not available") - } - u.profileToggle.SetSelected(model.ProfileQuality) - deadline := time.Now().Add(3 * time.Second) - for u.engine.Snapshot().Jobs[0].Settings.Profile() != model.ProfileQuality { - if time.Now().After(deadline) { - t.Fatal("job profile was not saved") - } - time.Sleep(5 * time.Millisecond) - } - if u.engine.Snapshot().Settings.Profile() != model.ProfileBalanced { - t.Fatal("job toggle changed defaults") - } - u.snapshot = u.engine.Snapshot() - u.refresh() - if u.profileToggle.Selected != model.ProfileQuality { - t.Fatal("refresh lost the selected profile") - } - u.snapshot.Jobs[0].Locked = true - u.refresh() - if !u.profileToggle.Disabled() { - t.Fatal("started job still allows profile changes") - } -} - func TestClearQueueConfirmationAndEmptyState(t *testing.T) { u := fileListFixture(t) - u.setFileSelected("0", true) + u.selectFiles("0", 0) if u.clear.Disabled() { t.Fatal("clear queue is disabled for a populated queue") } @@ -156,21 +180,14 @@ func TestJobHeaderPreview(t *testing.T) { u := fileListFixture(t) for _, appearance := range []string{"Light", "Dark"} { u.applyTheme(appearance) - for _, expanded := range []bool{false, true} { - u.setHeaderExpanded(expanded) - u.refresh() - mode := "collapsed" - if expanded { - mode = "expanded" - } - f, err := os.Create(filepath.Join(dir, "job-header-"+appearance+"-"+mode+".png")) - if err != nil { - t.Fatal(err) - } - if err := png.Encode(f, u.win.Canvas().Capture()); err != nil { - t.Fatal(err) - } - f.Close() + u.refresh() + f, err := os.Create(filepath.Join(dir, "job-header-"+appearance+"-fixed.png")) + if err != nil { + t.Fatal(err) + } + if err := png.Encode(f, u.win.Canvas().Capture()); err != nil { + t.Fatal(err) } + f.Close() } } diff --git a/internal/ui/jobs.go b/internal/ui/jobs.go new file mode 100644 index 0000000..b6110f0 --- /dev/null +++ b/internal/ui/jobs.go @@ -0,0 +1,286 @@ +package ui + +import ( + "fmt" + "image/color" + "math" + + "easydvd/internal/model" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/canvas" + "fyne.io/fyne/v2/container" + "fyne.io/fyne/v2/dialog" + "fyne.io/fyne/v2/layout" + "fyne.io/fyne/v2/theme" + "fyne.io/fyne/v2/widget" +) + +type jobList struct { + widget.List + u *window +} + +func (l *jobList) TypedKey(event *fyne.KeyEvent) { + if event.Name == fyne.KeyDelete { + l.u.removeSelectedJobs() + return + } + l.List.TypedKey(event) +} + +func (l *jobList) TypedShortcut(shortcut fyne.Shortcut) { + if _, ok := shortcut.(*fyne.ShortcutSelectAll); ok { + l.u.selectAllJobs() + } +} + +func (u *window) buildJobList() fyne.CanvasObject { + u.selectedJobs = make(map[string]bool) + u.queue = &jobList{u: u} + u.queue.Length = func() int { return len(u.snapshot.Jobs) } + u.queue.CreateItem = func() fyne.CanvasObject { return newJobTile(u) } + u.queue.UpdateItem = func(i widget.ListItemID, object fyne.CanvasObject) { + if i < len(u.snapshot.Jobs) { + object.(*jobTile).update(u.snapshot.Jobs[i]) + } + } + u.queue.HideSeparators = true + u.queue.ExtendBaseWidget(u.queue) + u.queue.OnSelected = func(i widget.ListItemID) { + if i < len(u.snapshot.Jobs) { + id := u.snapshot.Jobs[i].ID + u.selectJob(id) + u.queue.Unselect(i) + } + } + u.jobSelectAll = widget.NewButton("Select all", u.selectAllJobs) + u.jobSelectAll.Importance = widget.LowImportance + u.jobSelectionCount = widget.NewLabel("0 selected") + u.up = widget.NewButtonWithIcon("", theme.MoveUpIcon(), func() { id := u.selected; u.action(func() error { u.engine.Move(id, -1); return nil }) }) + u.down = widget.NewButtonWithIcon("", theme.MoveDownIcon(), func() { id := u.selected; u.action(func() error { u.engine.Move(id, 1); return nil }) }) + u.remove = widget.NewButtonWithIcon("Remove selected", theme.DeleteIcon(), u.removeSelectedJobs) + u.clear = widget.NewButtonWithIcon("Clear queue", theme.DeleteIcon(), u.clearQueue) + heading := container.NewBorder(nil, nil, nil, u.clear, widget.NewLabelWithStyle("Queue", fyne.TextAlignLeading, fyne.TextStyle{Bold: true})) + selection := container.NewHBox(u.jobSelectAll, layout.NewSpacer(), u.jobSelectionCount) + return container.NewBorder(container.NewVBox(heading, selection), container.NewHBox(u.up, u.down, layout.NewSpacer(), u.remove), nil, nil, u.queue) +} + +func (u *window) selectAllJobs() { + for _, j := range u.snapshot.Jobs { + u.selectedJobs[j.ID] = true + } + u.win.Canvas().Focus(u.queue) + u.refreshJobSelection() + u.queue.Refresh() +} + +func (u *window) selectJob(id string) { u.selectJobs(id, selectionModifiers(u.app)) } + +func (u *window) selectJobs(id string, modifiers fyne.KeyModifier) { + ids := make([]string, len(u.snapshot.Jobs)) + target := -1 + for i, j := range u.snapshot.Jobs { + ids[i] = j.ID + if j.ID == id { + target = i + } + } + if !selectItems(ids, u.selectedJobs, &u.jobSelectionAnchor, id, modifiers) { + return + } + u.selected = id + u.win.Canvas().Focus(u.queue) + u.queue.Highlight(target) + u.refresh() +} + +func (u *window) refreshJobSelection() { + valid := make(map[string]bool, len(u.snapshot.Jobs)) + for _, j := range u.snapshot.Jobs { + valid[j.ID] = true + } + for id := range u.selectedJobs { + if !valid[id] { + delete(u.selectedJobs, id) + } + } + if !valid[u.jobSelectionAnchor] { + u.jobSelectionAnchor = "" + } + count := len(u.selectedJobs) + u.jobSelectionCount.SetText(fmt.Sprintf("%d selected", count)) + enabled(u.jobSelectAll, len(u.snapshot.Jobs) > 0 && !u.snapshot.Clearing) + enabled(u.remove, count > 0 && !u.snapshot.Clearing) +} + +func (u *window) removeSelectedJobs() { + var ids []string + for _, j := range u.snapshot.Jobs { + if u.selectedJobs[j.ID] { + ids = append(ids, j.ID) + } + } + u.removeJobs(ids) +} + +func (u *window) removeJobs(ids []string) { + if len(ids) == 0 || u.snapshot.Clearing { + return + } + active := false + for _, j := range u.snapshot.Jobs { + for _, id := range ids { + if id == j.ID && (u.snapshot.Busy[id] || j.State == model.Running || j.State == model.Scanning) { + active = true + } + } + } + remove := func() { u.action(func() error { return u.engine.RemoveJobs(ids) }) } + if active { + d := dialog.NewConfirm("Stop and remove jobs?", fmt.Sprintf("Stop active work and remove %d selected jobs? Source and output files will be kept.", len(ids)), func(ok bool) { + if ok { + remove() + } + }, u.win) + d.SetConfirmText("Stop and remove") + d.Show() + } else { + remove() + } +} + +// The engine retains Needs attention for recoverable failures. Presentation +// distinguishes a failed processing attempt from files that need user input. +func jobAppearance(j model.Job) (string, fyne.ThemeColorName) { + if j.State == model.Blocked && (j.Locked || j.Stage == "Folder scan failed") { + return "Failed", theme.ColorNameError + } + for _, v := range j.Videos { + if v.Error != "" && !v.Excluded && (j.State == model.Ready || j.State == model.Blocked) { + return "Needs attention", theme.ColorNameWarning + } + } + switch j.State { + case model.Ready: + return "Ready", theme.ColorNameForeground + case model.Running: + return "Running", theme.ColorNamePrimary + case model.Complete: + return "Completed", theme.ColorNameSuccess + case model.Blocked: + return "Needs attention", theme.ColorNameWarning + case model.Scanning: + return "Scanning", theme.ColorNamePrimary + default: + return string(j.State), theme.ColorNameForeground + } +} + +type jobTile struct { + widget.BaseWidget + u *window + id, fullTitle string + background *canvas.Rectangle + stripe *canvas.Rectangle + active *canvas.Rectangle + title, state *canvas.Text + close *fileAction +} + +func newJobTile(u *window) *jobTile { + r := &jobTile{u: u, background: canvas.NewRectangle(color.Transparent), stripe: canvas.NewRectangle(color.Transparent), active: canvas.NewRectangle(color.Transparent)} + r.ExtendBaseWidget(r) + r.title = canvas.NewText("Folder", theme.ForegroundColor()) + r.title.TextSize, r.title.TextStyle.Bold = 14, true + r.state = canvas.NewText("Ready", theme.ForegroundColor()) + r.state.TextSize = 12 + r.close = newFileAction(u, theme.CancelIcon(), "Remove job") + r.active.StrokeWidth, r.active.CornerRadius = 1, 3 + return r +} + +func (r *jobTile) Tapped(*fyne.PointEvent) { r.u.selectJob(r.id) } + +func (r *jobTile) update(j model.Job) { + if r.id != j.ID { + r.close.hideHint() + } + r.id, r.fullTitle = j.ID, j.Title + label, name := jobAppearance(j) + tint := theme.Color(name) + r.stripe.FillColor, r.state.Color = tint, tint + r.title.Color = theme.ForegroundColor() + r.background.FillColor = withAlpha(tint, 18) + if r.u.selectedJobs[j.ID] { + r.background.FillColor = theme.SelectionColor() + } + r.active.StrokeColor = color.Transparent + if j.ID == r.u.selected { + r.active.StrokeColor = theme.PrimaryColor() + } + r.state.Text = fmt.Sprintf("%s · %d videos", label, len(j.Videos)) + if j.State == model.Running || j.State == model.Paused || j.State == model.Complete { + percent := math.Round(max(0, min(1, j.Progress)) * 100) + if j.State == model.Complete { + percent = 100 + } + r.state.Text += fmt.Sprintf(" · %.0f%%", percent) + } + r.close.OnTapped = func() { r.u.removeJobs([]string{j.ID}) } + enabled(r.close, !r.u.snapshot.Clearing) + r.Refresh() +} + +func withAlpha(c color.Color, alpha uint8) color.Color { + r, g, b, _ := c.RGBA() + return color.NRGBA{R: uint8(r >> 8), G: uint8(g >> 8), B: uint8(b >> 8), A: alpha} +} + +func (r *jobTile) CreateRenderer() fyne.WidgetRenderer { return &jobTileRenderer{tile: r} } + +type jobTileRenderer struct{ tile *jobTile } + +func (r *jobTileRenderer) MinSize() fyne.Size { return fyne.NewSize(160, 46) } +func (r *jobTileRenderer) Destroy() { r.tile.close.hideHint() } +func (r *jobTileRenderer) Objects() []fyne.CanvasObject { + t := r.tile + return []fyne.CanvasObject{t.background, t.active, t.stripe, t.title, t.state, t.close} +} +func (r *jobTileRenderer) Layout(size fyne.Size) { + t := r.tile + t.background.Resize(size) + t.active.Resize(size) + t.stripe.Resize(fyne.NewSize(3, size.Height)) + t.close.Move(fyne.NewPos(size.Width-34, (size.Height-32)/2)) + t.close.Resize(fyne.NewSize(32, 32)) + width := max(0, size.Width-48) + t.title.Text = elideJobText(t.fullTitle, width, t.title.TextSize, t.title.TextStyle) + t.title.Move(fyne.NewPos(10, 4)) + t.title.Resize(fyne.NewSize(width, 19)) + t.state.Move(fyne.NewPos(10, 24)) + t.state.Resize(fyne.NewSize(width, 16)) +} +func (r *jobTileRenderer) Refresh() { + r.Layout(r.tile.Size()) + for _, object := range r.Objects() { + object.Refresh() + } +} + +func elideJobText(text string, width, size float32, style fyne.TextStyle) string { + if fyne.MeasureText(text, size, style).Width <= width { + return text + } + runes := []rune(text) + lo, hi := 0, len(runes) + for lo < hi { + mid := (lo + hi + 1) / 2 + if fyne.MeasureText(string(runes[:mid])+"…", size, style).Width <= width { + lo = mid + } else { + hi = mid - 1 + } + } + return string(runes[:lo]) + "…" +} diff --git a/internal/ui/jobs_test.go b/internal/ui/jobs_test.go new file mode 100644 index 0000000..a990d1d --- /dev/null +++ b/internal/ui/jobs_test.go @@ -0,0 +1,163 @@ +package ui + +import ( + "fmt" + "image/png" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "easydvd/internal/model" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/test" +) + +func jobFixture(t *testing.T) *window { + return fileListFixture(t, + model.Job{Title: "Holiday 2002", State: model.Ready, ScanComplete: true}, + model.Job{Title: "Family memories", State: model.Ready, ScanComplete: true}, + model.Job{Title: "Winter 2003", State: model.Complete, ScanComplete: true, Progress: 1}, + model.Job{Title: "Weekend", State: model.Ready, ScanComplete: true}) +} + +func waitForJobCount(t *testing.T, u *window, count int) { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + s := u.engine.Snapshot() + if len(s.Jobs) == count && !s.Clearing { + u.snapshot = s + u.refresh() + return + } + time.Sleep(5 * time.Millisecond) + } + t.Fatal("job removal did not finish") +} + +func TestJobSelectionRangesAndDelete(t *testing.T) { + u := jobFixture(t) + jobs := append([]model.Job(nil), u.snapshot.Jobs...) + u.selectJobs(jobs[1].ID, 0) + u.selectJobs(jobs[3].ID, fyne.KeyModifierShift) + if len(u.selectedJobs) != 3 || u.selected != jobs[3].ID || u.jobSelectionCount.Text != "3 selected" { + t.Fatal("job Shift-selection differs from file selection") + } + u.selectJobs(jobs[0].ID, fyne.KeyModifierControl) + if len(u.selectedJobs) != 4 { + t.Fatal("Ctrl-click discarded previous selection") + } + u.selectJobs(jobs[0].ID, fyne.KeyModifierControl) + if len(u.selectedJobs) != 3 || u.remove.Disabled() || u.remove.Text != "Remove selected" { + t.Fatal("job toggling or bulk removal control is incorrect") + } + if u.win.Canvas().Focused() != u.queue { + t.Fatal("job click did not focus the queue for keyboard actions") + } + u.win.Canvas().Focused().TypedKey(&fyne.KeyEvent{Name: fyne.KeyDelete}) + waitForJobCount(t, u, 2) + if u.snapshot.Jobs[0].ID != jobs[0].ID || u.snapshot.Jobs[1].ID != jobs[4].ID || len(u.selectedJobs) != 0 { + t.Fatal("Delete removed jobs outside the selection or kept stale selections") + } + test.Tap(u.jobSelectAll) + if len(u.selectedJobs) != 2 { + t.Fatal("Select all missed queued jobs") + } + test.Tap(u.remove) + waitForJobCount(t, u, 0) + if !u.empty.Visible() || !u.remove.Disabled() { + t.Fatal("removing all selected jobs did not restore the empty state") + } +} + +func TestJobTileCloseTargetsOnlyItsJob(t *testing.T) { + u := jobFixture(t) + keep := u.snapshot.Jobs[0].ID + u.selectJobs(keep, 0) + r := newJobTile(u) + r.update(u.snapshot.Jobs[1]) + if r.MinSize().Height > 48 { + t.Fatalf("job tile still has too much vertical space: %v", r.MinSize()) + } + test.Tap(r.close) + waitForJobCount(t, u, 4) + if u.snapshot.Jobs[0].ID != keep || !u.selectedJobs[keep] { + t.Fatal("tile X removed a selected job instead of its own job") + } + // A recycled tile must bind its X to the next displayed job. + r.update(u.snapshot.Jobs[2]) + id := r.id + test.Tap(r.close) + waitForJobCount(t, u, 3) + for _, job := range u.snapshot.Jobs { + if job.ID == id { + t.Fatal("recycled X targeted the old job") + } + } +} + +func TestJobStatusAndSharedFooter(t *testing.T) { + u := jobFixture(t) + for _, tc := range []struct { + job model.Job + label string + }{ + {model.Job{State: model.Ready}, "Ready"}, + {model.Job{State: model.Running}, "Running"}, + {model.Job{State: model.Complete}, "Completed"}, + {model.Job{State: model.Blocked, Locked: true}, "Failed"}, + {model.Job{State: model.Blocked, Videos: []model.Video{{Error: "Unreadable file"}}}, "Needs attention"}, + } { + label, _ := jobAppearance(tc.job) + if label != tc.label { + t.Fatalf("status %s displayed as %s", tc.label, label) + } + } + u.snapshot.Jobs[2].State = model.Running + u.snapshot.Jobs[2].Progress = .426 + u.snapshot.Jobs[2].Stage = "Encoding · 4 of 10 complete" + u.selected = u.snapshot.Jobs[0].ID + u.refresh() + if !u.footerProgress.Visible() || u.queuePosition.Text != "Job 3 of 5" || u.queuePercent.Text != "43%" || u.queueProgress.Size().Height != 6 { + t.Fatal("shared status bar does not track the running job independently of the viewed job") + } + r := newJobTile(u) + r.update(u.snapshot.Jobs[2]) + if !strings.Contains(r.state.Text, "43%") { + t.Fatal("running job tile has no percentage") + } +} + +func TestQueuePreview(t *testing.T) { + dir := os.Getenv("EASYDVD_UI_PREVIEW") + if dir == "" { + t.Skip("visual preview not requested") + } + u := jobFixture(t) + base := u.snapshot.Jobs[1].Clone() + for i := len(u.snapshot.Jobs); i < 14; i++ { + j := base.Clone() + j.ID, j.Title = model.ID(), fmt.Sprintf("Family films %02d", i+1) + u.snapshot.Jobs = append(u.snapshot.Jobs, j) + } + u.snapshot.Jobs[1].State, u.snapshot.Jobs[1].Progress = model.Running, .42 + u.snapshot.Jobs[1].Stage = "Encoding · 4 of 10 complete" + u.snapshot.Jobs[2].State, u.snapshot.Jobs[2].Locked = model.Blocked, true + u.snapshot.Jobs[2].Error = "Encoding failed" + u.selectedJobs[u.snapshot.Jobs[4].ID] = true + for _, appearance := range []string{"Light", "Dark"} { + u.applyTheme(appearance) + u.refresh() + f, err := os.Create(filepath.Join(dir, "queue-"+appearance+".png")) + if err != nil { + t.Fatal(err) + } + if err := png.Encode(f, u.win.Canvas().Capture()); err != nil { + t.Fatal(err) + } + f.Close() + } +} diff --git a/internal/ui/menu_settings.go b/internal/ui/menu_settings.go index ea12403..23d1b77 100644 --- a/internal/ui/menu_settings.go +++ b/internal/ui/menu_settings.go @@ -89,7 +89,7 @@ func (u *window) menuSettings(id string) fyne.Window { status.Wrapping = fyne.TextWrapWord scope := widget.NewLabel("Changes apply to this pending job. Presets are available for any new set.") if id == "" { - scope.SetText("Defaults apply to new and pending jobs.") + scope.SetText("Saved defaults apply to new jobs. Existing jobs keep their own menu settings.") } else if job.Locked { scope.SetText("Started/finished set: preview changes and save presets here. Apply defaults for new jobs; existing ISOs stay unchanged.") } diff --git a/internal/ui/menu_settings_test.go b/internal/ui/menu_settings_test.go index 71de315..318920b 100644 --- a/internal/ui/menu_settings_test.go +++ b/internal/ui/menu_settings_test.go @@ -15,9 +15,6 @@ import ( func TestMenuSettingsApplyPreviewAndPresets(t *testing.T) { u := fileListFixture(t) - if u.preview.Text != "Menu" { - t.Fatal("job button must open menu settings") - } w := u.menuSettings(u.selected) if w == nil { t.Fatal("missing menu settings") diff --git a/internal/ui/playback_test.go b/internal/ui/playback_test.go index c232cd1..6e7b1ea 100644 --- a/internal/ui/playback_test.go +++ b/internal/ui/playback_test.go @@ -9,12 +9,13 @@ import ( "time" ) -func TestNoMenuOnlySelectableForSingleVideoJob(t *testing.T) { +func TestNoMenuCanOverrideMultipleAndSingleVideoDefaults(t *testing.T) { u := fileListFixture(t) j := u.selectedJob() u.settingsDialog(j.ID, j.Settings) var noMenu *widget.Check var cancel *widget.Button + var menuButton *widget.Button find := func(object fyne.CanvasObject) { switch w := object.(type) { case *widget.Check: @@ -22,14 +23,25 @@ func TestNoMenuOnlySelectableForSingleVideoJob(t *testing.T) { noMenu = w } case *widget.Button: + if w.Text == "Edit menu…" { + menuButton = w + } if w.Text == "Cancel" { cancel = w } } } walkFileTestObjects(u.win.Canvas().Overlays().Top(), find) - if noMenu == nil || !noMenu.Disabled() { - t.Fatal("multiple-video job offered no-menu playback") + if noMenu == nil || noMenu.Disabled() || menuButton == nil || menuButton.Disabled() { + t.Fatal("multiple-video job does not offer playback choices") + } + noMenu.SetChecked(true) + if !menuButton.Disabled() { + t.Fatal("menu editor enabled with no menu selected") + } + noMenu.SetChecked(false) + if menuButton.Disabled() { + t.Fatal("menu editor did not enable again") } test.Tap(cancel) var ids []string @@ -54,6 +66,9 @@ func TestNoMenuOnlySelectableForSingleVideoJob(t *testing.T) { t.Fatal("single-video playback option unavailable") } noMenu.SetChecked(true) + if !menuButton.Disabled() { + t.Fatal("single-video menu editor enabled while no menu selected") + } test.Tap(save) deadline := time.Now().Add(2 * time.Second) for time.Now().Before(deadline) { @@ -64,3 +79,33 @@ func TestNoMenuOnlySelectableForSingleVideoJob(t *testing.T) { } t.Fatal("no-menu choice was not saved") } + +func TestMultiVideoNoMenuChoicePersistsAndDisablesMenuEditor(t *testing.T) { + u := fileListFixture(t) + for _, checked := range []bool{true, false} { + u.snapshot = u.engine.Snapshot() + u.settingsDialog(u.selected, u.selectedJob().Settings) + fields, buttons := settingsFields(u) + noMenu := fields["Playback"].(*widget.Check) + menuButton := buttons["Edit menu…"] + if menuButton.Disabled() != noMenu.Checked { + t.Fatal("persisted menu editor state disagrees with playback mode") + } + noMenu.SetChecked(checked) + if menuButton.Disabled() != checked { + t.Fatal("menu editor did not follow checkbox") + } + test.Tap(buttons["Save settings"]) + deadline := time.Now().Add(3 * time.Second) + for { + j := u.engine.Snapshot().Jobs[0] + if j.Settings.NoMenu == checked && j.NoMenuOverride != nil && u.win.Canvas().Overlays().Top() == nil { + break + } + if time.Now().After(deadline) { + t.Fatal("explicit playback choice was not saved") + } + time.Sleep(5 * time.Millisecond) + } + } +} diff --git a/internal/ui/read_only_text.go b/internal/ui/read_only_text.go new file mode 100644 index 0000000..eccca33 --- /dev/null +++ b/internal/ui/read_only_text.go @@ -0,0 +1,28 @@ +package ui + +import ( + "image/color" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/container" + "fyne.io/fyne/v2/theme" + "fyne.io/fyne/v2/widget" +) + +// Diagnostic text is read-only, but it should have the contrast of normal +// text rather than the dim color used for unavailable controls. +func newReadOnlyText(text string) (*widget.Entry, *container.ThemeOverride) { + entry := widget.NewMultiLineEntry() + entry.SetText(text) + entry.Disable() + return entry, container.NewThemeOverride(entry, readableTextTheme{fyne.CurrentApp().Settings().Theme()}) +} + +type readableTextTheme struct{ fyne.Theme } + +func (t readableTextTheme) Color(name fyne.ThemeColorName, variant fyne.ThemeVariant) color.Color { + if name == theme.ColorNameDisabled { + name = theme.ColorNameForeground + } + return t.Theme.Color(name, variant) +} diff --git a/internal/ui/read_only_text_test.go b/internal/ui/read_only_text_test.go new file mode 100644 index 0000000..541ceb4 --- /dev/null +++ b/internal/ui/read_only_text_test.go @@ -0,0 +1,118 @@ +package ui + +import ( + "image/png" + "os" + "path/filepath" + "testing" + "time" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/container" + "fyne.io/fyne/v2/test" + "fyne.io/fyne/v2/theme" + "fyne.io/fyne/v2/widget" +) + +func assertReadableDiagnostic(t *testing.T, u *window, entry *widget.Entry) { + t.Helper() + before := entry.Text + entry.TypedRune('x') + if !entry.Disabled() || entry.Text != before { + t.Fatal("diagnostic text is editable") + } + actual := entry.Theme().Color(theme.ColorNameDisabled, u.app.Settings().ThemeVariant()) + want := theme.ForegroundColor() + r, g, b, a := actual.RGBA() + wr, wg, wb, wa := want.RGBA() + if r != wr || g != wg || b != wb || a != wa { + t.Fatal("read-only diagnostics still use dim disabled text") + } +} + +func TestDiagnosticDialogsUseReadableText(t *testing.T) { + u := fileListFixture(t) + if err := os.MkdirAll(u.engine.LogsDir(), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(u.engine.JobLogPath(u.selected), []byte("Scanning sources\n18 videos inspected\nReady for encoding\n"), 0644); err != nil { + t.Fatal(err) + } + preview := func(name string) { + if dir := os.Getenv("EASYDVD_UI_PREVIEW"); dir != "" { + f, err := os.Create(filepath.Join(dir, name+".png")) + if err != nil { + t.Fatal(err) + } + if err := png.Encode(f, u.win.Canvas().Capture()); err != nil { + t.Fatal(err) + } + f.Close() + } + } + closeDialog := func() { + var close *widget.Button + walkFileTestObjects(u.win.Canvas().Overlays().Top(), func(object fyne.CanvasObject) { + if b, ok := object.(*widget.Button); ok && b.Text == "Close" { + close = b + } + }) + if close == nil { + t.Fatal("dialog close button missing") + } + test.Tap(close) + } + for _, appearance := range []string{"Light", "Dark"} { + u.applyTheme(appearance) + u.refresh() + u.jobDetails() + var tabs *container.AppTabs + walkFileTestObjects(u.win.Canvas().Overlays().Top(), func(object fyne.CanvasObject) { + if found, ok := object.(*container.AppTabs); ok { + tabs = found + } + }) + if tabs == nil { + t.Fatal("details tabs missing") + } + for i := range tabs.Items { + tabs.SelectIndex(i) + entries := 0 + walkFileTestObjects(tabs.Items[i].Content, func(object fyne.CanvasObject) { + if entry, ok := object.(*widget.Entry); ok { + assertReadableDiagnostic(t, u, entry) + entries++ + } + }) + if entries == 0 { + t.Fatal("details text missing") + } + name := "details" + if i == 1 { + name = "log" + } + preview("diagnostic-" + name + "-" + appearance) + } + closeDialog() + u.diagnostics() + deadline := time.Now().Add(3 * time.Second) + for { + var entry *widget.Entry + walkFileTestObjects(u.win.Canvas().Overlays().Top(), func(object fyne.CanvasObject) { + if e, ok := object.(*widget.Entry); ok { + entry = e + } + }) + if entry != nil { + assertReadableDiagnostic(t, u, entry) + break + } + if time.Now().After(deadline) { + t.Fatal("tools diagnostics did not load") + } + time.Sleep(5 * time.Millisecond) + } + preview("diagnostic-tools-" + appearance) + closeDialog() + } +} diff --git a/internal/ui/selection.go b/internal/ui/selection.go new file mode 100644 index 0000000..899a1f6 --- /dev/null +++ b/internal/ui/selection.go @@ -0,0 +1,53 @@ +package ui + +import ( + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/driver/desktop" +) + +func selectionModifiers(app fyne.App) fyne.KeyModifier { + if driver, ok := app.Driver().(desktop.Driver); ok { + return driver.CurrentKeyModifiers() + } + return 0 +} + +// Both lists use Explorer semantics, with an anchor stable across Shift-clicks. +// Ctrl+Shift adds a range; Shift alone replaces it so ranges can also shrink. +func selectItems(ids []string, selected map[string]bool, anchor *string, target string, modifiers fyne.KeyModifier) bool { + start, end := -1, -1 + for i, id := range ids { + if id == *anchor { + start = i + } + if id == target { + end = i + } + } + if end < 0 { + return false + } + ctrl := modifiers&fyne.KeyModifierControl != 0 + shift := modifiers&fyne.KeyModifierShift != 0 + if shift && start >= 0 { + if !ctrl { + clear(selected) + } + for i := min(start, end); i <= max(start, end); i++ { + selected[ids[i]] = true + } + return true + } + *anchor = target + if ctrl { + if selected[target] { + delete(selected, target) + } else { + selected[target] = true + } + } else { + clear(selected) + selected[target] = true + } + return true +} diff --git a/internal/ui/selection_test.go b/internal/ui/selection_test.go new file mode 100644 index 0000000..3fb2e42 --- /dev/null +++ b/internal/ui/selection_test.go @@ -0,0 +1,114 @@ +package ui + +import ( + "testing" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/test" + "fyne.io/fyne/v2/widget" +) + +func TestExplorerSelectionInJobsAndFiles(t *testing.T) { + for _, jobs := range []bool{true, false} { + name := "files" + if jobs { + name = "jobs" + } + t.Run(name, func(t *testing.T) { + u := jobFixture(t) + var ids []string + selection := u.selectedFiles + click := func(index int, modifiers fyne.KeyModifier) { + if modifiers == 0 { + row := newFileRow(u) + row.update(u.selectedJob(), index) + test.Tap(row) + } else { + u.selectFiles(ids[index], modifiers) + } + } + selectAll := func() { u.files.TypedShortcut(&fyne.ShortcutSelectAll{}) } + if jobs { + selection = u.selectedJobs + for _, j := range u.snapshot.Jobs { + ids = append(ids, j.ID) + } + click = func(index int, modifiers fyne.KeyModifier) { + if modifiers == 0 { + row := newJobTile(u) + row.update(u.snapshot.Jobs[index]) + test.Tap(row) + } else { + u.selectJobs(ids[index], modifiers) + } + } + selectAll = func() { u.queue.TypedShortcut(&fyne.ShortcutSelectAll{}) } + } else { + for _, v := range u.selectedJob().Videos { + ids = append(ids, v.ID) + } + } + for _, tc := range []struct { + index int + modifiers fyne.KeyModifier + want []int + }{ + {1, 0, []int{1}}, + {3, 0, []int{3}}, + {3, 0, []int{3}}, // Repeated plain clicks never toggle the item off. + {1, fyne.KeyModifierControl, []int{1, 3}}, + {3, fyne.KeyModifierControl, []int{1}}, + {0, fyne.KeyModifierShift, []int{0, 1, 2, 3}}, + {2, fyne.KeyModifierShift, []int{2, 3}}, // Shrink the previous range. + {0, fyne.KeyModifierControl, []int{0, 2, 3}}, + {1, fyne.KeyModifierControl | fyne.KeyModifierShift, []int{0, 1, 2, 3}}, + {4, 0, []int{4}}, + } { + click(tc.index, tc.modifiers) + if len(selection) != len(tc.want) { + t.Fatalf("click %d with modifiers %v: selection=%v wanted=%v", tc.index, tc.modifiers, selection, tc.want) + } + for _, index := range tc.want { + if !selection[ids[index]] { + t.Fatalf("expected item %d selected", index) + } + } + } + selectAll() + if len(selection) != len(ids) { + t.Fatal("Ctrl+A did not select the complete list") + } + click(2, 0) + if len(selection) != 1 || !selection[ids[2]] { + t.Fatal("plain click did not replace Select all") + } + }) + } +} + +func TestJobHoverNeverChangesDisplayedJob(t *testing.T) { + u := jobFixture(t) + u.selectJobs(u.snapshot.Jobs[0].ID, 0) + u.selectFiles("1", 0) + job, title := u.selected, u.title.Text + // Fyne highlights rows for both mouse hover and keyboard movement. + // Highlighting must never be treated as choosing another job. + u.queue.Highlight(3) + if u.selected != job || u.title.Text != title || len(u.selectedJobs) != 1 || !u.selectedFiles["1"] { + t.Fatal("hover/highlight changed the displayed job or its file selection") + } + row := newJobTile(u) + row.update(u.snapshot.Jobs[3]) + test.Tap(row) + if u.selected != u.snapshot.Jobs[3].ID || u.title.Text != u.snapshot.Jobs[3].Title || len(u.selectedFiles) != 0 { + t.Fatal("clicking a job did not switch the displayed job") + } + walkFileTestObjects(u.win.Content(), func(object fyne.CanvasObject) { + if _, ok := object.(*widget.Check); ok { + t.Fatal("list selection still displays a checkbox") + } + if b, ok := object.(*widget.Button); ok && (b.Text == "More info" || b.Text == "Less info") { + t.Fatal("job header still expands") + } + }) +} diff --git a/internal/ui/settings.go b/internal/ui/settings.go new file mode 100644 index 0000000..41de088 --- /dev/null +++ b/internal/ui/settings.go @@ -0,0 +1,160 @@ +package ui + +import ( + "fmt" + "os" + "strconv" + "strings" + + "easydvd/internal/model" + "easydvd/internal/platform" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/container" + "fyne.io/fyne/v2/dialog" + "fyne.io/fyne/v2/layout" + "fyne.io/fyne/v2/theme" + "fyne.io/fyne/v2/widget" +) + +func (u *window) settingsDialog(id string, s model.Settings) { + defaults := id == "" + standard := widget.NewSelect([]string{"PAL", "NTSC"}, nil) + standard.SetSelected(s.Standard) + medium := widget.NewSelect([]string{"DVD-5", "DVD-9"}, nil) + medium.SetSelected(s.Media) + output := widget.NewEntry() + output.SetText(s.OutputDir) + folder := func(entry *widget.Entry) fyne.CanvasObject { + browse := widget.NewButtonWithIcon("", theme.FolderOpenIcon(), func() { + u.action(func() error { + paths, err := platform.PickFolders(false) + if err == nil && len(paths) > 0 { + fyne.Do(func() { entry.SetText(paths[0]) }) + } + return err + }) + }) + return container.NewBorder(nil, nil, nil, browse, entry) + } + form := widget.NewForm(widget.NewFormItem("TV standard", standard), widget.NewFormItem("Disc capacity", medium), widget.NewFormItem("Output folder", folder(output))) + menuText := "Edit menu…" + if defaults { + menuText = "Menu defaults…" + } + menuButton := widget.NewButtonWithIcon(menuText, theme.SettingsIcon(), func() { u.menuSettings(id) }) + form.Append("Menu", menuButton) + packing := widget.NewSelect([]string{"Strict order", "Space efficiency"}, nil) + packing.SetSelected(s.Packing) + workers := widget.NewSelect([]string{"1", "2"}, nil) + workers.SetSelected(strconv.Itoa(s.Encoders)) + profile := widget.NewSelect([]string{model.ProfileBalanced, model.ProfileQuality}, nil) + profile.SetSelected(s.Profile()) + jobProfile := widget.NewRadioGroup([]string{model.ProfileBalanced, model.ProfileQuality}, nil) + jobProfile.Horizontal, jobProfile.Required = true, true + jobProfile.SetSelected(s.Profile()) + work := widget.NewEntry() + work.SetText(s.WorkDir) + appearance := widget.NewSelect([]string{"System", "Light", "Dark"}, nil) + appearance.SetSelected(s.Theme) + stage := widget.NewCheck("Stage sources locally (recommended for network shares)", nil) + stage.SetChecked(s.StageLocally) + keep := widget.NewCheck("Keep intermediate media after success", nil) + keep.SetChecked(s.KeepWork) + noMenu := widget.NewCheck("No menu — play all videos automatically in order", nil) + noMenu.SetChecked(s.NoMenu) + playbackEdited := false + noMenu.OnChanged = func(checked bool) { playbackEdited = true; enabled(menuButton, !checked) } + if !defaults { + enabled(menuButton, !s.NoMenu) + } + title, note, saveText := "Job settings", "Overrides for this job only. Other jobs and saved defaults stay unchanged.", "Save settings" + if defaults { + title, note, saveText = "Default settings", "Every new job starts with these settings. Existing jobs keep their own settings.", "Save as defaults" + form.Append("File allocation", packing) + form.Append("Encoding profile", profile) + form.Append("Encoding workers", workers) + form.Append("Local work folder", folder(work)) + form.Append("Appearance", appearance) + } else { + form.Append("Encoding profile", jobProfile) + // Playback mode is part of this job's menu options. + form.Append("Playback", noMenu) + } + heading := widget.NewLabel(note) + heading.Wrapping = fyne.TextWrapWord + var d dialog.Dialog + save := func() { + // Menu options can be edited in their own window while this dialog is + // open. Merge the fields shown here into the latest saved settings. + snapshot := u.engine.Snapshot() + next := snapshot.Settings + if !defaults { + found := false + for _, j := range snapshot.Jobs { + if j.ID == id { + next, found = j.Settings, true + break + } + } + if !found { + dialog.ShowError(fmt.Errorf("job no longer exists"), u.win) + return + } + } + next.Standard, next.Media = standard.Selected, medium.Selected + next.OutputDir = strings.TrimSpace(output.Text) + if defaults { + next.Packing, next.EncodingProfile = packing.Selected, profile.Selected + next.Encoders, _ = strconv.Atoi(workers.Selected) + next.WorkDir, next.Theme = strings.TrimSpace(work.Text), appearance.Selected + next.StageLocally, next.KeepWork = stage.Checked, keep.Checked + } else { + next.NoMenu = noMenu.Checked + next.EncodingProfile = jobProfile.Selected + } + if err := next.Validate(); err != nil { + dialog.ShowError(err, u.win) + return + } + u.action(func() error { + var err error + if defaults || !playbackEdited { + err = u.engine.SetSettings(id, next) + } else { + err = u.engine.SetJobSettings(id, next) + } + if err == nil { + fyne.Do(func() { + if defaults { + u.applyTheme(next.Theme) + } + d.Hide() + }) + } + return err + }) + } + buttons := container.NewHBox(layout.NewSpacer(), widget.NewButton("Cancel", func() { d.Hide() }), widget.NewButton(saveText, save)) + options := container.NewVBox(form) + if defaults { + options.Add(stage) + options.Add(keep) + options.Add(u.updateSettings()) + buttons.Objects = append([]fyne.CanvasObject{widget.NewButtonWithIcon("Open logs folder", theme.FolderOpenIcon(), func() { + u.action(func() error { + if err := os.MkdirAll(u.engine.LogsDir(), 0755); err != nil { + return err + } + return platform.OpenFolder(u.engine.LogsDir()) + }) + })}, buttons.Objects...) + } + d = dialog.NewCustomWithoutButtons(title, container.NewBorder(heading, buttons, nil, nil, container.NewVScroll(options)), u.win) + size := fyne.NewSize(620, 460) + if defaults { + size = fyne.NewSize(740, 640) + } + d.Resize(size) + d.Show() +} diff --git a/internal/ui/settings_test.go b/internal/ui/settings_test.go new file mode 100644 index 0000000..e26fc2b --- /dev/null +++ b/internal/ui/settings_test.go @@ -0,0 +1,129 @@ +package ui + +import ( + "easydvd/internal/model" + "image/png" + "os" + "path/filepath" + "testing" + "time" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/test" + "fyne.io/fyne/v2/widget" +) + +func settingsFields(u *window) (map[string]fyne.CanvasObject, map[string]*widget.Button) { + fields := make(map[string]fyne.CanvasObject) + buttons := make(map[string]*widget.Button) + walkFileTestObjects(u.win.Canvas().Overlays().Top(), func(object fyne.CanvasObject) { + if f, ok := object.(*widget.Form); ok { + for _, item := range f.Items { + fields[item.Text] = item.Widget + } + } + if b, ok := object.(*widget.Button); ok { + buttons[b.Text] = b + } + }) + return fields, buttons +} + +func TestDefaultSettingsAndJobOverrideScope(t *testing.T) { + u := fileListFixture(t) + original := u.snapshot.Jobs[0].Settings + u.settingsDialog("", u.snapshot.Settings) + fields, buttons := settingsFields(u) + if fields["Titles per page"] != nil || fields["Menu layout"] != nil || buttons["Save as defaults"] == nil { + t.Fatal("default settings duplicate menu controls or have no explicit default save") + } + if fields["Encoding workers"] == nil || fields["Local work folder"] == nil { + t.Fatal("default options were lost") + } + fields["TV standard"].(*widget.Select).SetSelected("NTSC") + // Save a menu default while the main dialog is open; it must not be overwritten. + style := u.snapshot.Settings.Menu + style.Aspect = "16:9" + if err := u.engine.SetMenu("", style, "Text", 7); err != nil { + t.Fatal(err) + } + test.Tap(buttons["Save as defaults"]) + deadline := time.Now().Add(3 * time.Second) + for u.engine.Snapshot().Settings.Standard != "NTSC" || u.win.Canvas().Overlays().Top() != nil { + if time.Now().After(deadline) { + t.Fatal("defaults were not saved") + } + time.Sleep(5 * time.Millisecond) + } + snapshot := u.engine.Snapshot() + if snapshot.Settings.TitlesPerPage != 7 || snapshot.Settings.Menu.Aspect != "16:9" || snapshot.Jobs[0].Settings != original { + t.Fatal("saving defaults changed an existing job or lost menu defaults") + } + u.snapshot = snapshot + u.refresh() + u.settingsDialog(u.selected, original) + fields, buttons = settingsFields(u) + for _, name := range []string{"Encoding workers", "File allocation", "Local work folder", "Appearance", "Titles per page"} { + if fields[name] != nil { + t.Fatalf("job overrides expose default-only option %s", name) + } + } + for _, name := range []string{"TV standard", "Disc capacity", "Output folder", "Menu", "Encoding profile"} { + if fields[name] == nil { + t.Fatalf("missing job override %s", name) + } + } + fields["Disc capacity"].(*widget.Select).SetSelected("DVD-9") + profile, ok := fields["Encoding profile"].(*widget.RadioGroup) + if !ok || profile.Selected != model.ProfileBalanced { + t.Fatal("job settings have no encoding radio buttons") + } + profile.SetSelected(model.ProfileQuality) + jobMenu := original.Menu + jobMenu.Font = "Monospace" + if err := u.engine.SetMenu(u.selected, jobMenu, "Text", 6); err != nil { + t.Fatal(err) + } + test.Tap(buttons["Save settings"]) + deadline = time.Now().Add(3 * time.Second) + for u.engine.Snapshot().Jobs[0].Settings.Media != "DVD-9" { + if time.Now().After(deadline) { + t.Fatal("job override was not saved") + } + time.Sleep(5 * time.Millisecond) + } + snapshot = u.engine.Snapshot() + job := snapshot.Jobs[0].Settings + if job.Profile() != model.ProfileQuality || snapshot.Settings.Profile() != model.ProfileBalanced { + t.Fatal("job profile did not persist independently of defaults") + } + if snapshot.Settings.Media != "DVD-5" || snapshot.Settings.Standard != "NTSC" || job.Standard != "PAL" || job.TitlesPerPage != 6 || job.Menu.Font != "Monospace" || job.Encoders != original.Encoders || job.WorkDir != original.WorkDir { + t.Fatal("job override changed defaults, hidden options or menu changes") + } +} + +func TestSettingsPreview(t *testing.T) { + dir := os.Getenv("EASYDVD_UI_PREVIEW") + if dir == "" { + t.Skip("visual preview not requested") + } + u := fileListFixture(t) + u.applyTheme("Dark") + for _, id := range []string{"", u.selected} { + u.settingsDialog(id, u.snapshot.Settings) + mode := "job" + if id == "" { + mode = "defaults" + } + f, err := os.Create(filepath.Join(dir, "settings-"+mode+".png")) + if err != nil { + t.Fatal(err) + } + if err := png.Encode(f, u.win.Canvas().Capture()); err != nil { + t.Fatal(err) + } + f.Close() + _, buttons := settingsFields(u) + test.Tap(buttons["Cancel"]) + } +} diff --git a/internal/ui/status.go b/internal/ui/status.go new file mode 100644 index 0000000..1fd2835 --- /dev/null +++ b/internal/ui/status.go @@ -0,0 +1,96 @@ +package ui + +import ( + "fmt" + "math" + + "easydvd/internal/model" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/canvas" + "fyne.io/fyne/v2/container" + "fyne.io/fyne/v2/theme" + "fyne.io/fyne/v2/widget" +) + +func (u *window) buildStatusBar() fyne.CanvasObject { + u.queueProgress = &thinProgress{} + u.queueProgress.ExtendBaseWidget(u.queueProgress) + u.queuePosition = widget.NewLabel("") + u.queuePercent = widget.NewLabel("") + u.footerProgress = container.NewHBox(u.queuePosition, container.NewCenter(u.queueProgress), u.queuePercent) + u.footerProgress.Hide() + return container.NewVBox(widget.NewSeparator(), container.NewBorder(nil, nil, nil, u.footerProgress, u.status)) +} + +func (u *window) refreshStatusProgress() { + index := -1 + for _, state := range []model.State{model.Running, model.Scanning, model.Paused} { + for i, j := range u.snapshot.Jobs { + if j.State == state && (state != model.Paused || j.Progress > 0) { + index = i + break + } + } + if index >= 0 { + break + } + } + if index < 0 || u.snapshot.Clearing { + u.footerProgress.Hide() + u.win.Content().Refresh() + return + } + j := u.snapshot.Jobs[index] + value := max(0, min(1, j.Progress)) + percent := fmt.Sprintf("%.0f%%", math.Round(value*100)) + if j.State == model.Scanning { + percent = "Scanning" + value = 0 + if j.Discovered > 0 { + value = min(1, float64(len(j.Videos))/float64(j.Discovered)) + } + } + u.queuePosition.SetText(fmt.Sprintf("Job %d of %d", index+1, len(u.snapshot.Jobs))) + u.queuePercent.SetText(percent) + u.queueProgress.value = value + u.queueProgress.Refresh() + u.footerProgress.Show() + if j.Stage != "" && u.mediaReady && !u.mediaChecking && u.snapshot.Error == "" { + u.status.SetText(j.Stage) + } + u.win.Content().Refresh() +} + +// A six-pixel track keeps progress in the status bar without a full-height +// progress widget or repeated bars in individual job headers. +type thinProgress struct { + widget.BaseWidget + value float64 +} + +func (p *thinProgress) CreateRenderer() fyne.WidgetRenderer { + return &thinProgressRenderer{bar: p, track: canvas.NewRectangle(theme.ButtonColor()), fill: canvas.NewRectangle(theme.PrimaryColor())} +} + +type thinProgressRenderer struct { + bar *thinProgress + track, fill *canvas.Rectangle +} + +func (r *thinProgressRenderer) MinSize() fyne.Size { return fyne.NewSize(180, 6) } +func (r *thinProgressRenderer) Destroy() {} +func (r *thinProgressRenderer) Objects() []fyne.CanvasObject { + return []fyne.CanvasObject{r.track, r.fill} +} +func (r *thinProgressRenderer) Layout(size fyne.Size) { + r.track.CornerRadius, r.fill.CornerRadius = 3, 3 + r.track.Resize(size) + r.fill.Resize(fyne.NewSize(size.Width*float32(r.bar.value), size.Height)) +} +func (r *thinProgressRenderer) Refresh() { + r.track.FillColor, r.fill.FillColor = theme.ButtonColor(), theme.PrimaryColor() + r.Layout(r.bar.Size()) + r.track.Refresh() + r.fill.Refresh() +} diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 7af770b..dab06b9 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -4,9 +4,7 @@ import ( "context" "fmt" "image/color" - "os" "path/filepath" - "strconv" "strings" "time" @@ -50,38 +48,41 @@ func (professionalTheme) Size(name fyne.ThemeSizeName) float32 { } type window struct { - mediaReady bool - mediaChecking bool - mediaIssue string - mediaDialog dialog.Dialog - dropBar *fyne.Container - app fyne.App - win fyne.Window - engine *engine.Engine - snapshot engine.Snapshot - selected string - selectionJob string - selectionAnchor string - selectedFiles map[string]bool - fileHints *fyne.Container - selectAll *widget.Check - selectionCount *widget.Label - excludeSelected, includeSelected *widget.Button - queue, files *widget.List - title, meta, stage, status, source *widget.Label - progress *widget.ProgressBar - scanProgress *widget.ProgressBarInfinite - headerJob string - headerExpanded bool - headerInfo, jobHeader *fyne.Container - jobSummary, jobState, activity *widget.Label - headerToggle, jobWarning, clear *widget.Button - profileToggle *widget.RadioGroup - profileSync bool - details *fyne.Container - empty *fyne.Container - start, pause, cancel, retry, settings, preview, remove, up, down *widget.Button - closed chan struct{} + mediaReady bool + mediaChecking bool + mediaIssue string + mediaDialog dialog.Dialog + dropBar *fyne.Container + app fyne.App + win fyne.Window + engine *engine.Engine + snapshot engine.Snapshot + selected string + selectionJob string + selectionAnchor string + selectedFiles map[string]bool + selectedJobs map[string]bool + jobSelectionAnchor string + jobSelectAll *widget.Button + jobSelectionCount *widget.Label + fileHints *fyne.Container + selectAll *widget.Button + selectionCount *widget.Label + excludeSelected, includeSelected *widget.Button + queue *jobList + files *fileList + title, status, source *widget.Label + queueProgress *thinProgress + queuePosition, queuePercent *widget.Label + footerProgress *fyne.Container + jobHeader *fyne.Container + jobSummary, jobOutput *widget.Label + jobWarning, clear *widget.Button + renameJob *fileAction + details *fyne.Container + empty *fyne.Container + start, pause, cancel, retry, settings, remove, up, down *widget.Button + closed chan struct{} } func ShowStartupError(err error) { @@ -227,37 +228,14 @@ func (u *window) build() fyne.CanvasObject { }) u.start.Importance = widget.HighImportance u.pause = widget.NewButtonWithIcon("Pause", theme.MediaPauseIcon(), func() { u.action(func() error { u.engine.Pause(); return nil }) }) - preferences := widget.NewButtonWithIcon("Settings", theme.SettingsIcon(), func() { u.settingsDialog("", u.snapshot.Settings) }) - diagnostics := widget.NewButtonWithIcon("Tools", theme.InfoIcon(), u.diagnostics) + preferences := widget.NewButtonWithIcon("Default settings", theme.SettingsIcon(), func() { u.settingsDialog("", u.snapshot.Settings) }) + diagnostics := newFileAction(u, nil, "Media tools") + diagnostics.SetText("!") + diagnostics.Importance = widget.MediumImportance + diagnostics.OnTapped = u.diagnostics controls := container.NewCenter(container.NewHBox(u.start, u.pause, preferences, diagnostics)) top := container.NewVBox(container.NewBorder(nil, nil, brand, controls), widget.NewSeparator()) - u.queue = widget.NewList(func() int { return len(u.snapshot.Jobs) }, func() fyne.CanvasObject { - a := widget.NewLabelWithStyle("Folder", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}) - a.Truncation = fyne.TextTruncateEllipsis - b := widget.NewLabel("Ready") - b.Truncation = fyne.TextTruncateEllipsis - return container.NewVBox(a, b) - }, func(i widget.ListItemID, o fyne.CanvasObject) { - if i >= len(u.snapshot.Jobs) { - return - } - j := u.snapshot.Jobs[i] - c := o.(*fyne.Container) - c.Objects[0].(*widget.Label).SetText(j.Title) - c.Objects[1].(*widget.Label).SetText(fmt.Sprintf("%s · %d videos", j.State, len(j.Videos))) - }) - u.queue.OnSelected = func(i widget.ListItemID) { - if i < len(u.snapshot.Jobs) { - u.selected = u.snapshot.Jobs[i].ID - u.refresh() - } - } - u.up = widget.NewButtonWithIcon("", theme.MoveUpIcon(), func() { id := u.selected; u.action(func() error { u.engine.Move(id, -1); return nil }) }) - u.down = widget.NewButtonWithIcon("", theme.MoveDownIcon(), func() { id := u.selected; u.action(func() error { u.engine.Move(id, 1); return nil }) }) - u.remove = widget.NewButtonWithIcon("Remove", theme.DeleteIcon(), func() { id := u.selected; u.action(func() error { return u.engine.Remove(id) }) }) - u.clear = widget.NewButtonWithIcon("Clear queue", theme.DeleteIcon(), u.clearQueue) - queueHeading := container.NewBorder(nil, nil, nil, u.clear, widget.NewLabelWithStyle("Queue", fyne.TextAlignLeading, fyne.TextStyle{Bold: true})) - queue := container.NewBorder(container.NewVBox(queueHeading, widget.NewSeparator()), container.NewHBox(u.up, u.down, layout.NewSpacer(), u.remove), nil, nil, u.queue) + queue := u.buildJobList() dropLabel := widget.NewLabelWithStyle("Drop folders or video files here", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}) sub := widget.NewLabelWithStyle("Folders include subfolders · Group files into DVD sets", fyne.TextAlignCenter, fyne.TextStyle{}) border := canvas.NewRectangle(color.Transparent) @@ -284,7 +262,7 @@ func (u *window) build() fyne.CanvasObject { split.Offset = .27 u.status = widget.NewLabel("Ready") u.status.Truncation = fyne.TextTruncateEllipsis - content := container.NewPadded(container.NewBorder(top, container.NewVBox(widget.NewSeparator(), u.status), nil, nil, split)) + content := container.NewPadded(container.NewBorder(top, u.buildStatusBar(), nil, nil, split)) u.fileHints = container.NewWithoutLayout() return container.NewStack(content, u.fileHints) } @@ -316,17 +294,9 @@ func enabled(w fyne.Disableable, on bool) { } } func (u *window) refresh() { - u.queue.Refresh() - for index, job := range u.snapshot.Jobs { - if job.ID == u.selected { - u.queue.Select(index) - break - } - } j := u.selectedJob() if j == nil && len(u.snapshot.Jobs) > 0 { u.selected = u.snapshot.Jobs[0].ID - u.queue.Select(0) j = u.selectedJob() } enabled(u.pause, u.snapshot.Enabled) @@ -345,7 +315,6 @@ func (u *window) refresh() { } enabled(u.up, j != nil && !u.snapshot.Clearing) enabled(u.down, j != nil && !u.snapshot.Clearing) - enabled(u.remove, j != nil && !u.snapshot.Clearing && j.State != model.Running && j.State != model.Scanning) if j == nil { u.selected = "" u.details.Hide() @@ -356,30 +325,39 @@ func (u *window) refresh() { u.details.Show() u.dropBar.Show() enabled(u.settings, !j.Locked && !u.snapshot.Clearing) - enabled(u.preview, len(j.ActiveVideos()) > 0 && j.ScanComplete && !j.Settings.NoMenu) enabled(u.cancel, j.State != model.Complete && j.State != model.Canceled) enabled(u.retry, u.mediaReady && !u.snapshot.Clearing && !u.snapshot.Busy[j.ID] && (j.State == model.Blocked || j.State == model.Paused || j.State == model.Canceled)) } u.refreshJobHeader(j) u.refreshFileSelection() u.files.Refresh() + u.refreshJobSelection() + u.queue.Refresh() counts := map[model.State]int{} + failed, attention := 0, 0 for _, j := range u.snapshot.Jobs { counts[j.State]++ + state, _ := jobAppearance(j) + if state == "Failed" { + failed++ + } else if state == "Needs attention" { + attention++ + } } - status := fmt.Sprintf("%d sets · %d running · %d complete · %d need attention", len(u.snapshot.Jobs), counts[model.Running], counts[model.Complete], counts[model.Blocked]) + status := fmt.Sprintf("%d jobs · %d completed · %d failed · %d need attention", len(u.snapshot.Jobs), counts[model.Complete], failed, attention) if u.snapshot.Error != "" { status = u.snapshot.Error } if u.snapshot.Clearing { - status = "Stopping active work and clearing the queue…" + status = "Stopping active work and removing jobs…" } if u.mediaChecking { status = "Checking FFmpeg / FFprobe…" } else if !u.mediaReady { - status = "FFmpeg setup required — use Tools to download or locate a compatible installation" + status = "FFmpeg setup required — use ! to download or locate a compatible installation" } u.status.SetText(status) + u.refreshStatusProgress() } func (u *window) rename() { @@ -401,123 +379,6 @@ func (u *window) rename() { } }, u.win) } -func (u *window) settingsDialog(id string, s model.Settings) { - standard := widget.NewSelect([]string{"PAL", "NTSC"}, nil) - standard.SetSelected(s.Standard) - medium := widget.NewSelect([]string{"DVD-5", "DVD-9"}, nil) - medium.SetSelected(s.Media) - packingMode := widget.NewSelect([]string{"Strict order", "Space efficiency"}, nil) - packingMode.SetSelected(s.Packing) - perPage := widget.NewEntry() - perPage.SetText(strconv.Itoa(s.TitlesPerPage)) - menuLayout := widget.NewSelect([]string{"Text", "Thumbnails"}, func(v string) { - n, _ := strconv.Atoi(perPage.Text) - if v == "Thumbnails" && n > 6 { - perPage.SetText("6") - } - }) - menuLayout.SetSelected(s.Layout) - stage := widget.NewCheck("Stage sources locally (recommended for network shares)", nil) - stage.SetChecked(s.StageLocally) - keep := widget.NewCheck("Keep intermediate media after success", nil) - keep.SetChecked(s.KeepWork) - noMenu := widget.NewCheck("No menu — start playback automatically (one included video)", nil) - noMenu.SetChecked(s.NoMenu) - if !s.NoMenu && (id == "" || u.selectedJob() == nil || len(u.selectedJob().ActiveVideos()) != 1) { - noMenu.Disable() - } - workers := widget.NewSelect([]string{"1", "2"}, nil) - workers.SetSelected(strconv.Itoa(s.Encoders)) - profile := widget.NewSelect([]string{model.ProfileBalanced, model.ProfileQuality}, nil) - profile.SetSelected(s.Profile()) - output := widget.NewEntry() - output.SetText(s.OutputDir) - work := widget.NewEntry() - work.SetText(s.WorkDir) - browse := func(entry *widget.Entry) { - u.action(func() error { - paths, err := platform.PickFolders(false) - if err == nil && len(paths) > 0 { - fyne.Do(func() { entry.SetText(paths[0]) }) - } - return err - }) - } - folder := func(entry *widget.Entry) fyne.CanvasObject { - return container.NewBorder(nil, nil, nil, widget.NewButtonWithIcon("", theme.FolderOpenIcon(), func() { browse(entry) }), entry) - } - appearance := widget.NewSelect([]string{"System", "Light", "Dark"}, nil) - appearance.SetSelected(s.Theme) - form := widget.NewForm(widget.NewFormItem("TV standard", standard), widget.NewFormItem("Disc capacity", medium), widget.NewFormItem("File allocation", packingMode), widget.NewFormItem("Menu layout", menuLayout), widget.NewFormItem("Titles per page", perPage), widget.NewFormItem("Encoding workers", workers), widget.NewFormItem("Output folder", folder(output)), widget.NewFormItem("Local work folder", folder(work)), widget.NewFormItem("Appearance", appearance)) - form.Append("Playback", noMenu) - form.Append("Encoding profile", profile) - note := "Applies to new and pending jobs. Started jobs retain their settings." - if id != "" { - note = "Settings for this folder. Locked when processing starts." - } - heading := widget.NewLabel(note + "\nBalanced: faster encoding and smaller files. Quality: higher bitrate and more detailed analysis.") - heading.Wrapping = fyne.TextWrapWord - var d dialog.Dialog - save := func() { - n, err := strconv.Atoi(perPage.Text) - if err != nil { - dialog.ShowError(fmt.Errorf("titles per page must be a whole number"), u.win) - return - } - next := s - next.Standard = standard.Selected - next.Media = medium.Selected - next.Packing = packingMode.Selected - next.Layout = menuLayout.Selected - next.TitlesPerPage = n - next.Encoders, _ = strconv.Atoi(workers.Selected) - next.EncodingProfile = profile.Selected - next.StageLocally = stage.Checked - next.KeepWork = keep.Checked - next.NoMenu = noMenu.Checked - next.OutputDir = strings.TrimSpace(output.Text) - next.WorkDir = strings.TrimSpace(work.Text) - next.Theme = appearance.Selected - if err = next.Validate(); err != nil { - dialog.ShowError(err, u.win) - return - } - u.action(func() error { - err := u.engine.SetSettings(id, next) - if err == nil { - fyne.Do(func() { - if id == "" { - u.applyTheme(next.Theme) - } - d.Hide() - }) - } - return err - }) - } - buttons := container.NewHBox(layout.NewSpacer(), widget.NewButton("Cancel", func() { d.Hide() }), widget.NewButton("Save settings", save)) - if id == "" { - buttons.Objects = append([]fyne.CanvasObject{widget.NewButton("Menu settings…", func() { d.Hide(); u.menuSettings("") })}, buttons.Objects...) - openLogs := widget.NewButtonWithIcon("Open logs folder", theme.FolderOpenIcon(), func() { - u.action(func() error { - if err := os.MkdirAll(u.engine.LogsDir(), 0755); err != nil { - return err - } - return platform.OpenFolder(u.engine.LogsDir()) - }) - }) - buttons.Objects = append([]fyne.CanvasObject{openLogs}, buttons.Objects...) - } - options := container.NewVBox(form, stage, keep) - if id == "" { - options.Add(u.updateSettings()) - } - content := container.NewBorder(heading, buttons, nil, nil, container.NewVScroll(options)) - d = dialog.NewCustomWithoutButtons("Settings", content, u.win) - d.Resize(fyne.NewSize(740, 600)) - d.Show() -} - func (u *window) diagnostics() { holder := container.NewStack(widget.NewLabel("Checking bundled tools…")) var d *dialog.CustomDialog @@ -539,10 +400,8 @@ func (u *window) diagnostics() { text.WriteString("\n") } fyne.Do(func() { - entry := widget.NewMultiLineEntry() - entry.SetText(text.String()) - entry.Disable() - holder.Objects = []fyne.CanvasObject{container.NewScroll(entry)} + _, view := newReadOnlyText(text.String()) + holder.Objects = []fyne.CanvasObject{container.NewScroll(view)} holder.Refresh() }) return nil diff --git a/internal/ui/ui_test.go b/internal/ui/ui_test.go index 01b23d9..189b04f 100644 --- a/internal/ui/ui_test.go +++ b/internal/ui/ui_test.go @@ -20,7 +20,7 @@ func TestJobTitleGetsAvailableWidth(t *testing.T) { w.Resize(fyne.NewSize(1160, 780)) u.refresh() w.Show() - if u.title.Text != j.Title || u.title.Size().Width < 200 { + if u.title.Text != j.Title || u.title.Size().Width < fyne.MeasureText(j.Title, 14, u.title.TextStyle).Width { t.Fatalf("title was squeezed out: text=%q size=%v", u.title.Text, u.title.Size()) } if !u.dropBar.Visible() || u.empty.Visible() { diff --git a/validation/PLAYBACK-UI.md b/validation/PLAYBACK-UI.md new file mode 100644 index 0000000..e9677b9 --- /dev/null +++ b/validation/PLAYBACK-UI.md @@ -0,0 +1,25 @@ +# Playback options and compact header + +Validated on 2026-10-30 on Windows. Generated media, isolated queue databases, +temporary builds and UI previews were placed in isolated local scratch space. +The user's GUI queue and read-only Exchange media were not used for these tests. + +- Header: removed menu, encoding-profile controls and PAL/disc/packing text; + Job settings and Open output share the lower action row. Tools is labeled `!`. +- Job settings: Balanced/Quality radios persist independently of defaults. + No menu can be toggled for single- and multi-video jobs. The menu editor + disables immediately when No menu is checked, including after reopening. +- Playback defaults: one included video selects no menu; multiple included + videos select menus. Explicit overrides persist and survive inclusion changes. +- `go test ./...`, `go vet ./...` and `git diff --check` passed. +- Real toolchain integration: generated three two-second clips, with 4:3, + 16:9 and 4:3 aspect ratios, authored an autoplay DVD ISO and decoded every + title using FFmpeg's DVD input. No visible menu assets were generated. +- The libVLC navigation checker observed titles **1 → 2 → 3**, then playback + ended without displaying a menu. Single-title autoplay regression tests + also passed for PAL and NTSC. + +Autoplay across aspect-specific titlesets uses command-only VMGM navigation +chains, following the domain rules in the +[dvdauthor documentation](https://dvdauthor.sourceforge.net/doc/dvdauthor.html). +Each chain contains one jump to keep command counts bounded.