-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1424 lines (1314 loc) · 45.9 KB
/
Copy pathmain.go
File metadata and controls
1424 lines (1314 loc) · 45.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//go:build windows && amd64
// NVENCForge — Required Notice: Copyright (c) 2026 burnersen — NVENCForge
// Licensed under the PolyForm Noncommercial License 1.0.0 (non-commercial use only).
// Full terms: LICENSE.md · https://polyformproject.org/licenses/noncommercial/1.0.0
// NVENCForge — H265 Batch-Konverter + DaVinci Resolve Workflow + Split/Join
//
// Version 2: HDR10-bewusstes Encoding (behält bei PQ/HLG-Material die
// Originalauflösung, hebt das Bitraten-Limit an und übernimmt Mastering-Display
// + MaxCLL), Unicode-fähige Dateinamen-Bereinigung (jedes Schriftsystem
// weltweit) und ein gehärteter FFmpeg-Auto-Downloader (Verbindungs-/Antwort-
// Timeouts). Basiert auf der 6-Datei-Architektur mit fmt.Errorf/%w-Wrapping.
//
// Kompilieren:
//
// go mod init NVENCForge
// go mod tidy
// go build -ldflags="-s -w" -o NVENCForge.exe
//
// Lange Pfade (>260 Zeichen) aktivieren (Admin-CMD):
//
// reg add "HKLM\SYSTEM\CurrentControlSet\Control\FileSystem" /v LongPathsEnabled /t REG_DWORD /d 1 /f
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"unicode"
"github.com/pterm/pterm"
)
// appVersion is shown in the startup header so the running build is obvious.
// Keep it in sync with the git tag / GitHub release on every release.
const appVersion = "1.4.0"
// ----------------------------------------------------------------------------
// Package-level sentinels and tool paths (set once in initTools, read-only after)
// ----------------------------------------------------------------------------
var (
ffmpegPath string
ffprobePath string
)
// errFFmpegStall is the sentinel reported by the stall-watchdog via
// context.WithCancelCause. After the run it is checked with errors.Is against
// context.Cause(runCtx).
var errFFmpegStall = errors.New("ffmpeg stall timeout")
// ----------------------------------------------------------------------------
// Video file classification
// ----------------------------------------------------------------------------
var videoExtensions = map[string]bool{
".mp4": true, ".mkv": true, ".ts": true, ".avi": true,
".mov": true, ".flv": true, ".wmv": true, ".webm": true,
".m4v": true, ".mts": true, ".m2ts": true,
}
// skipSuffixes / skipInputSuffixes recognise NVENCForge's own outputs so a
// re-run never re-encodes an already-processed file. They MUST list every suffix
// remuxSuffix() can emit (.h265/.h264/.av1) plus the legacy ".remux" fallback.
var skipSuffixes = []string{".h265", ".h264", ".remux", ".av1"}
var skipInputSuffixes = []string{".h265", ".h264", ".remux", ".preview", ".av1"}
// sourceTagKey is the global container metadata key NVENCForge writes into every
// output it produces (see sourceTagArgs). It records the exact source file name
// so the "already converted" skip check can tell a genuine resume apart from a
// name collision — two different sources whose cleaned names (and durations)
// happen to match. Matroska may store the key upper-cased, so read it back with
// a case-insensitive compare.
const sourceTagKey = "NVENCFORGE_SOURCE"
// ----------------------------------------------------------------------------
// Filename normalisation (integrated from CleanVideoNames)
// Applied ONLY to video basenames, NEVER to directory names.
// ----------------------------------------------------------------------------
var markersDrop = map[string]bool{
"ts": true, "m2ts": true,
"web": true, "webrip": true, "webdl": true, "dl": true,
"bluray": true, "bdrip": true, "remux": true, "bdremux": true,
"hdtv": true, "dvdrip": true, "dvd": true, "p2p": true,
"mp4": true, "mkv": true, "avi": true, "mov": true,
"m4v": true, "wmv": true, "flv": true,
"mpg": true, "mpeg": true, "webm": true,
"xvid": true, "divx": true,
"proper": true, "repack": true, "internal": true,
}
var markersKeep = map[string]string{
"h264": "h264", "h265": "h265",
"x264": "x264", "x265": "x265",
"hevc": "hevc", "av1": "av1", "vp9": "vp9",
"720p": "720p", "1080p": "1080p", "1440p": "1440p", "2160p": "2160p", "4k": "4k",
"hdr": "hdr", "hdr10": "hdr10", "sdr": "sdr",
"10bit": "10bit", "8bit": "8bit",
"aac": "aac", "ac3": "ac3", "eac3": "eac3", "dts": "dts", "opus": "opus",
}
var (
reHashDigit = regexp.MustCompile(`#(\d)`)
reMultiDot = regexp.MustCompile(`\.{2,}`)
)
// normalizeName cleans a base name: any Unicode letter or digit survives — so
// non-Latin scripts (CJK, Cyrillic, Greek, Arabic, …) are preserved for users
// worldwide — plus the dot separator and any user-approved characters from
// extraFilenameChars (NVENCForge_Config.ini). Whitespace ALWAYS becomes a dot
// (not overridable), everything else (punctuation, symbols, emoji, control
// chars) becomes a dot too and is then collapsed by reMultiDot.
func normalizeName(s string) string {
s = reHashDigit.ReplaceAllString(s, "Nr$1")
s = strings.ReplaceAll(s, "#", "")
s = strings.Map(func(r rune) rune {
switch {
case r == '.':
return r
case unicode.IsSpace(r):
return '.'
case strings.ContainsRune(appSettings.extraFilenameChars, r):
return r
case unicode.IsLetter(r) || unicode.IsDigit(r):
return r
}
return '.'
}, s)
s = reMultiDot.ReplaceAllString(s, ".")
return strings.Trim(s, ".")
}
func extractTrailingMarkers(name string) (string, []string) {
var keep []string
for {
idx := strings.LastIndex(name, ".")
if idx == -1 {
break
}
tok := strings.ToLower(name[idx+1:])
if markersDrop[tok] {
name = name[:idx]
continue
}
if c, ok := markersKeep[tok]; ok {
keep = append([]string{c}, keep...)
name = name[:idx]
continue
}
break
}
if len(keep) > 0 && strings.Contains(name, ".") {
var f []string
for _, t := range strings.Split(name, ".") {
if t != "" && !markersDrop[strings.ToLower(t)] {
f = append(f, t)
}
}
name = strings.Join(f, ".")
}
if name != "" {
nl := strings.ToLower(name)
if markersDrop[nl] {
name = ""
} else if c, ok := markersKeep[nl]; ok {
keep = append([]string{c}, keep...)
name = ""
}
}
return name, keep
}
// cleanFileBaseName returns "" when nothing usable remains; callers keep the
// original name in that case.
func cleanFileBaseName(baseNoExt string) string {
main, keep := extractTrailingMarkers(normalizeName(baseNoExt))
if len(keep) == 0 {
return main
}
if main == "" {
return strings.Join(keep, ".")
}
return main + "." + strings.Join(keep, ".")
}
// ----------------------------------------------------------------------------
// Data structures
// ----------------------------------------------------------------------------
type ffprobeOutput struct {
Streams []ffprobeStream `json:"streams"`
Format ffprobeFormat `json:"format"`
}
type ffprobeStream struct {
CodecType string `json:"codec_type"`
CodecName string `json:"codec_name"`
Width int `json:"width"`
Height int `json:"height"`
RFrameRate string `json:"r_frame_rate"`
BitRate string `json:"bit_rate"`
Channels int `json:"channels"`
ChannelLayout string `json:"channel_layout"`
SampleRate string `json:"sample_rate"`
FieldOrder string `json:"field_order"`
ColorSpace string `json:"color_space"`
ColorTransfer string `json:"color_transfer"`
ColorPrimaries string `json:"color_primaries"`
ColorRange string `json:"color_range"`
Tags map[string]string `json:"tags"`
Disposition ffprobeDisposition `json:"disposition"`
}
type ffprobeDisposition struct {
AttachedPic int `json:"attached_pic"`
Forced int `json:"forced"`
HearingImpaired int `json:"hearing_impaired"`
}
type ffprobeFormat struct {
Duration string `json:"duration"`
BitRate string `json:"bit_rate"`
Tags map[string]string `json:"tags"`
}
type AudioStreamInfo struct {
Codec string
Channels int
Layout string
Language string
Title string
SampleRate int
}
type VideoStats struct {
VideoCodec string
AudioCodec string
Channels int
AudioStreams []AudioStreamInfo
SubCodecs []string
Width int
Height int
FPSNum int
FPSDen int
DurationSec float64
BitrateBps int64
FileSizeMB float64
FieldOrder string
ColorSpace string
ColorTransfer string
ColorPrimaries string
ColorRange string
SourceTag string // sourceTagKey value found in the container (origin file name), "" if none
}
type ProcessResult struct {
InputFile string
OutputFile string
SavedMB float64
Success bool
Skipped bool
IsPreview bool
NoAudio bool // video-only fallback used: output has no sound, original kept
ErrMsg string
FailedAt time.Time
}
type lockInfo struct {
PID int `json:"pid"`
StartedAt time.Time `json:"started_at"`
Source string `json:"source"`
SizeMB float64 `json:"size_mb"`
OwnerImage string `json:"owner_image,omitempty"`
Hostname string `json:"hostname,omitempty"`
}
// ----------------------------------------------------------------------------
// pterm printers with custom prefixes
// ----------------------------------------------------------------------------
var (
pWarn = pterm.Warning.WithPrefix(pterm.Prefix{
Text: " WARNING ",
Style: pterm.NewStyle(pterm.BgYellow, pterm.FgBlack, pterm.Bold),
})
pErr = pterm.Error.WithPrefix(pterm.Prefix{
Text: " ERROR ",
Style: pterm.NewStyle(pterm.BgRed, pterm.FgWhite, pterm.Bold),
})
pOK = pterm.Success.WithPrefix(pterm.Prefix{
Text: " OK ",
Style: pterm.NewStyle(pterm.BgGreen, pterm.FgBlack, pterm.Bold),
})
pInfo = pterm.Info.WithPrefix(pterm.Prefix{
Text: " INFO ",
Style: pterm.NewStyle(pterm.BgCyan, pterm.FgBlack, pterm.Bold),
})
pAbort = pterm.Error.WithPrefix(pterm.Prefix{
Text: " ABORT ",
Style: pterm.NewStyle(pterm.BgRed, pterm.FgLightWhite, pterm.Bold),
})
// pFatal is never silenced by -debug. Reserved for run-blocking startup
// errors the user must see (missing GPU, FFmpeg setup) — unlike pErr, which
// reports per-operation failures and is suppressed without -debug.
pFatal = pterm.Error.WithPrefix(pterm.Prefix{
Text: " ERROR ",
Style: pterm.NewStyle(pterm.BgRed, pterm.FgWhite, pterm.Bold),
})
)
// ----------------------------------------------------------------------------
// Debug switch (hidden, developer-only)
// ----------------------------------------------------------------------------
// debugMode is set once at the start of main() and read-only afterwards. When
// false, all pErr output is routed to io.Discard so end users never see internal
// failure reasons. Intentionally undocumented (absent from help and tips).
var debugMode bool
// davinciMode is true when the process runs in -davinci mode (the DaVinci
// Resolve workflow). Set once at the start of main(); read by the abort
// handlers to pick the right message (there is no preview file in this mode).
var davinciMode bool
// splitMode / joinMode are true for the lossless -split / -join modes. Like
// -davinci they produce no preview file, so the abort handler treats them the
// same way (unfinished outputs are removed, nothing is salvaged).
var (
splitMode bool
joinMode bool
)
// consumeDebugFlag scans os.Args for a "-debug" token (case-insensitive),
// removes it so it is never treated as input, and reports whether it was present.
func consumeDebugFlag() bool {
found := false
out := os.Args[:0]
for _, a := range os.Args {
if strings.EqualFold(a, "-debug") {
found = true
continue
}
out = append(out, a)
}
os.Args = out
return found
}
// ----------------------------------------------------------------------------
// Signal handling
// ----------------------------------------------------------------------------
// setupSignalContext returns the root context and its cancel function.
// - First Ctrl+C: ctx is cancelled → runFFmpeg sends FFmpeg "q" (preview is
// cleanly finalized).
// - Second Ctrl+C: immediate hard exit.
func setupSignalContext() (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancel(context.Background())
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigChan
cancel()
fmt.Println()
if davinciMode || splitMode || joinMode {
pAbort.Println("Ctrl+C detected. Aborting — unfinished files will be removed...")
} else {
pAbort.Println("Ctrl+C detected. Finishing current task cleanly (preview will be saved)...")
}
<-sigChan
fmt.Print("\033[?25h\033[?7h")
fmt.Println()
pAbort.WithPrefix(pterm.Prefix{
Text: " FORCE QUIT ",
Style: pterm.NewStyle(pterm.BgRed, pterm.FgLightWhite, pterm.Bold),
}).Println("Second Ctrl+C detected. Exiting immediately!")
os.Exit(1)
}()
return ctx, cancel
}
// ----------------------------------------------------------------------------
// Tool detection: local folder first, then system PATH
// ----------------------------------------------------------------------------
// initTools resolves ffmpeg.exe and ffprobe.exe. If neither is found locally
// nor in PATH, it calls downloadFFmpeg to fetch them automatically.
func initTools() error {
exePath, err := os.Executable()
if err != nil {
return fmt.Errorf("main.go: initTools (os.Executable): %w", err)
}
exeDir := filepath.Dir(exePath)
resolve := func(name string) (string, bool) {
local := filepath.Join(exeDir, name)
if info, statErr := os.Stat(local); statErr == nil && !info.IsDir() {
return local, true
}
if p, lookErr := exec.LookPath(name); lookErr == nil {
return p, true
}
return "", false
}
fp, okF := resolve("ffmpeg.exe")
pp, okP := resolve("ffprobe.exe")
if !okF || !okP {
pInfo.Println("FFmpeg not found locally or in PATH. Attempting auto-download...")
if dlErr := downloadFFmpeg(exeDir); dlErr != nil {
return fmt.Errorf("main.go: initTools: auto-download failed: %w", dlErr)
}
// Re-resolve after download.
fp, okF = resolve("ffmpeg.exe")
pp, okP = resolve("ffprobe.exe")
if !okF || !okP {
return errors.New("main.go: initTools: ffmpeg.exe / ffprobe.exe still missing after download")
}
}
ffmpegPath = fp
ffprobePath = pp
return nil
}
// ----------------------------------------------------------------------------
// Hardware check: NVENC HEVC 10-bit dummy encode + CAS filter probe
// ----------------------------------------------------------------------------
// nvencAdvancedAQ is true while the GPU supports Temporal AQ + multipass (Turing
// / RTX 20 series or newer). checkHardwareCapabilities clears it for older cards
// (Pascal/Volta) so the real encode drops -temporal-aq/-multipass instead of
// failing on every single file.
var nvencAdvancedAQ = true
// checkHardwareCapabilities probes with the SAME flags the real encode uses, so a
// card that passes here cannot fail later on every file. HEVC B-frames AND Temporal
// AQ/multipass share the Turing+ gate; older cards (Maxwell-2/Pascal/Volta) are
// retried once fully degraded and then run without those features instead of
// refusing to start. Maxwell-1 / no-NVENC cards fail the 10-bit probe outright.
func checkHardwareCapabilities() error {
pInfo.Println("Checking GPU capabilities (NVENC HEVC 10-bit)...")
tryEncode := func(bf int, advancedAQ bool) (string, error) {
args := []string{
"-v", "error", "-f", "lavfi",
"-i", "color=c=black:s=1920x1080:d=1",
"-c:v", "hevc_nvenc", "-profile:v", "main10", "-pix_fmt", "p010le",
"-preset", appSettings.nvencPreset, "-tune", "hq",
"-rc-lookahead", strconv.Itoa(appSettings.nvencLookahead),
"-spatial-aq", "1",
}
if advancedAQ {
args = append(args, "-multipass", "qres", "-temporal-aq", "1")
}
if bf > 0 {
args = append(args, "-bf", strconv.Itoa(bf), "-b_ref_mode", "2")
}
args = append(args, "-f", "null", "-")
dummy := exec.Command(ffmpegPath, args...)
dummy.SysProcAttr = &syscall.SysProcAttr{CreationFlags: winCREATE_NO_WINDOW}
out, err := dummy.CombinedOutput()
return strings.TrimSpace(string(out)), err
}
if out, err := tryEncode(appSettings.bFrames, true); err != nil {
// HEVC B-frames and Temporal AQ share the same Turing+ gate, so a single
// fully-degraded retry (no B-frames, no Temporal AQ/multipass) decides it:
// succeeds → pre-Turing card (Pascal/Volta), keep encoding without those
// features; fails → genuine rejection (Maxwell-1, no 10-bit, no NVENC).
if _, retryErr := tryEncode(0, false); retryErr == nil {
if appSettings.bFrames > 0 {
appSettings.bFrames = 0
pWarn.Println("GPU does not support HEVC B-frames — continuing without B-frames.")
pWarn.Println("Set 'bFrames=0' in NVENCForge_Config.ini to make this permanent.")
}
nvencAdvancedAQ = false
pWarn.Println("GPU does not support Temporal AQ / multipass (needs RTX 20 series or newer) — continuing without them.")
} else {
return fmt.Errorf("main.go: checkHardwareCapabilities: NVENC dummy encode failed: %v | %s",
err, out)
}
}
filters := exec.Command(ffmpegPath, "-v", "error", "-filters")
filters.SysProcAttr = &syscall.SysProcAttr{CreationFlags: winCREATE_NO_WINDOW}
out, err := filters.Output()
if err != nil {
return fmt.Errorf("main.go: checkHardwareCapabilities: cannot read FFmpeg filter list: %w", err)
}
hasCAS := false
for _, ln := range strings.Split(string(out), "\n") {
f := strings.Fields(ln)
if len(f) >= 2 && f[1] == "cas" {
hasCAS = true
break
}
}
if !hasCAS {
return errors.New("main.go: checkHardwareCapabilities: CAS filter missing in FFmpeg build")
}
return nil
}
// checkAV1Capability probes a 10-bit av1_nvenc dummy encode. AV1 encoding
// needs an RTX 40 series GPU (Ada) or newer; older cards fail here cleanly.
func checkAV1Capability() error {
pInfo.Println("Checking GPU capabilities (NVENC AV1 10-bit)...")
args := []string{
"-v", "error", "-f", "lavfi",
"-i", "color=c=black:s=1920x1080:d=1",
"-c:v", "av1_nvenc", "-pix_fmt", "p010le",
"-f", "null", "-",
}
dummy := exec.Command(ffmpegPath, args...)
dummy.SysProcAttr = &syscall.SysProcAttr{CreationFlags: winCREATE_NO_WINDOW}
out, err := dummy.CombinedOutput()
if err != nil {
return fmt.Errorf("main.go: checkAV1Capability: AV1 dummy encode failed: %v | %s",
err, strings.TrimSpace(string(out)))
}
return nil
}
// ----------------------------------------------------------------------------
// Lock management
// ----------------------------------------------------------------------------
func readLockInfo(lockPath string) (lockInfo, error) {
var info lockInfo
data, err := os.ReadFile(lockPath)
if err != nil {
return info, fmt.Errorf("main.go: readLockInfo (ReadFile): %w", err)
}
if err := json.Unmarshal(data, &info); err != nil {
return info, fmt.Errorf("main.go: readLockInfo (Unmarshal): %w", err)
}
if info.StartedAt.IsZero() {
if st, statErr := os.Stat(lockPath); statErr == nil {
info.StartedAt = st.ModTime()
}
}
return info, nil
}
// removeStaleLock returns (removed bool, foreignHost string).
// If foreignHost != "" the lock belongs to another machine and is never removed.
func removeStaleLock(lockPath string) (bool, string) {
info, err := readLockInfo(lockPath)
if err != nil {
// errors.Is unwraps the fmt.Errorf chain from readLockInfo
// (os.IsNotExist would never match the wrapped error).
if errors.Is(err, fs.ErrNotExist) {
return true, ""
}
data, readErr := os.ReadFile(lockPath)
if readErr == nil && len(bytes.TrimSpace(data)) == 0 {
_ = os.Remove(lockPath)
return true, ""
}
st, statErr := os.Stat(lockPath)
if statErr != nil {
if os.IsNotExist(statErr) {
return true, ""
}
return false, ""
}
if time.Since(st.ModTime()) > 5*time.Minute {
_ = os.Remove(lockPath)
return true, ""
}
return false, ""
}
localHost, _ := os.Hostname()
if info.Hostname != "" && localHost != "" &&
!strings.EqualFold(info.Hostname, localHost) {
return false, info.Hostname
}
if isLockOwnerAlive(info) {
return false, ""
}
_ = os.Remove(lockPath)
return true, ""
}
// FIX LOCK-02: Sync() vor Close() stellt sicher, dass der JSON-Inhalt auf Disk
// landet bevor andere Instanzen das Lockfile lesen können.
func acquireProcessingLock(lockPath string, sizeMB float64, sourceFile string) (func(), error) {
exePath, _ := os.Executable()
hostname, _ := os.Hostname()
payload := lockInfo{
PID: os.Getpid(),
StartedAt: time.Now().UTC(),
Source: filepath.Base(sourceFile),
SizeMB: sizeMB,
OwnerImage: exePath,
Hostname: hostname,
}
encoded, _ := json.MarshalIndent(payload, "", " ")
if len(encoded) == 0 {
encoded = []byte(fmt.Sprintf(
`{"pid":%d,"started_at":%q,"source":%q,"size_mb":%.2f,"owner_image":%q,"hostname":%q}`,
payload.PID, payload.StartedAt.Format(time.RFC3339),
payload.Source, payload.SizeMB, payload.OwnerImage, payload.Hostname))
}
for tries := 0; tries < 3; tries++ {
lf, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
if err == nil {
if _, wErr := lf.Write(encoded); wErr != nil {
_ = lf.Close()
_ = os.Remove(lockPath)
return nil, fmt.Errorf("main.go: acquireProcessingLock (write): %w", wErr)
}
_ = lf.Sync()
_ = lf.Close()
return func() { _ = os.Remove(lockPath) }, nil
}
if !os.IsExist(err) {
return nil, fmt.Errorf("main.go: acquireProcessingLock (OpenFile): %w", err)
}
removed, foreignHost := removeStaleLock(lockPath)
if foreignHost != "" {
return nil, fmt.Errorf("main.go: acquireProcessingLock: already being processed on PC %q", foreignHost)
}
if removed {
continue
}
return nil, fmt.Errorf("main.go: acquireProcessingLock: lock active: %s", filepath.Base(lockPath))
}
return nil, fmt.Errorf("main.go: acquireProcessingLock: could not acquire lock: %s", filepath.Base(lockPath))
}
// ----------------------------------------------------------------------------
// Argument parsing
// ----------------------------------------------------------------------------
func (cfg *AppConfig) parseArgs(args []string) []string {
var rest []string
explicitBitrate := false
sawAutoCQFlag, sawNoAutoCQ := false, false
for i := 0; i < len(args); i++ {
arg := args[i]
if strings.EqualFold(arg, "-shutdown") {
cfg.autoShutdown = true
pInfo.Println("Auto-shutdown after completion enabled.")
continue
}
if strings.EqualFold(arg, "-orig") || strings.EqualFold(arg, "-original") {
cfg.keepOriginal = true
pInfo.Println("Original resolution mode enabled: no downscaling.")
continue
}
if strings.EqualFold(arg, "-copyaudio") || strings.EqualFold(arg, "-ca") {
cfg.copyAudio = true
pInfo.Println("Audio copy mode enabled: streams copied 1:1 (no AAC re-encode).")
continue
}
if strings.EqualFold(arg, "-av1") {
cfg.av1 = true
pInfo.Println("AV1 mode enabled: encoding with av1_nvenc instead of H.265.")
continue
}
if strings.EqualFold(arg, "-apple") {
cfg.apple = true
pInfo.Println("Apple mode enabled: output as an iOS-ready MP4 (H.265/hvc1 + AAC + faststart).")
continue
}
if strings.EqualFold(arg, "-keep") {
cfg.keepSource = true
pInfo.Println("Keep-source mode enabled: originals are NOT moved to the recycle bin.")
continue
}
if strings.EqualFold(arg, "-autocq") {
cfg.autoCQ = true
sawAutoCQFlag = true
continue
}
if strings.EqualFold(arg, "-noautocq") {
cfg.autoCQ = false
sawNoAutoCQ = true
continue
}
if strings.EqualFold(arg, "-cq") {
// Two-token flag: the CQ value follows as its own argument. The
// valid upper bound depends on the codec (H.265 1-51, AV1 1-63),
// which is only known after the whole loop (-av1 may follow -cq),
// so the range is checked there.
if i+1 < len(args) {
if n, err := strconv.Atoi(args[i+1]); err == nil {
i++ // the number belongs to -cq, even when out of range
if n >= 1 {
cfg.forcedCQ = n
} else {
pWarn.Printf("-cq %d is not a valid CQ (must be positive) — ignored.\n", n)
}
continue
}
}
pWarn.Println("-cq needs a CQ number (e.g. \"-cq 28\") — ignored.")
continue
}
if len(arg) > 1 && arg[0] == '-' {
if _, errStat := os.Stat(arg); os.IsNotExist(errStat) {
if n, err := strconv.ParseInt(arg[1:], 10, 64); err == nil && n > 0 {
cfg.maxBitrateKbps = n
explicitBitrate = true
pInfo.Printf("Max bitrate set manually: %sk\n",
pterm.LightCyan(fmt.Sprintf("%d", cfg.maxBitrateKbps)))
continue
}
// Looks like an option but matches nothing known and no file on
// disk: warn instead of silently ignoring (typos like -shutdwon).
if strings.EqualFold(arg, "-davinci") || strings.EqualFold(arg, "-streams") ||
strings.EqualFold(arg, "-split") || strings.EqualFold(arg, "-join") {
pWarn.Printf("'%s' must be the FIRST argument — ignored here.\n", strings.ToLower(arg))
pWarn.Printf("Example: NVENCForge.exe %s file.mkv\n", strings.ToLower(arg))
} else {
pWarn.Printf("Unknown option %q ignored. Available: -NNNN, -cq, -orig/-original, -copyaudio/-ca, -av1, -apple, -autocq, -noautocq, -keep, -shutdown, -davinci, -split, -join\n", arg)
}
continue
}
}
rest = append(rest, arg)
}
// -apple targets the iOS Photos app, which cannot decode AV1 at all, so the
// Apple output is always H.265 (hvc1). -av1 is overridden here, before the
// codec-dependent CQ range and bitrate caps below are resolved.
if cfg.apple && cfg.av1 {
cfg.av1 = false
pWarn.Println("-apple forces H.265: iOS cannot play AV1 — the -av1 flag is ignored for this run.")
}
// -cq uses the active codec's CQ scale: H.265 1-51, AV1 1-63. The same
// number means a different quality per codec, so the upper bound depends
// on the -av1 flag, which is only fully known now (it may follow -cq).
if cfg.forcedCQ > 0 {
maxCQ, scaleLabel := 51, "H.265 scale 1-51"
if cfg.av1 {
maxCQ, scaleLabel = 63, "AV1 scale 1-63"
}
if cfg.forcedCQ > maxCQ {
pWarn.Printf("-cq %d is out of range (%s) — ignored.\n", cfg.forcedCQ, scaleLabel)
cfg.forcedCQ = 0
}
}
// A manual -cq exists exactly for the runs where the automatic pick is
// unwanted, so it wins over every Auto-CQ source (flag or config).
if cfg.forcedCQ > 0 {
cfg.autoCQ = false
pInfo.Printf("Manual CQ %d forced for this run — Auto-CQ disabled.\n", cfg.forcedCQ)
}
// Auto-CQ can come from the -autocq flag or the config (autoCQ=true);
// the last flag on the command line wins, so the status is only known —
// and reported once — after the whole loop. It works for both codecs, each
// on its own CQ-scale profile (H.265 anchors 26/30, AV1 anchors 24/32).
autoCQCodec := "H.265"
if cfg.av1 {
autoCQCodec = "AV1"
}
switch {
case cfg.autoCQ && sawAutoCQFlag:
pInfo.Printf("Auto-CQ mode enabled: CQ per file via sampled VMAF measurement (%s).\n", autoCQCodec)
case cfg.autoCQ:
pInfo.Printf("Auto-CQ mode enabled via configuration: CQ per file via sampled VMAF measurement (%s).\n", autoCQCodec)
case sawNoAutoCQ && (sawAutoCQFlag || appSettings.autoCQ):
pInfo.Println("Auto-CQ disabled for this run (-noautocq) — using the configured CQ.")
}
// AV1 reaches H.265 quality at ~25-30% less bitrate, so the AV1 mode has
// its own (lower) caps. An explicit -NNNN always wins.
if !explicitBitrate {
switch {
case cfg.av1 && cfg.keepOriginal:
cfg.maxBitrateKbps = appSettings.av1MaxBitrateOriginal
pInfo.Printf("Max bitrate (AV1 Original mode): %sk\n",
pterm.LightCyan(fmt.Sprintf("%d", cfg.maxBitrateKbps)))
case cfg.av1:
cfg.maxBitrateKbps = appSettings.av1MaxBitrate1080p
pInfo.Printf("Max bitrate (AV1 mode): %sk\n",
pterm.LightCyan(fmt.Sprintf("%d", cfg.maxBitrateKbps)))
case cfg.keepOriginal:
cfg.maxBitrateKbps = appSettings.maxBitrateOriginal
pInfo.Printf("Max bitrate (Original mode): %sk\n",
pterm.LightCyan(fmt.Sprintf("%d", appSettings.maxBitrateOriginal)))
}
}
cfg.inputArgs = rest
return rest
}
func collectInputFiles(cfg *AppConfig, args []string) []string {
if len(args) > 0 {
var out []string
for _, a := range args {
abs, err := filepath.Abs(a)
if err != nil {
continue
}
abs = getLongPathName(abs)
info, err := os.Stat(abs)
if err != nil {
continue
}
if !info.IsDir() {
if videoExtensions[strings.ToLower(filepath.Ext(abs))] {
out = append(out, abs)
}
continue
}
_ = filepath.WalkDir(abs, func(path string, d os.DirEntry, err error) error {
if err != nil {
return nil
}
if d.IsDir() {
if strings.EqualFold(d.Name(), "output") {
return filepath.SkipDir
}
return nil
}
if videoExtensions[strings.ToLower(filepath.Ext(path))] {
out = append(out, path)
}
return nil
})
}
return out
}
workDir := getWorkDir(cfg)
entries, err := os.ReadDir(workDir)
if err != nil {
return nil
}
var out []string
for _, e := range entries {
if !e.IsDir() && videoExtensions[strings.ToLower(filepath.Ext(e.Name()))] {
out = append(out, filepath.Join(workDir, e.Name()))
}
}
return out
}
func getWorkDir(cfg *AppConfig) string {
if len(cfg.inputArgs) > 0 {
if info, err := os.Stat(cfg.inputArgs[0]); err == nil && info.IsDir() {
return cfg.inputArgs[0]
}
return filepath.Dir(cfg.inputArgs[0])
}
if wd, err := os.Getwd(); err == nil {
return wd
}
exe, _ := os.Executable()
return filepath.Dir(exe)
}
// ----------------------------------------------------------------------------
// Utility helpers
// ----------------------------------------------------------------------------
func waitForEnter() {
fmt.Print("\nPress Enter to exit...")
_, _ = bufio.NewReader(os.Stdin).ReadString('\n')
}
func formatDuration(seconds float64) string {
if seconds < 0 || seconds > 360000 {
return "-:--"
}
t := int(seconds)
h, m, s := t/3600, (t%3600)/60, t%60
if h > 0 {
return fmt.Sprintf("%d:%02d:%02d", h, m, s)
}
return fmt.Sprintf("%d:%02d", m, s)
}
func getFileSizeMB(path string) float64 {
i, e := os.Stat(path)
if e != nil {
return 0
}
return float64(i.Size()) / 1048576
}
// FIX LEAK-04: explicit f.Close() per iteration (no defer inside loop).
func writeErrorLog(cfg *AppConfig, results []ProcessResult) {
groups := make(map[string][]string)
for _, r := range results {
if !r.Success && !r.Skipped && !r.IsPreview {
ts := r.FailedAt
if ts.IsZero() {
ts = time.Now()
}
dir := filepath.Dir(r.InputFile)
if dir == "" {
dir = getWorkDir(cfg)
}
line := fmt.Sprintf("[%s] %s: %s",
ts.Format("2006-01-02 15:04:05"),
filepath.Base(r.InputFile), r.ErrMsg)
groups[dir] = append(groups[dir], line)
}
}
if len(groups) == 0 {
return
}
header := fmt.Sprintf("=== %s ===\n", time.Now().Format("2006-01-02 15:04:05"))
for dir, lines := range groups {
logPath := filepath.Join(dir, "error_report.txt")
f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
pWarn.Printf("Could not write error log: %v\n", err)
continue
}
if _, err := f.WriteString(header); err != nil {
pWarn.Printf("Error log: writing header failed: %v\n", err)
_ = f.Close()
continue
}
if _, err := f.WriteString(strings.Join(lines, "\n") + "\n"); err != nil {
pWarn.Printf("Error log: writing entries failed: %v\n", err)
}
_ = f.Close()
}
}
// ----------------------------------------------------------------------------
// printActiveSettings
// ----------------------------------------------------------------------------
func printActiveSettings(cfg *AppConfig) {
s := appSettings
pterm.DefaultHeader.
WithFullWidth().
WithBackgroundStyle(pterm.NewStyle(pterm.BgDarkGray)).
WithTextStyle(pterm.NewStyle(pterm.FgLightWhite, pterm.Bold)).
Println("Active Settings (NVENCForge_Config.ini)")
fmt.Println()
bitrate := s.maxBitrate1080p
bitrateActive := false
resValue := fmt.Sprintf("%d p", s.maxResolution)
resActive := false
autoShutdown := s.autoShutdown
if cfg != nil {
if cfg.maxBitrateKbps != s.maxBitrate1080p {
bitrate = cfg.maxBitrateKbps
bitrateActive = true
}
if cfg.keepOriginal {
resValue = "original"
resActive = true
}
autoShutdown = cfg.autoShutdown
}
shutdownVal := "off"
shutdownColor := "gray"
if autoShutdown {
shutdownVal = "on"
shutdownColor = "yellow"
}
// -copyaudio switches the whole audio pipeline to 1:1 copy; the AAC
// bitrate settings shown above it are not applied then.
audioMode := "AAC if needed"
audioModeActive := false
if cfg != nil && cfg.copyAudio {
audioMode = "copy 1:1"
audioModeActive = true
}
// -av1 switches encoder, CQ scale (av1TargetCQ) and bitrate caps; the
// B-frame setting is not used by av1_nvenc.
videoCodec := "H.265"
codecActive := false
cqVal := s.targetCQ
bfVal := fmt.Sprintf("%d", s.bFrames)