summaryrefslogtreecommitdiff
path: root/transcode.sh
blob: 41a22abffe9623fd9def76fdf6e7eac4bf5f770d (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
#!/usr/bin/env bash

# SPDX-FileCopyrightText: 2025 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

###############################################################################
# DESCRIPTION
#     Batch transcode helper for media files using ffmpeg.
#
#     The actual ffmpeg encoding parameters are provided by *presets* stored in:
#         ${XDG_CONFIG_HOME:-$HOME/.config}/transcode.sh/presets/<name>.sh
#
#     Each preset is a small bash snippet that must set an array named `ffargs`,
#     for example:
#         ffargs=( -c:v:0 libsvtav1 -crf 30 -preset 6 -pix_fmt "$output_pixel_format" )
#
#     The following variables are available to presets at source time:
#         input_codec          - video codec of the input file (e.g. h264, hevc)
#         input_pixel_format   - pixel format after yuvj* normalisation (e.g. yuv420p)
#         output_pixel_format  - recommended output pixel format, derived from the
#                                input to preserve chroma subsampling and bit depth
#         input_frame_rate     - raw frame rate fraction as reported by ffprobe
#                                (e.g. 30000/1001, 25/1, 60/1)
#         input_fps            - input_frame_rate rounded to nearest integer
#                                (e.g. 30, 25, 60)
#         output_gop_size      - recommended GOP size derived from input_fps
#                                (≈ 5 s of video, capped at 300 frames)
#
#     Note: Presets are sourced as shell code. Only use trusted presets.
#
#     An optional TOML configuration file may be placed at:
#         ${XDG_CONFIG_HOME:-$HOME/.config}/transcode.sh/config.toml
#
#     It may set defaults for any option, for example:
#         [encoding]
#         preset = "av1"
#         nice   = 10
#
#         [skip]
#         codecs = ["av1", "hevc"]
#
#         [saving]
#         enabled = false
#         file    = "transcode_savings"
#
#     CLI flags always take precedence over config file values.
#     Requires tomlq (https://github.com/nicowillis/tomlq) when config.toml
#     is present.
#
#     NOTE: skip.conf is deprecated. If it exists alongside config.toml the
#     script will warn and ignore it. Migrate codecs to [skip] codecs in
#     config.toml.
#
# NOTES
#     This script respects the NO_COLOR standard (https://no-color.org/).
#
# AUTHOR
#     Dennis Fink <me+coding@dennisfink.me>
###############################################################################

# TRACE enables bash execution tracing and is intended for debugging control
# flow / expansions. DEBUG enable structured debug messages (see debug()) and
# is intended for high-level state reporting.
#
# Recommended usage:
#   TRACE=1 ./transcode.sh ...  # show every command bash executes
#   DEBUG=1 ./transcode.sh .... # show script-defined debug messages

TRACE=${TRACE:-0}
if [[ $TRACE -eq 1 ]]; then
  set -o xtrace
fi

###############################################################################
# SHELL SCRIPT HARDENING
#
# This script enables strict and predictable behavior for improved safety,
# security, and debuggability. These measures help avoid common pitfalls
# such as accidental globbing, unexpected alias expansion, silent failures,
# or unintended word splitting.
###############################################################################

# Unalias everything to avoid unexpected alias expansion
command unalias -a

# Clear the shell command hash table to avoid stale command lookups
hash -r

# Set a safe IFS to prevent word-splitting vulnerabilities
IFS=$'\n\t'

# Set a secure default file creation mask (controls default permissions)
umask 002

# Ensure ERR traps are inherited by functions and subshells
set -o errtrace
# Treat use of undefined variables as an error and exit
set -o nounset
# Make pipelines fail if any command in the pipeline fails
set -o pipefail

###############################################################################
# SCRIPT METADATA
#
# These variables describe the script and are used for the --version output
# and for informational messages. They are marked readonly to prevent
# accidental modification at runtime.
###############################################################################
readonly SCRIPTNAME=${0##*/}
readonly DESCRIPTION="Batch transcode helper for media files using ffmpeg."
readonly DATE_OF_CREATION=2025-08-06
readonly DATE_OF_REVISION=2026-05-08
readonly VERSION=1.0.1
readonly AUTHOR="Dennis Fink <me+coding@dennisfink.me>"
readonly LICENSE="BSD-3-Clause"

###############################################################################
# GLOBAL VARIABLES
###############################################################################

ALL_OFF=""
BOLD=""
RED=""
GREEN=""
YELLOW=""
BLUE=""
MAGENTA=""
CYAN=""

DEBUG=${DEBUG:-0}
QUIET=0
VERBOSE=0

CONTINUE_ON_FAIL=0
DRY_RUN=0
ENCODE_FILE=""
HWACCEL=1
HWACCEL_VALUE="auto"
NICE_VALUE=19
ONLY_IF_SMALLER=0
PRESET_NAME="default"
SAVING=0
SAVING_FILE="transcode_savings"
SAVING_FILE_EXPLICIT=0
VERIFY_OUTPUT=1
declare -A SKIP_CODECS

REMAINING_ARGS=()

TMP_FILES=()

readonly PRESET_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/transcode.sh/presets"
CONFIG_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/transcode.sh/config.toml"
# Kept for deprecation warning only — no longer read for codec data.
readonly SKIP_CODECS_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/transcode.sh/skip.conf"

# Sentinel flags: set to 1 by the CLI option parser so that load_config()
# knows which values have already been provided and must not be overridden.
_CLI_CONFIG_FILE=0
_CLI_CONTINUE=0
_CLI_HWACCEL=0
_CLI_NICE=0
_CLI_ONLY_IF_SMALLER=0
_CLI_PRESET=0
_CLI_QUIET=0
_CLI_SAVING=0
_CLI_SAVING_FILE=0
_CLI_VERBOSE=0
_CLI_VERIFY_OUTPUT=0

###############################################################################
# EXIT CODES
###############################################################################

EXIT_OK=0
EXIT_RUNTIME_FAILURE=1
EXIT_USAGE_ERROR=2
EXIT_CONFIG_ERROR=3
EXIT_MISSING_DEPENDENCY=127
readonly EXIT_OK EXIT_RUNTIME_FAILURE EXIT_USAGE_ERROR EXIT_CONFIG_ERROR EXIT_MISSING_DEPENDENCY

##############################################################################
# FUNCTIONS
#
# This section defines the helper functions used throughout the script. They
# handle formatted output, error reporting, version information, utilities
# functions and runtime behaviour such as displaying usage instructions.
###############################################################################

error() {
  local mesg="$1"
  shift
  printf "${BOLD}${RED}==> ERROR:${ALL_OFF} ${BOLD}%s${ALL_OFF} %s\n" "$mesg" "$@" >&2
}

msg() {
  if [[ $QUIET -eq 0 ]]; then
    local mesg="$1"
    shift
    printf "${BOLD}${GREEN}==>${ALL_OFF} ${BOLD}%s${ALL_OFF} %s\n" "$mesg" "$@"
  fi
}

warn() {
  if [[ $QUIET -eq 0 ]]; then
    local mesg="$1"
    shift
    printf "${BOLD}${YELLOW}==>${ALL_OFF} ${BOLD}%s${ALL_OFF} %s\n" "$mesg" "$@"
  fi
}

verbose() {
  if [[ $VERBOSE -eq 1 && $QUIET -eq 0 ]]; then
    local mesg="$1"
    shift
    printf "${BOLD}${BLUE}==>${ALL_OFF} ${BOLD}%s${ALL_OFF} %s\n" "$mesg" "$@"
  fi
}

debug() {
  if [[ $DEBUG -eq 1 ]]; then
    local mesg="$1"
    shift
    printf "${BOLD}${MAGENTA}==> DEBUG:${ALL_OFF} ${BOLD}%s${ALL_OFF} %s\n" "$mesg" "$@"
  fi
}

print_help() {
  printf "${BOLD}${MAGENTA}%s${ALL_OFF} - ${BOLD}${CYAN}%s${ALL_OFF} - ${BOLD}%s${ALL_OFF}

${BOLD}${BLUE}Usage:${ALL_OFF} ${BOLD}${MAGENTA}%s${ALL_OFF} ${BOLD}${YELLOW}[OPTION]... [--]${ALL_OFF} ${BOLD}${GREEN}FILE...${ALL_OFF}

Long options that take a value also accept ${BOLD}${YELLOW}--option${ALL_OFF}${BOLD}${CYAN}=${ALL_OFF}${BOLD}${GREEN}VALUE${ALL_OFF} syntax.

${BOLD}${BLUE}Encoding options:${ALL_OFF}
  ${BOLD}${YELLOW}-p, --preset${ALL_OFF} ${BOLD}${GREEN}NAME${ALL_OFF}           load ffmpeg arguments from a preset (default: ${BOLD}${RED}%s${ALL_OFF})
  ${BOLD}${YELLOW}-N, --nice${ALL_OFF} ${BOLD}${GREEN}VALUE${ALL_OFF}            nice value for ffmpeg (default: ${BOLD}${RED}%d${ALL_OFF})
  ${BOLD}${YELLOW}-n, --dry-run${ALL_OFF}               show what would be done, do not run ffmpeg
  ${BOLD}${YELLOW}    --hwaccel${ALL_OFF} ${BOLD}${GREEN}[METHOD]${ALL_OFF}      enable hardware acceleration; METHOD defaults to ${BOLD}${RED}auto${ALL_OFF}
                              if omitted
  ${BOLD}${YELLOW}    --no-hwaccel${ALL_OFF}            disable hardware acceleration (do not pass ${BOLD}${YELLOW}-hwaccel${ALL_OFF} to ffmpeg)
  ${BOLD}${YELLOW}-l, --only-if-smaller${ALL_OFF}       only replace original if new file is smaller
      ${BOLD}${YELLOW}--no-only-if-smaller${ALL_OFF}    do replace original even if new file is bigger
  ${BOLD}${YELLOW}-c, --continue${ALL_OFF}              continue with the next file even if ffmpeg fails
      ${BOLD}${YELLOW}--no-continue${ALL_OFF}           do not continue with the next file if ffmpeg fails
      ${BOLD}${YELLOW}--verify-output${ALL_OFF}         probe output with ffprobe before replacing original (default)
      ${BOLD}${YELLOW}--no-verify-output${ALL_OFF}      skip the post-encode integrity check

${BOLD}${BLUE}Input options:${ALL_OFF}
      ${BOLD}${YELLOW}--config-file${ALL_OFF} ${BOLD}${GREEN}FILE${ALL_OFF}      load configuration from FILE instead of the default path
  ${BOLD}${YELLOW}-f, --encode-file${ALL_OFF} ${BOLD}${GREEN}FILE${ALL_OFF}      file containing a list of files to encode
  ${BOLD}${YELLOW}-S, --skip-codec${ALL_OFF} ${BOLD}${GREEN}LIST${ALL_OFF}       skip files with these codecs;
                              ${BOLD}${GREEN}LIST${ALL_OFF} is comma, space, or colon separated

${BOLD}${BLUE}Savings log options:${ALL_OFF}
  ${BOLD}${YELLOW}-s, --saving${ALL_OFF}                log filesize savings to a TSV file
      ${BOLD}${YELLOW}--saving-file${ALL_OFF} ${BOLD}${GREEN}FILE${ALL_OFF}      path for the savings log (default: ${BOLD}${RED}%s${ALL_OFF})

${BOLD}${BLUE}Output options:${ALL_OFF}
  ${BOLD}${YELLOW}-q, --quiet${ALL_OFF}                 suppress all output; takes precedence over ${BOLD}${YELLOW}-v${ALL_OFF}
  ${BOLD}${YELLOW}-v, --verbose${ALL_OFF}               explain what is being done
      ${BOLD}${YELLOW}--color${ALL_OFF}                 force colored output
      ${BOLD}${YELLOW}--no-color${ALL_OFF}              disable colored output

${BOLD}${BLUE}General options:${ALL_OFF}
  ${BOLD}${YELLOW}-h, --help${ALL_OFF}                  display this help and exit
      ${BOLD}${YELLOW}--version${ALL_OFF}               output version information and exit

${BOLD}${BLUE}Configuration files:${ALL_OFF}
  ${BOLD}${CYAN}%s/<NAME>.sh${ALL_OFF}
    preset file; must define a bash array ${BOLD}${GREEN}ffargs${ALL_OFF} with the ffmpeg encoding arguments.
    the following variables are available to presets:
      ${BOLD}${GREEN}input_codec${ALL_OFF}          e.g. h264, hevc
      ${BOLD}${GREEN}input_pixel_format${ALL_OFF}   e.g. yuv420p
      ${BOLD}${GREEN}output_pixel_format${ALL_OFF}  derived from input
      ${BOLD}${GREEN}input_frame_rate${ALL_OFF}     raw fraction from ffprobe (e.g. 30000/1001)
      ${BOLD}${GREEN}input_fps${ALL_OFF}            input_frame_rate rounded to nearest integer
      ${BOLD}${GREEN}output_gop_size${ALL_OFF}       ~5 s GOP derived from input_fps, capped at 300
    
    ${BOLD}${RED}presets are sourced as shell code; only use trusted presets from trusted
    directories.${ALL_OFF}

  ${BOLD}${CYAN}%s${ALL_OFF}
    Use ${BOLD}${YELLOW}--config-file${ALL_OFF} ${BOLD}${GREEN}FILE${ALL_OFF} to load an alternative path.
    CLI flags always take precedence. Requires ${BOLD}tomlq${ALL_OFF} when the file is present.

${BOLD}${BLUE}Examples:${ALL_OFF}
  %s video.mp4
  %s -s -f list.txt
  %s -n -N 10 my_movie.mkv\n" \
    "$SCRIPTNAME" "$VERSION" "$DESCRIPTION" \
    "$SCRIPTNAME" \
    "$PRESET_NAME" "$NICE_VALUE" "$SAVING_FILE" \
    "$PRESET_DIR" "$CONFIG_FILE" \
    "$SCRIPTNAME" "$SCRIPTNAME" "$SCRIPTNAME"
}

print_version() {
  printf "${RED}${BOLD}Scriptname:${ALL_OFF} %s
${GREEN}${BOLD}Version:${ALL_OFF} %s
${YELLOW}${BOLD}Description:${ALL_OFF} %s
${BLUE}${BOLD}Author:${ALL_OFF} %s
${MAGENTA}${BOLD}Date of creation:${ALL_OFF} %s
${CYAN}${BOLD}Date of revision:${ALL_OFF} %s
${RED}${BOLD}License:${ALL_OFF} %s

Copyright (c) 2025 Dennis Fink <me+coding@dennisfink.me>.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" \
    "$SCRIPTNAME" "$VERSION" "$DESCRIPTION" "$AUTHOR" "$DATE_OF_CREATION" \
    "$DATE_OF_REVISION" "$LICENSE"
}

filesize() {
  stat -c "%s" -- "$1" 2>/dev/null || stat -f "%z" -- "$1"
}

###############################################################################
# TERMINAL COLOR SETUP
#
# Colors and style escape sequences are configured dynamically through the
# `setup_colors` function, which enables or disables color output based on
# the value of ENABLE_COLOR. When enabled, terminal capabilities are detected
# via `tput`, falling back to ANSI escapes if unavailable.
#
# This script respects the NO_COLOR standard (https://no-color.org/).
# If the environment variable NO_COLOR is set (to any value), all color output
# is disabled. If FORCE_COLOR is set, colors are always enabled.
###############################################################################

# NOTE: This block calls debug() and reads $DEBUG. Both must be defined before
# this point. Do not move this block above the GLOBAL VARIABLES or FUNCTIONS
# sections without adjusting those dependencies.
if [[ -n "${NO_COLOR:-}" ]]; then
  debug "Colors are disabled via NO_COLOR"
  ENABLE_COLOR=0
elif [[ -n "${FORCE_COLOR:-}" ]]; then
  debug "Colors are forced via FORCE_COLOR"
  ENABLE_COLOR=1
elif [[ -t 1 ]]; then
  debug "Colors are enabled via interactive terminal"
  ENABLE_COLOR=1
else
  debug "Colors are disabled"
  ENABLE_COLOR=0
fi

setup_colors() {
  if [[ "$ENABLE_COLOR" -eq 1 ]]; then
    if tput setaf 0 >/dev/null 2>&1; then
      debug "Setting colors via tput"
      ALL_OFF="$(tput sgr0)"
      BOLD="$(tput bold)"
      RED="$(tput setaf 1)"
      GREEN="$(tput setaf 2)"
      YELLOW="$(tput setaf 3)"
      BLUE="$(tput setaf 4)"
      MAGENTA="$(tput setaf 5)"
      CYAN="$(tput setaf 6)"
    else
      # Hardcoded ANSI fallback: colors only (no bold embedded), matching the
      # tput path where BOLD and color variables are kept separate.
      debug "Using hardcoded color ANSI escape sequences"
      ALL_OFF="\e[0m"
      BOLD="\e[1m"
      RED="\e[31m"
      GREEN="\e[32m"
      YELLOW="\e[33m"
      BLUE="\e[34m"
      MAGENTA="\e[35m"
      CYAN="\e[36m"
    fi
  else
    ALL_OFF=""
    BOLD=""
    RED=""
    GREEN=""
    YELLOW=""
    BLUE=""
    MAGENTA=""
    CYAN=""
  fi
}
setup_colors

###############################################################################
# MAIN EXECUTION
###############################################################################

###############################################################################
# CONFIGURATION FILE
#
# Load defaults from config.toml if it exists. Values are only applied when
# the corresponding CLI flag has NOT already been set (CLI takes precedence).
# Requires tomlq when config.toml is present.
###############################################################################

# Query a single scalar value from config.toml via tomlq.
# Usage: _tomlq_get <key>   (e.g. ".encoding.preset")
# Outputs the raw string on stdout; returns non-zero if the key is absent
# or tomlq fails for any reason.
_tomlq_get() {
  tomlq -r "$1" "$CONFIG_FILE" 2>/dev/null
}

# Load configuration from config.toml, respecting CLI precedence.
# Called once, after option parsing, so all _CLI_* sentinels are already set.
load_config() {
  # Warn about the legacy skip.conf here (not at startup) so --quiet is
  # respected; by this point the CLI has been fully parsed.
  if [[ -f "$SKIP_CODECS_FILE" ]]; then
    warn "skip.conf is deprecated." "Migrate codecs to [skip] codecs in config.toml and remove $SKIP_CODECS_FILE"
  fi

  # We use -r and not -f to allow things like /dev/null
  [[ -r "$CONFIG_FILE" ]] || {
    if [[ $_CLI_CONFIG_FILE -eq 1 ]]; then
      error "Config file not found:" "$CONFIG_FILE"
      exit $EXIT_CONFIG_ERROR
    fi
    return 0
  }

  command -v tomlq >/dev/null 2>&1 || {
    error "tomlq not found but $CONFIG_FILE exists. Install tomlq or remove the config file."
    exit $EXIT_MISSING_DEPENDENCY
  }

  # Validate that the config file is well-formed TOML before reading any keys.
  # tomlq exits non-zero and prints to stderr if the file cannot be parsed.
  if ! tomlq '.' "$CONFIG_FILE" >/dev/null 2>&1; then
    error "Config file is not valid TOML:" "$CONFIG_FILE"
    exit $EXIT_CONFIG_ERROR
  fi

  debug "Loading config file:" "$CONFIG_FILE"

  local val

  # [encoding] preset
  if [[ $_CLI_PRESET -eq 0 ]]; then
    val=$(_tomlq_get '.encoding.preset // empty') && [[ -n "$val" ]] && {
      debug "Config: preset =" "$val"
      PRESET_NAME="$val"
    }
  fi

  # [encoding] nice
  if [[ $_CLI_NICE -eq 0 ]]; then
    val=$(_tomlq_get '.encoding.nice // empty') && [[ -n "$val" ]] && {
      debug "Config: nice =" "$val"
      NICE_VALUE="$val"
    }
  fi

  # [encoding] only_if_smaller
  if [[ $_CLI_ONLY_IF_SMALLER -eq 0 ]]; then
    val=$(_tomlq_get '.encoding.only_if_smaller // empty') && [[ -n "$val" ]] && {
      debug "Config: encoding.only_if_smaller =" "$val"
      [[ "$val" == "true" ]] && ONLY_IF_SMALLER=1 || ONLY_IF_SMALLER=0
    }
  fi

  # [encoding] continue
  if [[ $_CLI_CONTINUE -eq 0 ]]; then
    val=$(_tomlq_get '.encoding.continue // empty') && [[ -n "$val" ]] && {
      debug "Config: encoding.continue =" "$val"
      [[ "$val" == "true" ]] && CONTINUE_ON_FAIL=1 || CONTINUE_ON_FAIL=0
    }
  fi

  # [encoding] verify_output
  if [[ $_CLI_VERIFY_OUTPUT -eq 0 ]]; then
    val=$(_tomlq_get '.encoding.verify_output // empty') && [[ -n "$val" ]] && {
      debug "Config: encoding.verify_output =" "$val"
      [[ "$val" == "true" ]] && VERIFY_OUTPUT=1 || VERIFY_OUTPUT=0
    }
  fi

  # [encoding] hwaccel
  if [[ $_CLI_HWACCEL -eq 0 ]]; then
    val=$(_tomlq_get '.encoding.hwaccel // empty') && [[ -n "$val" ]] && {
      debug "Config: encoding.hwaccel =" "$val"
      if [[ "$val" == "false" ]]; then
        HWACCEL=0
      else
        HWACCEL=1
        # A bare `hwaccel = true` keeps "auto"; any other string is the METHOD.
        if [[ "$val" != "true" ]]; then
          HWACCEL_VALUE="$val"
        fi
      fi
    }
  fi

  # [skip] codecs  (TOML array → one element per line via tomlq -r '.skip.codecs[]')
  # CLI --skip-codec entries are additive, so we always load config codecs
  # regardless of _CLI_SKIP_CODEC. Both sources merge into SKIP_CODECS.
  local codec
  while IFS= read -r codec; do
    [[ -n "$codec" ]] && add_skip_codec_token "$codec"
  done < <(tomlq -r '.skip.codecs[]?' "$CONFIG_FILE" 2>/dev/null)

  # [saving] enabled
  if [[ $_CLI_SAVING -eq 0 ]]; then
    val=$(_tomlq_get '.saving.enabled // empty') && [[ -n "$val" ]] && {
      debug "Config: saving.enabled =" "$val"
      [[ "$val" == "true" ]] && SAVING=1 || SAVING=0
    }
  fi

  # [saving] file
  if [[ $_CLI_SAVING_FILE -eq 0 ]]; then
    val=$(_tomlq_get '.saving.file // empty') && [[ -n "$val" ]] && {
      debug "Config: saving.file =" "$val"
      SAVING_FILE="$val"
    }
  fi

  # [output] verbose
  if [[ $_CLI_VERBOSE -eq 0 ]]; then
    val=$(_tomlq_get '.output.verbose // empty') && [[ -n "$val" ]] && {
      debug "Config: output.verbose =" "$val"
      [[ "$val" == "true" ]] && VERBOSE=1 || VERBOSE=0
    }
  fi

  # [output] quiet
  if [[ $_CLI_QUIET -eq 0 ]]; then
    val=$(_tomlq_get '.output.quiet // empty') && [[ -n "$val" ]] && {
      debug "Config: output.quiet =" "$val"
      [[ "$val" == "true" ]] && QUIET=1 || QUIET=0
    }
  fi
}

# Add a codec name to the SKIP_CODECS associative array.
# - Normalizes to lowercase
# - Ignores empty tokens
# - Used both for CLI --skip-codec and for skip.conf lines
add_skip_codec_token() {
  local token="${1,,}" # lowercase
  if [[ ! -v SKIP_CODECS["$token"] ]]; then
    debug "Add to skip codec:" "$token"
    SKIP_CODECS["$token"]=
  else
    debug "Codec already skipped:" "$token"
  fi
}

# Parse a user-provided codec list (comma/space/colon separated)
# and add each token to SKIP_CODECS
parse_skip_codec_parameter() {
  local arg="$1"
  local IFS=',: ' token
  for token in $arg; do
    [[ -z "$token" ]] && continue
    add_skip_codec_token "$token"
  done
}

# Load ffmpeg argument preset by name.
#
# Security:
#   Presets are sourced as shell code. Names are validated against a strict
#   allowlist (alphanumerics, hyphens, underscores only) to prevent path
#   traversal and shell metacharacter injection. Note: a valid preset name
#   could still be a symlink to an arbitrary file; ensure the preset directory
#   itself is not writable by untrusted users.
#
# Contract:
#   The sourced preset MUST set the bash array `ffargs`.
#   Presets may reference variables from the caller (encode_one) such as:
#     output_pixel_format, input_pixel_format, input_codec, input_frame_rate,
#     input_fps, output_gop_size
load_preset() {
  local preset="$1"
  # Strict allowlist: only alphanumerics, hyphens, and underscores are permitted.
  # This prevents path traversal, shell metacharacter injection, and symlink-based
  # attacks more reliably than a blocklist approach.
  if [[ -z "$preset" || ! "$preset" =~ ^[a-zA-Z0-9_-]+$ ]]; then
    error "Invalid preset name (only alphanumerics, hyphens, underscores allowed):" "$preset"
    exit $EXIT_USAGE_ERROR
  fi

  local file="$PRESET_DIR/$preset.sh"
  [[ -f "$file" ]] || {
    error "Preset not found:" "$file"
    exit $EXIT_CONFIG_ERROR
  }

  # Reject preset files that are world-writable to prevent arbitrary users
  # from injecting shell code.
  #
  # Symlinks must be resolved first: stat on a symlink returns the permissions
  # of the symlink itself (always 777 on Linux), not the target. We use
  # readlink -f (GNU) with a fallback to realpath for macOS/BSD.
  local resolved_file
  resolved_file=$(readlink -f -- "$file" 2>/dev/null || realpath -- "$file")

  local preset_perms
  preset_perms=$(stat -c '%a' -- "$resolved_file" 2>/dev/null || stat -f '%OLp' -- "$resolved_file")

  if [[ "${preset_perms: -1}" =~ [2367] ]]; then
    error "Preset file is world-writable, refusing to source:" "$resolved_file"
    exit $EXIT_CONFIG_ERROR
  fi

  unset -v ffargs
  ffargs=()

  debug "Sourcing preset file:" "$file"

  # shellcheck source=/dev/null
  source "$file"

  ((${#ffargs[@]})) || {
    error "Preset '$preset' did not set ffargs"
    exit $EXIT_RUNTIME_FAILURE
  }

  debug "Preset ffargs:" "$(printf "%q " "${ffargs[@]}")"
}

if [[ $# -eq 0 ]]; then
  debug "No parameters were specified"
  printf "${BOLD}${BLUE}Usage:${ALL_OFF} ${BOLD}${MAGENTA}%s${ALL_OFF} ${BOLD}${YELLOW}[OPTION] [--]${ALL_OFF} ${BOLD}${GREEN}FILE...${ALL_OFF}
Run ${BOLD}${MAGENTA}%s${ALL_OFF} ${BOLD}${YELLOW}--help${ALL_OFF} for full usage information.\n" "$SCRIPTNAME" "$SCRIPTNAME" >&2
  exit $EXIT_USAGE_ERROR
fi

while [[ $# -gt 0 ]]; do
  case "$1" in
  -h | --help | -\?)
    print_help
    exit $EXIT_OK
    ;;
  --version)
    print_version
    exit $EXIT_OK
    ;;
  -q | --quiet)
    QUIET=1
    _CLI_QUIET=1
    shift
    ;;
  -v | --verbose)
    VERBOSE=1
    _CLI_VERBOSE=1
    shift
    ;;
  --color)
    ENABLE_COLOR=1
    setup_colors
    shift
    ;;
  --no-color)
    ENABLE_COLOR=0
    setup_colors
    shift
    ;;
  -c | --continue)
    CONTINUE_ON_FAIL=1
    _CLI_CONTINUE=1
    shift
    ;;
  --no-continue)
    CONTINUE_ON_FAIL=0
    _CLI_CONTINUE=1
    shift
    ;;
  --verify-output)
    VERIFY_OUTPUT=1
    _CLI_VERIFY_OUTPUT=1
    shift
    ;;
  --no-verify-output)
    VERIFY_OUTPUT=0
    _CLI_VERIFY_OUTPUT=1
    shift
    ;;
  --config-file)
    [[ $# -ge 2 ]] || {
      error "Missing value for $1"
      exit $EXIT_USAGE_ERROR
    }
    [[ -n "$2" ]] || {
      error "Value for $1 must not be empty"
      exit $EXIT_USAGE_ERROR
    }
    CONFIG_FILE="$2"
    _CLI_CONFIG_FILE=1
    shift 2
    ;;
  --config-file=*)
    [[ -n "${1#*=}" ]] || {
      error "Value for --config-file must not be empty"
      exit $EXIT_USAGE_ERROR
    }
    CONFIG_FILE="${1#*=}"
    _CLI_CONFIG_FILE=1
    shift
    ;;
  --no-config)
    CONFIG_FILE="/dev/null"
    _CLI_CONFIG_FILE=1
    shift
    ;;
  -f | --encode-file)
    [[ $# -ge 2 ]] || {
      error "Missing value for $1"
      exit $EXIT_USAGE_ERROR
    }
    [[ -n "$2" ]] || {
      error "Value for $1 must not be empty"
      exit $EXIT_USAGE_ERROR
    }
    ENCODE_FILE="$2"
    shift 2
    ;;
  --encode-file=*)
    [[ -n "${1#*=}" ]] || {
      error "Value for --encode-file must not be empty"
      exit $EXIT_USAGE_ERROR
    }
    ENCODE_FILE="${1#*=}"
    shift
    ;;
  -n | --dry-run)
    DRY_RUN=1
    shift
    ;;
  -N | --nice)
    [[ $# -ge 2 ]] || {
      error "Missing value for $1"
      exit $EXIT_USAGE_ERROR
    }
    NICE_VALUE="$2"
    _CLI_NICE=1
    shift 2
    ;;
  --nice=*)
    NICE_VALUE="${1#*=}"
    _CLI_NICE=1
    shift
    ;;
  -s | --saving)
    SAVING=1
    _CLI_SAVING=1
    shift
    ;;
  --no-saving)
    SAVING=0
    _CLI_SAVING=1
    shift
    ;;
  --saving-file)
    [[ $# -ge 2 ]] || {
      error "Missing value for $1"
      exit $EXIT_USAGE_ERROR
    }
    [[ -n "$2" ]] || {
      error "Value for $1 must not be empty"
      exit $EXIT_USAGE_ERROR
    }
    SAVING_FILE="$2"
    SAVING_FILE_EXPLICIT=1
    _CLI_SAVING_FILE=1
    shift 2
    ;;
  --saving-file=*)
    [[ -n "${1#*=}" ]] || {
      error "Value for --saving-file must not be empty"
      exit $EXIT_USAGE_ERROR
    }
    SAVING_FILE="${1#*=}"
    SAVING_FILE_EXPLICIT=1
    _CLI_SAVING_FILE=1
    shift
    ;;
  -S | --skip-codec)
    [[ $# -ge 2 ]] || {
      error "Missing value for $1"
      exit $EXIT_USAGE_ERROR
    }
    parse_skip_codec_parameter "$2"
    shift 2
    ;;
  --skip-codec=*)
    parse_skip_codec_parameter "${1#*=}"
    shift
    ;;
  -l | --only-if-smaller)
    ONLY_IF_SMALLER=1
    _CLI_ONLY_IF_SMALLER=1
    shift
    ;;
  --no-only-if-smaller)
    ONLY_IF_SMALLER=0
    _CLI_ONLY_IF_SMALLER=1
    shift
    ;;
  --hwaccel)
    HWACCEL=1
    # Peek at the next argument: use it as the METHOD only if it is
    # non-empty and does not look like an option flag.
    if [[ $# -ge 2 && -n "$2" && "$2" != -* ]]; then
      HWACCEL_VALUE="$2"
      shift 2
    else
      HWACCEL_VALUE="auto"
      shift
    fi
    _CLI_HWACCEL=1
    ;;
  --hwaccel=*)
    HWACCEL=1
    HWACCEL_VALUE="${1#*=}"
    [[ -n "$HWACCEL_VALUE" ]] || {
      error "Value for --hwaccel must not be empty"
      exit $EXIT_USAGE_ERROR
    }
    _CLI_HWACCEL=1
    shift
    ;;
  --no-hwaccel)
    HWACCEL=0
    _CLI_HWACCEL=1
    shift
    ;;
  -p | --preset)
    [[ $# -ge 2 ]] || {
      error "Missing value for $1"
      exit $EXIT_USAGE_ERROR
    }
    [[ -n "$2" ]] || {
      error "Value for $1 must not be empty"
      exit $EXIT_USAGE_ERROR
    }
    PRESET_NAME="$2"
    _CLI_PRESET=1
    shift 2
    ;;
  --preset=*)
    [[ -n "${1#*=}" ]] || {
      error "Value for --preset must not be empty"
      exit $EXIT_USAGE_ERROR
    }
    PRESET_NAME="${1#*=}"
    _CLI_PRESET=1
    shift
    ;;
  --)
    shift
    REMAINING_ARGS+=("$@")
    break
    ;;
  -*)
    error "Unknown option: $1"
    exit $EXIT_USAGE_ERROR
    ;;
  *)
    REMAINING_ARGS+=("$1")
    shift
    ;;
  esac
