Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
290 changes: 274 additions & 16 deletions bin/omarchy-transcode
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,22 @@
# omarchy:group=transcode
# omarchy:name=
# omarchy:summary=Transcode pictures and videos for sharing
# omarchy:args=[--path path] [input] [format] [resolution] [quality]
# omarchy:examples=omarchy transcode|omarchy transcode --path ~/Downloads|omarchy transcode ~/Videos/demo.mov mp4 1080p|omarchy transcode ~/Pictures/background.heic jpg medium|omarchy transcode ~/Videos/demo.mov mp4 1080p low
# omarchy:args=[--path path] [--target size] [input] [format] [resolution] [quality]
# omarchy:examples=omarchy transcode|omarchy transcode --path ~/Downloads|omarchy transcode ~/Videos/demo.mov mp4 1080p|omarchy transcode ~/Pictures/background.heic jpg medium|omarchy transcode ~/Videos/demo.mov mp4 1080p low|omarchy transcode ~/Videos/demo.mov mp4 1080p --target 25M

set -euo pipefail

usage() {
cat <<'EOF'
Usage:
omarchy transcode [--path path] [input] [format] [resolution] [quality]
omarchy transcode [--path path] [--target size] [input] [format] [resolution] [quality]

With no input, pick a picture or video from ~/Pictures and ~/Videos,
or only from --path when provided. Then pick the output format, resolution, and for videos the quality.

Options:
--path path Limit interactive fuzzy file selection to this path
--path path Limit interactive fuzzy file selection to this path
--target size Target output size (e.g. 25M, 1.5G); bare number means MB

Formats:
Pictures: jpg, png
Expand Down Expand Up @@ -230,7 +231,7 @@ estimate_label() {
awk -v dur="$1" -v kbps="$2" -v audio="$3" -v src="$4" 'BEGIN {
bytes = dur * (kbps + audio) * 125 # kbps * 1000 / 8 bytes per second
if (src != "" && bytes > src) { print "larger than source"; exit }
mb = bytes / 1048576 # MiB, the scale the completion notification reports
mb = bytes / 1000000 # decimal MB -- matches file managers and upload limits
if (mb < 1) { print "~1 MB"; exit }
d = int(log(mb) / log(10)) - 1 # round to 2 significant figures
if (d < -1) d = -1
Expand All @@ -240,13 +241,14 @@ estimate_label() {
}

# Builds the quality rows as "\t<tier>\t<subtext>" argv (the leading tab is the
# empty glyph field), pre-highlights medium, and prints the picked tier. The
# "label\tsubtext" return is stripped at the first tab and re-validated here so
# a foreign label dies inside the helper, before the notification boundary --
# never reaching output_path or ffmpeg.
# empty glyph field), pre-highlights medium, and prints the picked tier -- or
# "target:<bytes>" when the mp4-only Custom size… row is picked, which main()
# unwraps into the --target path. The "label\tsubtext" return is stripped at the
# first tab and re-validated here so a foreign label dies inside the helper,
# before the notification boundary -- never reaching output_path or ffmpeg.
select_quality() {
local input="$1" format="$2" resolution="$3"
local duration="" src_bytes="" audio_kbps=192 tier subtext selection
local duration="" src_bytes="" audio_kbps=192 tier subtext selection custom_label="Custom size…" custom_subtext="Enter a size like 25M" bytes
local rows=()

if [[ $format == "mp4" ]]; then
Expand All @@ -273,9 +275,20 @@ select_quality() {
rows+=($'\t'"$tier"$'\t'"$subtext")
done

# mp4 only: the sentinel row's label doubles as its key -- the menu returns
# "label\tsubtext", and the strip below hands the label back verbatim.
[[ $format == "mp4" ]] && rows+=($'\t'"$custom_label"$'\t'"$custom_subtext")

selection=$(omarchy-menu-select "Select quality" "${rows[@]}" -- --default-index 1) || return

selection="${selection%%$'\t'*}"

if [[ $format == "mp4" && $selection == "$custom_label" ]]; then
bytes=$(prompt_target_size) || return
printf 'target:%s' "$bytes"
return
fi

case "$selection" in
high | medium | low) ;;
*)
Expand All @@ -293,14 +306,204 @@ output_size_label() {
bytes=$(stat -c %s "$1" 2>/dev/null || true)
[[ $bytes =~ ^[0-9]+$ ]] || return 1
awk -v b="$bytes" 'BEGIN {
if (b > 0 && b < 1048576) { printf "<1 MB"; exit }
printf "%.0f MB", b / 1048576
if (b > 0 && b < 1000000) { printf "<1 MB"; exit }
printf "%.0f MB", b / 1000000
}'
}

# Parses a free-text --target size ("25M", "1.5G", "500K", "25MB", bare "25"
# meaning MB) into integer bytes on stdout, or prints an error on stderr and
# returns 1. A pure validator -- callers own the exit code (the flag arm
# propagates 2) and Phase 9's Custom size row re-prompts on failure. The raw
# string is discarded here: only the integer bytes and the numfmt --to=si
# token derived from them ever reach a filename or ffmpeg argv. Units are
# decimal (SI): 25M means 25,000,000 bytes, matching file managers and
# upload limits like Discord's.
parse_target_size() {
local raw="$1" normalized bytes

[[ $raw =~ ^[0-9]+(\.[0-9]+)?([kKmMgG][bB]?)?$ ]] ||
{ echo "Invalid target size: $raw" >&2; return 1; }

normalized="${raw%[bB]}" # drop an optional trailing B: 25MB -> 25M
normalized="${normalized^^}" # uppercase the unit letter: 25m -> 25M
[[ $normalized =~ [KMG]$ ]] || normalized+="M" # a bare number means MB

bytes=$(numfmt --from=si "$normalized") ||
{ echo "Invalid target size: $raw" >&2; return 1; }
(( bytes > 0 )) ||
{ echo "Invalid target size: $raw" >&2; return 1; }

printf '%s' "$bytes"
}

# Prompts for a free-text target size behind the Custom size… row. Re-prompts
# exactly once -- the second prompt carries an error hint so it reads as
# "invalid", not "didn't take" (D-02) -- then cancels. Esc cancels at either
# prompt like every sibling. Empty submits ride through parse_target_size with
# everything else: one validator for both entry points. Planner refusals are
# NOT this loop's business (D-01).
prompt_target_size() {
local prompt="Target size (e.g. 25M)" answer bytes attempt
for attempt in 1 2; do
answer=$(omarchy-menu-input "$prompt") || return 1
if bytes=$(parse_target_size "$answer"); then
printf '%s' "$bytes"
return 0
fi
prompt="Invalid size — e.g. 25M"
done
return 1
}

# Plans a --target run: refuses a target at or above the source size (a
# re-encode can only degrade it -- drop --target and pick a quality for format
# conversion), probes duration and audio, derives the video bitrate
# (target*8/duration/1000 with a ~2% container reserve, minus the audio
# stream), then walks the locked 2000/800/400 kbps floors stepping
# 4k -> 1080p -> 720p until the budget fits. Prints "<res> <video_kbps>" on
# stdout; every refusal prints to stderr and returns nonzero, and cheap
# refusals precede the probes. A negative or zero derived bitrate is not
# special-cased -- it rides the floor loop to the 720p refusal, which IS the
# audio-alone-exceeds-budget refusal, so no negative, zero, or -nan -b:v ever
# reaches ffmpeg argv.
plan_target() {
local input="$1" target_bytes="$2" res="$3"
local src_bytes duration audio_kbps video_kbps floor min_label

src_bytes=$(stat -c %s "$input" 2>/dev/null || true)
if [[ $src_bytes =~ ^[0-9]+$ ]] && (( target_bytes >= src_bytes )); then
echo "Invalid --target: $(numfmt --to=si "$target_bytes") meets or exceeds the source size ($(numfmt --to=si "$src_bytes")); drop --target and pick a quality for format conversion" >&2
return 1
fi

# The probed duration is mandatory -- there is no qualitative fallback under
# --target. Captures stay on their own lines so a nonzero status is never
# masked by local.
duration=$(video_duration "$input") ||
{ echo "Cannot determine duration for $input; cannot size to a target" >&2; return 1; }
audio_kbps=$(video_audio_kbps "$input")

# Duration is gated inside awk because (( )) cannot compare floats ("60.033"
# is a syntax error there). %d truncates toward zero and may go negative;
# the floor loop converts that into the 720p refusal.
video_kbps=$(awk -v b="$target_bytes" -v d="$duration" -v a="$audio_kbps" 'BEGIN {
if (d <= 0) exit 1
printf "%d", b * 8 / d / 1000 * 0.98 - a
}') ||
{ echo "Cannot determine duration for $input; cannot size to a target" >&2; return 1; }

while :; do
case "$res" in
4k) floor=2000 ;;
1080p) floor=800 ;;
720p) floor=400 ;;
*) echo "Invalid video resolution: $res" >&2; return 1 ;;
esac
(( video_kbps >= floor )) && break
case "$res" in
4k) res=1080p ;;
1080p) res=720p ;;
*)
# Below the 720p floor: refuse naming the achievable minimum at that
# floor -- (400k + audio) * duration * 125 bytes, in decimal MB.
min_label=$(awk -v a="$audio_kbps" -v d="$duration" \
'BEGIN { printf "%.0f MB", (400 + a) * d * 125 / 1000000 }')
echo "Cannot fit under $(numfmt --to=si "$target_bytes") -- smallest achievable is ~$min_label for this duration" >&2
return 1
;;
esac
done

