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, "