done

# Apply config file defaults. Must run after CLI parsing so _CLI_* sentinels
# are set, but before validation so config-supplied values are validated too.
load_config

printf -v joined ' %s' "${!SKIP_CODECS[@]}"

debug "Effective configuration:"
debug "  config-file:" "$CONFIG_FILE"
debug "  dry-run:" "$DRY_RUN"
debug "  encode-file:" "$ENCODE_FILE"
debug "  hwaccel:" "$HWACCEL"
debug "  hwaccel_value:" "$HWACCEL_VALUE"
debug "  nice:" "$NICE_VALUE"
debug "  only-if-smaller:" "$ONLY_IF_SMALLER"
debug "  preset:" "$PRESET_NAME"
debug "  quiet:" "$QUIET"
debug "  saving-file:" "$SAVING_FILE"
debug "  saving:" "$SAVING"
debug "  skip-codecs:" "${joined# }"
debug "  verbose:" "$VERBOSE"
debug "  verify-output:" "$VERIFY_OUTPUT"

command -v ffmpeg >/dev/null 2>&1 || {
  error "ffmpeg not found."
  exit $EXIT_MISSING_DEPENDENCY
}
command -v ffprobe >/dev/null 2>&1 || {
  error "ffprobe not found."
  exit $EXIT_MISSING_DEPENDENCY
}
command -v nice >/dev/null 2>&1 || {
  error "nice not found."
  exit $EXIT_MISSING_DEPENDENCY
}