printf '%s %s\n' "$res" "$video_kbps"
}

# Two-pass encode to a size budget: pass 1 writes stats into a per-run mktemp
# passdir under TMPDIR (never the output dir -- a stale passlog would silently
# corrupt the next run) and pass 2 encodes at the derived -b:v. The passdir is
# removed whole by an EXIT trap plus an explicit rm at the end -- EXIT, not
# RETURN, because a failed pass aborts under set -e without firing
# function-return traps, and the -d guard keeps the persisted trap inert after
# return (this script has no other EXIT trap). -vf/-c:v/-preset/-b:v are
# identical across passes; -an only on pass 1, -movflags only on pass 2, and
# no -crf anywhere (the tier arms own that flag). The scale and codec tables
# deliberately duplicate transcode_video's per the quality_token convention --
# a shared table would refactor that code inside the PR conflict window.
transcode_video_target() {
local input="$1" resolution="$2" output="$3" video_kbps="$4" target_bytes="$5"
local notify_id="${6:-}" desc="${7:-}"
local scale codec preset passdir actual retry_kbps

case "$resolution" in
4k) scale='scale=-2:2160' ;;
1080p) scale='scale=-2:1080' ;;
720p) scale='scale=-2:720' ;;
*)
echo "Invalid video resolution: $resolution" >&2
return 1
;;
esac

