summaryrefslogtreecommitdiff
path: root/transcode.sh
blob: 527c15c224b79e9c93b27e71395e2430c6dae7e4 (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
#!/usr/bin/env bash

# SPDX-FileCopyrightText: 2025 Dennis Fink <dennis.fink@c3l.lu>
#
# 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
#
#     Note: Presets are sourced as shell code. Only use trusted presets.
#
#     A per-user list of video-codecs to skip can be provided in:
#         ${XDG_CONFIG_HOME:-$HOME/.config}/transcode.sh/skip.conf
#
# NOTES
#     This script respects the NO_COLOR standard (https://no-color.org/).
#
# AUTHOR
#     Dennis Fink <dennis.fink@c3l.lu>
###############################################################################

# 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

# Set a predictable and secure PATH (ignores user-controlled paths).
# Trade-off: tools installed outside these directories (e.g. ffmpeg via
# Homebrew on macOS at /opt/homebrew/bin, or via Nix at /nix/store/...)
# will not be found. In that case, invoke this script via a wrapper that
# prepends the correct path, e.g.: PATH="/opt/homebrew/bin:$PATH" ./transcode.sh
PATH='/bin:/usr/bin:/usr/local/bin'
export PATH

# 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-02-25
readonly VERSION=1.0.0
readonly AUTHOR="Dennis Fink <dennis.fink@c3l.lu>"
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=""
NICE_VALUE=19
ONLY_IF_SMALLER=0
PRESET_NAME="default"
SAVING=0
SAVING_FILE="transcode_savings"
SAVING_FILE_EXPLICIT=0
declare -A SKIP_CODECS

REMAINING_ARGS=()

TMP_FILES=()

readonly PRESET_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/transcode.sh/presets"
readonly SKIP_CODECS_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/transcode.sh/skip.conf"

###############################################################################
# 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 "%s - %s - %s

Usage: %s [OPTION] [--] FILE...

Options:
  -c, --continue          Continue with next file even if ffmpeg fails
  -f, --encodefile PATH   File containing list of files to encode
  --encodefile=PATH
  -n, --dry-run           Show what would be done, don't run ffmpeg
  -N, --nice VALUE        Nice value for ffmpeg (default: 19)
  --nice=VALUE
  -s, --saving            Log filesize savings (filename, orig, new, %%)
  --saving-file PATH      Specify where to save filesize savings (default: transcode_savings)
  --saving-file=PATH
  -S, --skip-codec LIST   Add codecs to skip (comma/space/colon separated)
  --skip-codec=LIST
  -l, --only-if-smaller   Only overwrite files if the transcoded file is smaller
  -p, --preset NAME       Load ffmpeg arguments from a preset (default: default)
  --preset=NAME
  -h, --help, -?          Show this help text and exit
  -q, --quiet             Do not output anything, takes precedence over -v and --verbose
  -v, --verbose           Be more verbose
  --version               Print script information and version
  --color                 Force colored output
  --no-color              Disable colored output

Examples:
  %s video.mp4
  %s -s -f list.txt
  %s -n -N 10 my_movie.mkv\n" "$SCRIPTNAME" "$VERSION" "$DESCRIPTION" "$SCRIPTNAME" "$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\n" "$SCRIPTNAME" "$VERSION" "$DESCRIPTION" "$AUTHOR" "$DATE_OF_CREATION" "$DATE_OF_REVISION" "$LICENSE"

  if [[ -f "LICENSES/${LICENSE}.txt" ]]; then
    printf "\n"
    cat "LICENSES/${LICENSE}.txt"
  fi
}

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
###############################################################################

# 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
}

if [[ -f "$SKIP_CODECS_FILE" ]]; then
  while read -r line || [[ -n "$line" ]]; do
    [[ -z "$line" || "${line:0:1}" == "#" ]] && continue
    parse_skip_codec_parameter "$line"
  done <"$SKIP_CODECS_FILE"
fi

# Load ffmpeg argument preset by name.
#
# Arguments:
#   $1 - preset name
#   $2 - name of the caller's array variable to populate (nameref)
#
# 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
#   On return the caller's array (named by $2) is populated with the preset's
#   ffargs; the preset-local `ffargs` variable is unset before returning.
load_preset() {
  local preset="$1"
  local -n _load_preset_out="$2"

  # 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

  local 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[@]}")"

  _load_preset_out=("${ffargs[@]}")
}

if [[ $# -eq 0 ]]; then
  debug "No parameters were specified"
  printf "Usage: %s [OPTION] [--] FILE...\nRun '%s --help' 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
    shift
    ;;
  -v | --verbose)
    VERBOSE=1
    shift
    ;;
  --color)
    ENABLE_COLOR=1
    setup_colors
    shift
    ;;
  --no-color)
    ENABLE_COLOR=0
    setup_colors
    shift
    ;;
  -c | --continue)
    CONTINUE_ON_FAIL=1
    shift
    ;;
  -f | --encodefile)
    [[ $# -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
    ;;
  --encodefile=*)
    [[ -n "${1#*=}" ]] || {
      error "Value for --encodefile 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"
    shift 2
    ;;
  --nice=*)
    NICE_VALUE="${1#*=}"
    shift
    ;;
  -s | --saving)
    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
    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
    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
    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"
    shift 2
    ;;
  --preset=*)
    [[ -n "${1#*=}" ]] || {
      error "Value for --preset must not be empty"
      exit $EXIT_USAGE_ERROR
    }
    PRESET_NAME="${1#*=}"
    shift
    ;;
  --)
    shift
    break
    ;;
  -*)
    error "Unknown option: $1"
    exit $EXIT_USAGE_ERROR
    ;;
  *)
    REMAINING_ARGS+=("$1")
    shift
    ;;
  esac
done

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 [[ ${#SKIP_CODECS[@]} -gt 0 ]]; then
  printf -v joined ' %s' "${!SKIP_CODECS[@]}"
  verbose "Skipping files with codecs:" "${joined# }"
fi

# 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 \
    -of default=nk=1:nw=1 "file:$file" 2>/dev/null)

  local input_codec input_pixel_format
  input_codec=$(printf '%s\n' "$probe_out" | sed -n '1p')
  input_pixel_format=$(printf '%s\n' "$probe_out" | sed -n '2p')

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

  # Load preset early so a missing/invalid preset fails before we create a
  # temp file or do any further work.
  local ffargs=()
  load_preset "$PRESET_NAME" ffargs

  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
  # - Let the preset override specific streams (usually video) via ffargs
  local cmd=(ffmpeg
    -nostdin
    -y
    -hide_banner
    -v error
    -stats
    -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 "Command:" "${cmd[*]}"
    return $EXIT_OK
  fi

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

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

    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