if [[ $SAVING -eq 1 ]]; then
  # bc is only required when --saving is active; intentionally checked here
  # rather than in the main dependency block to avoid requiring it universally.
  command -v bc >/dev/null 2>&1 || {
    error "bc not found."
    exit $EXIT_MISSING_DEPENDENCY
  }
fi

if [[ $SAVING_FILE_EXPLICIT -eq 1 && $SAVING -eq 0 ]]; then
  warn "--saving-file has no effect without --saving"
fi

if [[ ! "$NICE_VALUE" =~ ^-?[0-9]+$ ]] || ((NICE_VALUE < -20 || NICE_VALUE > 19)); then
  error "Invalid nice value (must be an integer between -20 and 19):" "$NICE_VALUE"
  exit $EXIT_USAGE_ERROR
fi

if [[ ! -z "${joined# }" ]]; then
  verbose "Skipping files with codecs:" "${joined# }"
fi
unset joined

# Remove temporary output files created during encoding.
# Registered via trap EXIT so it runs on normal exit and on failures
# shellcheck disable=SC2329
cleanup() {
  # "${TMP_FILES[@]+"${TMP_FILES[@]}"}" expands to nothing when the array is
  # empty (safe under nounset), unlike [@]:-} which yields one empty iteration.
  for t in "${TMP_FILES[@]+"${TMP_FILES[@]}"}"; do
    debug "Cleanup temp file:" "$t"
    [[ -f "$t" ]] && rm -f -- "$t" || true
  done
}
trap cleanup EXIT