if [[ $resolution == "4k" ]]; then
codec=libx265
preset=slow
else
codec=libx264
preset=fast
fi

# The trap bakes the resolved path in -- locals die with the function under
# errexit, so a '$passdir' trap would see the variable already unset.
passdir=$(mktemp -d "${TMPDIR:-/tmp}/transcode-2pass.XXXXXX")
trap "rm -rf -- $(printf '%q' "$passdir")" EXIT

ffmpeg -i "$input" -vf "$scale" -c:v "$codec" -preset "$preset" \
-b:v "${video_kbps}k" -pass 1 -passlogfile "$passdir/2pass" \
-an -f null /dev/null

# One toast, replaced in place: pass 1/2 -> pass 2/2. A real if keeps the
# skip deliberate -- a failing [[ ]] && cmd statement would be silently
# inert too, but if names the intent.
if [[ $notify_id =~ ^[0-9]+$ ]]; then
omarchy-notification-send -r "$notify_id" -g  "Transcoding video…" \
"${desc:-$(basename -- "$input") to mp4 ($resolution}, pass 2/2)" || true
fi

ffmpeg -i "$input" -vf "$scale" -c:v "$codec" -preset "$preset" \
-b:v "${video_kbps}k" -pass 2 -passlogfile "$passdir/2pass" \
-c:a aac -b:a 192k -movflags +faststart "$output"

# Any byte-over target triggers exactly one pass-2-only retry at a
# tightened bitrate -- video_kbps scaled by target/actual, resolution and
# the 192k audio fixed (re-planning could silently move resolution after
# the filename and toasts committed to it). The retry encodes to a passdir
# sibling -- unique, so no -y is ever needed -- and mv's onto $output only
# on success, so a failed retry preserves the overshot-but-playable first
# output. The done toast reports the stat-measured actual size either way;
# that honest hit/miss report is the point of the feature.
actual=$(stat -c %s "$output" 2>/dev/null || true)
if [[ $actual =~ ^[0-9]+$ ]] && (( actual > target_bytes )); then
retry_kbps=$(awk -v k="$video_kbps" -v t="$target_bytes" -v a="$actual" \
'BEGIN { printf "%d", k * t / a }')
if [[ $retry_kbps =~ ^[0-9]+$ ]] && (( retry_kbps > 0 )); then
if ffmpeg -i "$input" -vf "$scale" -c:v "$codec" -preset "$preset" \
-b:v "${retry_kbps}k" -pass 2 -passlogfile "$passdir/2pass" \
-c:a aac -b:a 192k -movflags +faststart "$passdir/retry.mp4"; then
mv -f -- "$passdir/retry.mp4" "$output"
fi
fi
fi

# The retry reuses the passlog, so the explicit cleanup waits until here;
# the EXIT trap stays armed as the failure-path backstop.
rm -rf "$passdir"
}

main() {
local input="" format="" resolution="" search_path=""
local type output quality size positional=()
local target_bytes="" target_token="" video_kbps="" requested_resolution=""
local notify_id="" plan="" target_desc=""

while (( $# > 0 )); do
case "$1" in
Expand All @@ -309,6 +512,12 @@ main() {
(( $# > 0 )) || { echo "Missing value for --path" >&2; return 2; }
search_path="$1"
;;
--target)
shift
(( $# > 0 )) || { echo "Missing value for --target" >&2; return 2; }
target_bytes=$(parse_target_size "$1") || return 2
target_token=$(numfmt --to=si "$target_bytes")
;;
--help | -h)
usage
return 0
Expand Down Expand Up @@ -346,6 +555,10 @@ main() {
type=$(media_type "$input")

if [[ -n $quality ]]; then
if [[ -n $target_bytes ]]; then
echo "Invalid argument: --target cannot be combined with a quality tier ($quality)" >&2
return 1
fi
if [[ $type == "picture" ]]; then
echo "Invalid argument: quality applies to videos only" >&2
return 1
Expand All @@ -360,6 +573,11 @@ main() {
esac
fi

if [[ -n $target_bytes && $type == "picture" ]]; then
echo "Invalid argument: --target applies to videos only" >&2
return 1
fi

if [[ -z $format ]]; then
if [[ $type == "picture" ]]; then
format=$(omarchy-menu-select "Select format" jpg png)
Expand All @@ -384,6 +602,13 @@ main() {
return 1
;;
esac
# Format may have come from the interactive menu, so the gif refusal
# lives here -- a menu-picked gif under --target dies on this check, not
# on the resolution case below.
if [[ -n $target_bytes && $format == "gif" ]]; then
echo "Invalid argument: --target is not supported for gif output" >&2
return 1
fi
case "$resolution" in
4k | 1080p | 720p) ;;
*)
Expand All @@ -408,15 +633,48 @@ main() {
esac
fi

if [[ $type == "video" && -z $quality ]]; then
if [[ $type == "video" && -z $quality && -z $target_bytes ]]; then
quality=$(select_quality "$input" "$format" "$resolution")
# A Custom size… pick returns target:<bytes> -- unwrap into the same two
# variables --target sets, so the planner block, output_path, and the
# dispatch below are byte-identical to a CLI run (D-00f).
if [[ $quality == target:* ]]; then
target_bytes="${quality#target:}"
[[ $target_bytes =~ ^[0-9]+$ ]] ||
{ echo "Invalid target size: $target_bytes" >&2; return 1; }
target_token=$(numfmt --to=si "$target_bytes")
quality=""
fi
fi

output=$(output_path "$input" "$format" "$resolution" "$quality")
# Under --target the planner runs after every menu and before the output
# name: it may step the requested resolution down to the highest rung whose
# bitrate floor fits, and writing the effective rung back into $resolution
# makes the filename and both toasts name it for free.
if [[ -n $target_bytes ]]; then
requested_resolution="$resolution"
plan=$(plan_target "$input" "$target_bytes" "$requested_resolution")
read -r resolution video_kbps <<<"$plan"
fi

output=$(output_path "$input" "$format" "$resolution" "${target_token:-$quality}")

if [[ $type == "video" ]]; then
omarchy-notification-send -g  "Transcoding video…" "$(basename -- "$input") to $format ($resolution)"
transcode_video "$input" "$format" "$resolution" "$output" "$quality"
if [[ -n $target_bytes ]]; then
# The start toast carries the effective resolution, the step-down
# disclosure, and the target; -p captures the daemon id so the pass-2
# update inside transcode_video_target can replace it in place.
target_desc="$(basename -- "$input") to $format ($resolution"
if [[ $requested_resolution != "$resolution" ]]; then
target_desc+=" — stepped down from $requested_resolution"
fi
target_desc+=", target ≤$target_token"
notify_id=$(omarchy-notification-send -p -g  "Transcoding video…" "$target_desc, pass 1/2)")
transcode_video_target "$input" "$resolution" "$output" "$video_kbps" "$target_bytes" "$notify_id" "$target_desc"
else
omarchy-notification-send -g  "Transcoding video…" "$(basename -- "$input") to $format ($resolution)"
transcode_video "$input" "$format" "$resolution" "$output" "$quality"
fi
copy_to_clipboard "$output"
size=$(output_size_label "$output" || true)
omarchy-notification-send -g  "Transcoded to $resolution $format" "Saved and copied to clipboard${size:+ ($size)}."
Expand Down
Loading