# Encode a single media file according to PRESET_NAME.
#
# Arguments:
#   $1 - path to the file to encode
#   $2 - current index (1-based, for progress display)
#   $3 - total file count (for progress display)
#
# Steps:
#   1) Probe input codec and pixel format (v:0) in a single ffprobe call.
#   2) Optionally skip based on codec.
#   3) Normalize pixel formats (handle yuvj* forms).
#   4) Select an output pixel format that preserves chroma subsampling/bit depth.
#   5) Load preset ffargs.
#   6) Run ffmpeg into a temp file in the same directory.
#   7) Optionally keep only-if-smaller; optionally log savings; then replace.
#
# Return:
#   EXIT_OK on success or if skipped; EXIT_RUNTIME_FAILURE on failure.
encode_one() {
  local file="$1"
  local idx="$2"
  local total="$3"

  [[ -z "$file" ]] && return $EXIT_OK

  msg "Processing [$idx/$total]:" "$file"
  [[ ! -f "$file" ]] && {
    error "Not found:" "$file"
    return $EXIT_RUNTIME_FAILURE
  }
  [[ ! -r "$file" ]] && {
    error "File is not readable:" "$file"
    return $EXIT_RUNTIME_FAILURE
  }

  # Probe codec and pixel format in a single ffprobe invocation to halve
  # the startup overhead on large batches.
  local probe_out
  probe_out=$(ffprobe -v error -select_streams v:0 \
    -show_entries stream=codec_name,pix_fmt,r_frame_rate \
    -of default=nk=1:nw=1 "file:$file" 2>/dev/null)

  local input_codec input_pixel_format input_frame_rate input_fps

  input_codec=$(printf '%s\n' "$probe_out" | sed -n '1p')
  debug "Input codec:" "$input_codec"

  input_pixel_format=$(printf '%s\n' "$probe_out" | sed -n '2p')
  input_frame_rate=$(printf "%s\n" "$probe_out" | sed -n '3p')

  if [[ -z "$input_codec" ]]; then
    error "Could not determine input video codec:" "$file"
    return $EXIT_RUNTIME_FAILURE
  fi
  if [[ -z "$input_pixel_format" ]]; then
    error "Could not determine input pixel format:" "$file"
    return $EXIT_RUNTIME_FAILURE
  fi
  if [[ -z "$input_frame_rate" ]]; then
    error "Could not determine input frame rate:" "$file"
    return $EXIT_RUNTIME_FAILURE
  fi

  if [[ -v SKIP_CODECS["$input_codec"] ]]; then
    msg "Skipping (codec excluded):" "$input_codec"
    return $EXIT_OK
  fi

  # Some files report "yuvj*" formats (full-range JPEG-style). For encoding
  # purposes we normalize to the equivalent "yuv*" formats.
  input_pixel_format="${input_pixel_format/yuvj/yuv}"
  debug "Normalized input pixel format:" "$input_pixel_format"

  # Preserve chroma subsampling (420/422/444) and bit depth (8/10/12/16-bit)
  # to avoid unintended quality loss or incompatible output.
  # Known limitation: exotic formats not matching these patterns (e.g. gbrp,
  # yuva*, gray*) fall through to yuv420p. Extend the logic below if needed.
  local subsampling depth output_pixel_format

  case "$input_pixel_format" in
  *444*) subsampling="444" ;;
  *422*) subsampling="422" ;;
  *)
    subsampling="420"
    [[ "$input_pixel_format" != *420* ]] &&
      verbose "Unrecognised chroma subsampling in '$input_pixel_format', falling back to yuv420p"
    ;;
  esac

  case "$input_pixel_format" in
  *16*) depth="p16le" ;;
  *12*) depth="p12le" ;;
  *10*) depth="p10le" ;;
  *) depth="p" ;;
  esac

  output_pixel_format="yuv${subsampling}${depth}"
  debug "Selected output pixel format:" "$output_pixel_format"

  # Convert ffprobe frame rate fractions like 30000/1001 to rounded integer FPS
  # values for simpler encoder heuristics and logging.
  input_fps=$(
    awk -F/ '
      {
        if ($2)
          printf "%.0f\n", $1 / $2
        else
          printf "%.0f\n", $1
      }
    ' <<<"$input_frame_rate"
  )
  debug "Calculated input fps:" "$input_fps"

  # Use a larger GOP for better compression efficiency while keeping seek
  # performance reasonable. A common rule-of-thumb is roughly five seconds of
  # video per GOP, capped at 300 frames.
  local output_gop_size
  output_gop_size=$(((10 * input_fps) / 2))
  if [[ "$output_gop_size" -ge 300 ]]; then
    debug "Calculated GOP size exceeds 300 frames, capping to 300"
    output_gop_size=300
  fi
  debug "Calculated output GOP size:" "$output_gop_size"

  load_preset "$PRESET_NAME"

  local extension directory tmp base stem
  # filename (path without extension) is used only for the savings log.
  # Note: only the last extension is stripped, so multi-dot names like
  # "my.show.s01e01.mkv" are logged as "my.show.s01e01".
  local filename

  base="${file##*/}"
  if [[ "$base" == *.* ]]; then
    extension="${base##*.}"
    stem="${base%.*}"
    filename="${file%.*}"
  else
    extension=""
    stem="$base"
    filename="$file"
  fi

  directory=$(dirname -- "$file")

  # Temp file is created in the same directory as the input so that `mv` is
  # atomic on the same filesystem (avoid cross-device rename issues).
  # mktemp provides cryptographically random names and atomic creation,
  # unlike $$.$RANDOM which has limited entropy and is predictable.
  tmp=$(mktemp -- "$directory/.${stem}_${PRESET_NAME}.XXXXXX${extension:+.$extension}")
  TMP_FILES+=("$tmp")
  debug "Temporary output path:" "$tmp"

  # Build ffmpeg command:
  # - Map all streams, metadata, and chapters
  # - Default to stream copy for everything
  # - Prepend -hwaccel before -i when hardware acceleration is requested
  # - Let the preset override specific streams (usually video) via ffargs

  local hwaccel_args=()
  if [[ $HWACCEL -eq 1 ]]; then
    hwaccel_args=(-hwaccel "$HWACCEL_VALUE")
  fi

  local cmd=(ffmpeg
    -nostdin
    -y
    -hide_banner
    -v error
    -stats
    "${hwaccel_args[@]}"
    -i "file:$file"
    -map 0
    -map_metadata 0
    -map_chapters 0
    -c copy
    "${ffargs[@]}"
    "file:$tmp")

  if [[ $DRY_RUN -eq 1 ]]; then
    msg "DRY RUN:" "Would encode with preset $PRESET_NAME"
    verbose "Input codec:" "$input_codec"
    verbose "Input pixel format:" "$input_pixel_format"
    verbose "Output pixel format:" "$output_pixel_format"
    verbose "Input frame rate:" "$input_frame_rate"
    verbose "Input FPS:" "$input_fps"
    verbose "Output GOP size:" "$output_gop_size"
    verbose "Command:" "${cmd[*]}"
    return $EXIT_OK
  fi

  msg "Encoding:" "$file"
  debug "Nice value:" "$NICE_VALUE"

  if nice -n "$NICE_VALUE" "${cmd[@]}"; then

    # Integrity verification: confirm the encoded output is a valid, playable
    # file before discarding the original. ffprobe exits non-zero and emits
    # nothing useful if the container is corrupt or contains no readable
    # streams, so we treat any non-zero exit as a fatal encode failure.
    # Skip with --no-verify-output when trust in the encoder is high and the
    # extra probe round-trip is undesirable.
    if [[ $VERIFY_OUTPUT -eq 1 ]]; then
      debug "Verifying output integrity:" "$tmp"
      if ! ffprobe -v error "file:$tmp" >/dev/null 2>&1; then
        error "Output failed integrity check:" "$tmp"
        rm -f -- "$tmp"
        if [[ $CONTINUE_ON_FAIL -eq 1 ]]; then
          return $EXIT_RUNTIME_FAILURE
        else
          exit $EXIT_RUNTIME_FAILURE
        fi
      fi
      verbose "Integrity check passed:" "$tmp"
    fi

    local original_filesize new_filesize
    original_filesize=$(filesize "$file")
    new_filesize=$(filesize "$tmp")

    # If requested, keep the original if the new file is larger.
    if [[ $ONLY_IF_SMALLER -eq 1 && $new_filesize -gt $original_filesize ]]; then
      msg "Did not replace (new file is larger):" "$file"
      rm -f -- "$tmp"
      return $EXIT_OK
    fi

    if [[ $SAVING -eq 1 ]]; then
      local pct
      if [[ $original_filesize -gt 0 ]]; then
        pct=$(bc <<<"($original_filesize - $new_filesize) * 100 / $original_filesize")
      else
        pct=0
      fi
      # Write a header line if the savings file does not yet exist.
      if [[ ! -f "$SAVING_FILE" ]]; then
        printf "filename\toriginal_bytes\tnew_bytes\tsaved_pct\n" >"$SAVING_FILE"
      fi
      printf "%s\t%s\t%s\t%s%%\n" "$filename" "$original_filesize" "$new_filesize" "$pct" >>"$SAVING_FILE"
    fi

    mv -f -- "$tmp" "$file"
    msg "Replaced:" "$file"
  else
    error "Encode FAILED:" "$file"
    if [[ $CONTINUE_ON_FAIL -eq 1 ]]; then
      return $EXIT_RUNTIME_FAILURE # fail this but keep going
    else
      exit $EXIT_RUNTIME_FAILURE
    fi
  fi
}

STATUS=$EXIT_OK
if [[ -n $ENCODE_FILE ]]; then
  [[ -f "$ENCODE_FILE" ]] || {
    error "Encode file not found:" "$ENCODE_FILE"
    exit $EXIT_USAGE_ERROR
  }
  # Build the file list into an array first so we know the total count.
  mapfile -t FILES_TO_ENCODE < <(
    while IFS= read -r file || [[ -n "$file" ]]; do
      [[ -n "$file" ]] && printf '%s\n' "$file"
    done <"$ENCODE_FILE"
  )
  total=${#FILES_TO_ENCODE[@]}
  for ((i = 0; i < total; i++)); do
    encode_one "${FILES_TO_ENCODE[i]}" "$((i + 1))" "$total" || STATUS=$EXIT_RUNTIME_FAILURE
  done
else
  total=${#REMAINING_ARGS[@]}
  for ((i = 0; i < total; i++)); do
    encode_one "${REMAINING_ARGS[i]}" "$((i + 1))" "$total" || STATUS=$EXIT_RUNTIME_FAILURE
  done
fi

exit $STATUS