#!/bin/bash

# omarchy:summary=Start or stop screen recording
# omarchy:group=capture
# omarchy:args=[--fullscreen] [--with-desktop-audio] [--with-microphone-audio] [--with-webcam] [--webcam-device=<device>] [--webcam-size=<small|medium|large>] [--resolution=<size>] [--stop-recording] [--status]
# omarchy:examples=omarchy screenrecord | omarchy capture screenrecording --with-desktop-audio
# omarchy:aliases=omarchy screenrecord
#
# Env: OMARCHY_SCREENRECORD_USE_PORTAL=true skips the built-in slurp picker and
# uses gpu-screen-recorder's xdg-desktop-portal capture backend instead. The
# portal backend was originally added (PR #3401) for HDR-aware capture, support
# for monitors driven by external GPUs, and window capture — enable it if any
# of those matter to you. Off by default because the portal path can fail EGL
# DMA-BUF modifier import on some configurations, leaving recording unable to
# start.
#
# Env: OMARCHY_SCREENRECORD_DEBUG=true appends the recorder's stderr (and the
# picker target it was launched with) to $XDG_RUNTIME_DIR/omarchy-screenrecord.log
# so users can attach a log when reporting capture failures.
#
# Backend: gpu-screen-recorder. Where it is not installed, or it exits before
# the recording starts (it knows only NVIDIA, AMD, Intel and Broadcom GPUs, and
# aborts on others such as Apple Silicon's), wf-recorder records instead when
# it is installed. wf-recorder encodes on the CPU and captures one audio
# device, so desktop and microphone audio together go through a temporary null
# sink. Portal capture and --resolution are gpu-screen-recorder only.

DESKTOP_AUDIO="false"
MICROPHONE_AUDIO="false"
WEBCAM="false"
WEBCAM_DEVICE=""
WEBCAM_SIZE="medium"
RESOLUTION=""
FULLSCREEN="false"
STOP_RECORDING="false"
STATUS="false"
# Both of these live in the per-user runtime directory, which is 0700. What
# RECORDING_FILE holds is read back on stop and used as a path -- ffmpeg writes
# beside it, `mv` replaces it, and `rm -f` deletes its preview -- so a name in
# world-writable /tmp is a name any other local account can create first and
# then point wherever it likes. The debug log carries the recorder's stderr and
# the picked geometry, which is nobody else's business either. Fall back to
# the state directory when there is no session runtime dir -- :-/tmp would put
# both files back at the fixed names this comment describes.
RUNTIME_DIR="${XDG_RUNTIME_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/omarchy}"
RECORDING_FILE="$RUNTIME_DIR/omarchy-screenrecord-filename"
REGION_FILE="$RUNTIME_DIR/omarchy-screenrecord-region"
# The recorder's pid, so stop and status act on that process alone.
REC_PID_FILE="$RUNTIME_DIR/omarchy-screenrecord-pid"
# The PulseAudio module ids of a combined-audio null sink, for cleanup.
PA_MODULES_FILE="$RUNTIME_DIR/omarchy-screenrecord-pa-modules"
# Present while a start holds the lock; another toggle or stop then leaves
# CANCEL_FILE for that start instead of queueing behind its picker or recorder.
STARTING_FILE="$RUNTIME_DIR/omarchy-screenrecord-starting"
CANCEL_FILE="$RUNTIME_DIR/omarchy-screenrecord-cancel"
# How long a recorder may take to create its file, except through the portal,
# whose picker waits on the user.
READY_TIMEOUT_TICKS=75
LOG_FILE=$([[ ${OMARCHY_SCREENRECORD_DEBUG:-false} == "true" ]] && echo "$RUNTIME_DIR/omarchy-screenrecord.log" || echo "/dev/null")

for arg in "$@"; do
  case "$arg" in
  --with-desktop-audio) DESKTOP_AUDIO="true" ;;
  --with-microphone-audio) MICROPHONE_AUDIO="true" ;;
  --with-webcam) WEBCAM="true" ;;
  --webcam-device=*) WEBCAM_DEVICE="${arg#*=}" ;;
  --webcam-size=*) WEBCAM_SIZE="${arg#*=}" ;;
  --resolution=*) RESOLUTION="${arg#*=}" ;;
  --fullscreen) FULLSCREEN="true" ;;
  --stop-recording) STOP_RECORDING="true" ;;
  --status) STATUS="true" ;;
  esac
done

case $WEBCAM_SIZE in
small | medium | large) ;;
*)
  echo "Invalid webcam size: $WEBCAM_SIZE (expected small, medium, or large)" >&2
  exit 1
  ;;
esac

# --status only answers whether our recording runs, for the bar and the menu, so
# it needs no recordings directory and never notifies.
if [[ $STATUS != "true" ]]; then
  [[ -f ~/.config/user-dirs.dirs ]] && source ~/.config/user-dirs.dirs
  OUTPUT_DIR="${OMARCHY_SCREENRECORD_DIR:-${XDG_VIDEOS_DIR:-$HOME/Videos}}"
  if [[ ! -d $OUTPUT_DIR ]]; then
    omarchy-notification-send -u critical -t 3000 "$(omarchy-i18n capture.noRecordingDir "$OUTPUT_DIR")"
    exit 1
  fi
fi

start_webcam_overlay() {
  cleanup_webcam

  # Auto-detect first available webcam if none specified
  if [[ -z $WEBCAM_DEVICE ]]; then
    WEBCAM_DEVICE=$(omarchy-capture-webcam-list | sed -n '1s/[[:space:]].*//p')
    if [[ -z $WEBCAM_DEVICE ]]; then
      omarchy-notification-send -u critical -t 3000 "$(omarchy-i18n capture.noWebcam)"
      return 1
    fi
  fi

  # Try preferred 16:9 resolutions in order, use first available
  local preferred_resolutions=("640x360" "1280x720" "1920x1080")
  local capture_options=(-framerate 30)
  local available_formats=$(v4l2-ctl --list-formats-ext -d "$WEBCAM_DEVICE" 2>/dev/null)

  for resolution in "${preferred_resolutions[@]}"; do
    if echo "$available_formats" | grep -q "$resolution"; then
      capture_options=(-video_size "$resolution" "${capture_options[@]}")
      break
    fi
  done

  # ffplay's SDL window takes its Wayland app id from the environment, which the
  # overlay's window rules match on.
  SDL_VIDEO_WAYLAND_WMCLASS="WebcamOverlay-$WEBCAM_SIZE" SDL_APP_ID="WebcamOverlay-$WEBCAM_SIZE" \
    ffplay -f v4l2 "${capture_options[@]}" -i "$WEBCAM_DEVICE" \
    -fflags nobuffer -flags low_delay -framedrop -sync ext \
    -vf 'crop=ih*8/9:ih' \
    -window_title WebcamOverlay -noborder -an \
    -loglevel quiet 9>&- &>/dev/null &

  # The move has to settle before gpu-screen-recorder starts, or the camera is
  # recorded sliding into its corner. Waiting for the map is what the blind
  # second was partly guessing at, so the remainder is trimmed to hold the
  # pre-capture delay where it was: starting later costs the first words spoken.
  local waited=0
  while ((waited < 40)) && ! hyprctl clients -j | jq -e 'any(.[]; .title == "WebcamOverlay")' >/dev/null 2>&1; do
    sleep 0.05
    ((waited++))
  done

  [[ ${1:-} == region:* ]] && echo "${1#region:}" >"$REGION_FILE"
  omarchy-capture-webcam-resize "$WEBCAM_SIZE"

  sleep 0.6
}

cleanup_webcam() {
  pkill -f "WebcamOverlay" 2>/dev/null
  rm -f "$REGION_FILE"
}

cap_resolution() {
  local width=$1 height=$2
  [[ $width =~ ^[0-9]+$ && $height =~ ^[0-9]+$ ]] || return

  if ((height > width)); then
    if ((width > 2160 || height > 3840)); then
      echo "2160x3840"
    fi
  elif ((width > 3840 || height > 2160)); then
    echo "3840x2160"
  fi
}

default_resolution() {
  local monitor=${1:-} width height capped
  read -r width height < <(hyprctl monitors -j | jq -r --arg name "$monitor" '
    first(.[] | select(if $name != "" then .name == $name else .focused == true end)) |
    if ((.transform // 0) % 2) == 1 then "\(.height) \(.width)" else "\(.width) \(.height)" end
  ')
  capped=$(cap_resolution "$width" "$height")
  echo "${capped:-0x0}"
}

# Cap a region whose physical pixel size exceeds 4K so gpu-screen-recorder stays
# on its hardware H.264 encoder instead of switching to HEVC (which Chromium on
# Linux and many chat players cannot play). Smaller regions omit -s so they are
# recorded at native pixels and never upscaled.
region_resolution() {
  [[ $1 =~ ^([0-9]+)x([0-9]+)\+(-?[0-9]+)\+(-?[0-9]+)$ ]] || return
  local rw=${BASH_REMATCH[1]} rh=${BASH_REMATCH[2]} rx=${BASH_REMATCH[3]} ry=${BASH_REMATCH[4]}
  local width height
  read -r width height < <(hyprctl monitors -j | jq -r \
    --argjson rw "$rw" --argjson rh "$rh" --argjson rx "$rx" --argjson ry "$ry" '
    . as $monitors |
    [ $monitors[] |
      select((.mirrorOf // "none") == "none") |
      (((.transform // 0) % 2) == 1) as $rot |
      (if $rot then .height else .width end / (.scale // 1)) as $mw |
      (if $rot then .width else .height end / (.scale // 1)) as $mh |
      select(.x < ($rx + $rw) and (.x + $mw) > $rx and .y < ($ry + $rh) and (.y + $mh) > $ry) |
      (.scale // 1)
    ] | (max // ([ $monitors[] | select(.focused == true) | (.scale // 1) ] | first) // 1) as $s |
    "\($rw * $s | round) \($rh * $s | round)"
  ')
  cap_resolution "$width" "$height"
}

screenrecording_needs_cpu_encoder() {
  # AMD Polaris GPUs can hang their VCE 3.4 encode ring mid-recording and lose
  # compositor VRAM when the ensuing GPU reset fails (#9555). The recorder's
  # fallback cannot recover from a GPU that has already hung, so avoid starting
  # hardware encoding on Polaris altogether. The IDs are amdgpu's CHIP_POLARIS10,
  # 11, 12 and CHIP_VEGAM, read from sysfs as lspci would wake a suspended dGPU.
  local polaris=(
    0x67c0 0x67c1 0x67c2 0x67c4 0x67c7 0x67c8 0x67c9 0x67ca 0x67cc 0x67cf 0x67d0 0x67d4 0x67df 0x6fdf
    0x67e0 0x67e1 0x67e3 0x67e7 0x67e8 0x67e9 0x67eb 0x67ef 0x67ff
    0x6980 0x6981 0x6985 0x6986 0x6987 0x698f 0x6995 0x6997 0x699f
    0x694c 0x694e 0x694f
  )
  local device vendor id

  for device in "${OMARCHY_PCI_DEVICES_PATH:-/sys/bus/pci/devices}"/*; do
    [[ -r $device/device ]] && read -r vendor <"$device/vendor" && read -r id <"$device/device" || continue
    [[ $vendor == "0x1002" && " ${polaris[*]} " == *" $id "* ]] && return 0
  done

  return 1
}

# Echoes "monitor:NAME" when the selection matches an entire monitor (prefer
# -w <monitor> over a region capture — same kms backend, but no scaling math
# and full native res), otherwise "region:WxH+X+Y". Returns non-zero if the
# user cancelled the picker.
select_capture_target() {
  local target
  target=$(omarchy-capture-region smart --match-monitor) || return 1

  if [[ $target == monitor:* ]]; then
    echo "$target"
    return
  fi

  [[ $target =~ ^(-?[0-9]+),(-?[0-9]+)[[:space:]]([0-9]+)x([0-9]+)$ ]] || return 1

  # gpu-screen-recorder wants region geometry in the compositor's logical
  # coordinate space — same space slurp returns — so pass the values through
  # untouched. (gsr scales to physical pixels itself based on the monitor.)
  echo "region:${BASH_REMATCH[3]}x${BASH_REMATCH[4]}+${BASH_REMATCH[1]}+${BASH_REMATCH[2]}"
}

# gpu-screen-recorder first, then wf-recorder, of those installed. The base
# packages carry gpu-screen-recorder, but an architecture may build none.
recorder_backends() {
  local backend found=false

  for backend in gpu-screen-recorder wf-recorder; do
    if omarchy-cmd-present "$backend"; then
      echo "$backend"
      found=true
    fi
  done

  # Neither installed: fail the way a missing gpu-screen-recorder always has.
  $found || echo gpu-screen-recorder
}

# wf-recorder records a single audio device. Map the desktop/mic flags onto one:
# desktop -> default sink monitor, mic -> default source. When both are requested,
# route them through a throwaway null sink so a single track carries both; the
# module ids are saved to PA_MODULES_FILE so stop can unload them. A requested
# source that can't be recorded is left out with a notification naming it, and
# the recording carries whichever source remains.
wf_audio_device() {
  local sink="" source="" m
  [[ $DESKTOP_AUDIO == "true" ]] && sink=$(pactl get-default-sink 2>/dev/null)
  [[ $MICROPHONE_AUDIO == "true" ]] && source=$(pactl get-default-source 2>/dev/null)
  # With no default source pactl answers its own placeholder, never nothing.
  [[ $source == "@DEFAULT_SOURCE@" ]] && source=""

  if [[ -n $sink && -n $source ]]; then
    if m=$(pactl load-module module-null-sink sink_name=omarchy_screenrec sink_properties=device.description=omarchy_screenrec 2>/dev/null); then
      echo "$m" >"$PA_MODULES_FILE"
      if m=$(pactl load-module module-loopback source="${sink}.monitor" sink=omarchy_screenrec latency_msec=20 2>/dev/null); then
        echo "$m" >>"$PA_MODULES_FILE"
      else
        sink=""
      fi
      if m=$(pactl load-module module-loopback source="$source" sink=omarchy_screenrec latency_msec=20 2>/dev/null); then
        echo "$m" >>"$PA_MODULES_FILE"
      else
        source=""
      fi
      if [[ -n $sink && -n $source ]]; then
        echo "omarchy_screenrec.monitor"
        return
      fi
      wf_audio_cleanup
    else
      # No device to mix into: desktop audio records alone, as it always has.
      source=""
    fi
  fi

  [[ $DESKTOP_AUDIO == "true" && -z $sink ]] && wf_audio_unavailable desktop
  [[ $MICROPHONE_AUDIO == "true" && -z $source ]] && wf_audio_unavailable microphone
  if [[ -n $sink ]]; then
    echo "${sink}.monitor"
  elif [[ -n $source ]]; then
    echo "$source"
  fi
}

wf_audio_unavailable() {
  omarchy-notification-send -u critical -t 5000 "$(omarchy-i18n capture.recordingWithoutAudio "$1")" "$(omarchy-i18n capture.audioNotAdded "$1")" >/dev/null 2>&1
}

wf_audio_cleanup() {
  [[ -f $PA_MODULES_FILE ]] || return
  # Unload in reverse so the loopbacks drop before the null sink they feed.
  tac "$PA_MODULES_FILE" 2>/dev/null | while read -r m; do
    [[ -n $m ]] && pactl unload-module "$m" 2>/dev/null
  done
  rm -f "$PA_MODULES_FILE"
}

# Launches wf-recorder for the given picker target, backgrounded, with REC_PID set.
launch_wf_recorder() {
  local target=$1 filename=$2
  local geom_args=()

  case $target in
  monitor:*)
    geom_args=(-o "${target#monitor:}")
    ;;
  region:*)
    # region:WxH+X+Y (logical coords) -> wf-recorder -g "X,Y WxH" (same space).
    [[ ${target#region:} =~ ^([0-9]+)x([0-9]+)\+(-?[0-9]+)\+(-?[0-9]+)$ ]] || return 1
    geom_args=(-g "${BASH_REMATCH[3]},${BASH_REMATCH[4]} ${BASH_REMATCH[1]}x${BASH_REMATCH[2]}")
    ;;
  *)
    return 1
    ;;
  esac

  local audio_args=() dev
  dev=$(wf_audio_device)
  [[ -n $dev ]] && audio_args=(--audio="$dev")

  # -r 60 caps the framerate: capturing a 120 Hz panel at its native rate makes
  # needlessly large files. -R 48000 keeps the AAC track at 48 kHz rather than
  # following a sink that advertises 96 kHz into a file many players, and some
  # speaker DSPs, play as silence. -D captures every frame, not only changed
  # ones: wf-recorder reads a stop signal only when a frame arrives, so on a
  # still screen it would never exit and the stop would have to kill it.
  wf-recorder "${geom_args[@]}" -D -r 60 -R 48000 "${audio_args[@]}" -f "$filename" 9>&- 2>>"$LOG_FILE" &
  REC_PID=$!
}

start_cancelled() {
  [[ -e $CANCEL_FILE ]]
}

# Stops a recorder this start launched: TERM, two seconds to exit, then KILL.
end_launched_recorder() {
  local pid=$1 waited=0 state
  kill "$pid" 2>/dev/null
  while (( waited++ < 20 )); do
    state=$(<"/proc/$pid/stat") 2>/dev/null || break
    state=${state##*) }
    [[ ${state:0:1} != "Z" ]] || break
    sleep 0.1
  done
  kill -KILL "$pid" 2>/dev/null
  wait "$pid" 2>/dev/null
}

start_screenrecording() {
  # A pid left by a recording that ended without a stop would otherwise hide
  # this one from the toggle until it has started and saved its own.
  rm -f "$REC_PID_FILE"
  local capture_args=()
  local target

  # Opt-in path for HDR, external-GPU monitors, and window capture (all things
  # the portal backend supports and the kms backend doesn't). Default flow uses
  # slurp + the kms backend, which avoids the EGL DMA-BUF modifier import
  # failures the portal path can hit on some configurations.
  if [[ ${OMARCHY_SCREENRECORD_USE_PORTAL:-false} == "true" ]]; then
    target="portal"
    capture_args=(-w portal -s "${RESOLUTION:-$(default_resolution)}")
  elif [[ $FULLSCREEN == "true" ]]; then
    target="monitor:$(omarchy-hyprland-monitor-focused)"
    capture_args=(-w "${target#monitor:}" -s "${RESOLUTION:-$(default_resolution "${target#monitor:}")}")
  else
    target=$(select_capture_target) || return 1
    start_cancelled && return 1

    case $target in
    monitor:*)
      capture_args=(-w "${target#monitor:}" -s "${RESOLUTION:-$(default_resolution "${target#monitor:}")}")
      ;;
    region:*)
      local region=${target#region:}
      local res="${RESOLUTION:-$(region_resolution "$region")}"
      capture_args=(-w "$region")
      [[ -n $res ]] && capture_args+=(-s "$res")
      ;;
    esac
  fi

  [[ $WEBCAM == "true" ]] && start_webcam_overlay "$target"
  start_cancelled && return 1

  local filename="$OUTPUT_DIR/screenrecording-$(date +'%Y-%m-%d_%H-%M-%S').mp4"
  local backend pid=""

  for backend in $(recorder_backends); do
    [[ $backend == "wf-recorder" && $target == "portal" ]] && continue
    echo "===== $(date '+%F %T') args: $* backend: $backend target: $target =====" >>"$LOG_FILE"

    if [[ $backend == "wf-recorder" ]]; then
      launch_wf_recorder "$target" "$filename" || continue
      pid=$REC_PID
    else
      local audio_devices=""
      local audio_args=()
      local encoder_args=()

      if screenrecording_needs_cpu_encoder; then
        encoder_args=(-encoder cpu)
      fi

      [[ $DESKTOP_AUDIO == "true" ]] && audio_devices+="default_output"

      if [[ $MICROPHONE_AUDIO == "true" ]]; then
        # Merge audio tracks into one - separate tracks only play one at a time in most players
        [[ -n $audio_devices ]] && audio_devices+="|"
        audio_devices+="default_input"
      fi

      [[ -n $audio_devices ]] && audio_args+=(-a "$audio_devices" -ac aac)

      gpu-screen-recorder "${capture_args[@]}" "${encoder_args[@]}" -k auto -f 60 -fm cfr -fallback-cpu-encoding yes -o "$filename" "${audio_args[@]}" 9>&- 2>>"$LOG_FILE" &
      pid=$!
    fi

    local ticks=0
    while kill -0 $pid 2>/dev/null && [[ ! -f $filename ]]; do
      start_cancelled && break
      if [[ $target != "portal" ]] && (( ++ticks > READY_TIMEOUT_TICKS )); then
        end_launched_recorder "$pid"
        wf_audio_cleanup
        rm -f "$filename"
        continue 2
      fi
      sleep 0.2
    done

    if start_cancelled; then
      end_launched_recorder "$pid"
      wf_audio_cleanup
      rm -f "$filename"
      return 1
    fi

    if kill -0 $pid 2>/dev/null; then
      echo "$pid" >"$REC_PID_FILE"
      echo "$filename" >"$RECORDING_FILE"
      toggle_screenrecording_indicator
      return 0
    fi

    wf_audio_cleanup
    rm -f "$filename"
  done

  return 1
}

# Selects the recorder this script started, by the pid it saved. A saved pid
# that is no longer a recorder is a recording that ended without a stop, so
# nothing of ours is recording and no other recorder is touched. Without a
# saved pid (a recording started before the pid was saved), every recorder the
# user runs counts, as for the bar indicator and the menu.
select_recorder() {
  RECORDER=()
  RECORDER_VERIFIED=0
  [[ -f $REC_PID_FILE ]] || return 0

  local pid
  pid=$(<"$REC_PID_FILE")
  [[ $pid =~ ^[0-9]+$ ]] && omarchy-capture-screenrecording-process --pid "$pid" || return 1
  RECORDER=(--pid "$pid")
  RECORDER_VERIFIED=1
}

# Stops the recorder screenrecording_active selected.
stop_screenrecording() {
  omarchy-capture-screenrecording-process "${RECORDER[@]}" --signal INT # SIGINT required to save video properly

  # Wait a maximum of 5 seconds to finish before hard killing
  local count=0
  while omarchy-capture-screenrecording-process "${RECORDER[@]}" && ((count < 50)); do
    sleep 0.1
    count=$((count + 1))
  done

  toggle_screenrecording_indicator
  cleanup_webcam
  wf_audio_cleanup

  if omarchy-capture-screenrecording-process "${RECORDER[@]}"; then
    omarchy-capture-screenrecording-process "${RECORDER[@]}" --signal KILL
    omarchy-notification-send -u critical -t 5000 "$(omarchy-i18n capture.recordingError)" "$(omarchy-i18n capture.recordingKilled)"
  elif [[ ! -f $(cat "$RECORDING_FILE" 2>/dev/null) ]]; then
    # No recording to finalize or show, as when stopping a recorder this script did not start.
    :
  else
    local filename=$(cat "$RECORDING_FILE" 2>/dev/null)
    local preview="$RUNTIME_DIR/omarchy-screenrecord-preview-$$.png"

    # Take the preview frame from the raw recording while finalizing runs,
    # 0.2s in: the frame the finalized video, trimmed by 0.1s, shows at 0.1s.
    # Finalizing renames its output over the file, so the raw one is held open
    # here first and ffmpeg reads it through that descriptor, whenever it starts.
    local raw_fd preview_pid=""
    if exec {raw_fd}<"$filename"; then
      ffmpeg -y -ss 00:00:00.2 -i "/proc/self/fd/$raw_fd" -vframes 1 -vf "scale='min(320,iw)':-2" "$preview" -loglevel quiet 2>/dev/null &
      preview_pid=$!
    fi
    finalize_recording
    if [[ -n $preview_pid ]]; then
      wait "$preview_pid"
      exec {raw_fd}<&-
    fi
    echo "$filename"

    local image_args=()
    [[ -s $preview ]] && image_args=(--image "$preview")

    omarchy-notification-send "$(omarchy-i18n capture.recordingSaved)" "$(recording_details "$filename")" \
      -t 10000 "${image_args[@]}" \
      --action "$(omarchy-i18n capture.recordingOpen)" omaview open \
      --action "$(omarchy-i18n capture.recordingCut)" omacut \
      --with "$filename"

    # The shell loads the preview into memory when the toast appears and never
    # re-reads the file, so it only has to outlive that load -- not the toast.
    # A toast held back behind others appears later, so give it half a minute.
    (
      sleep 30
      rm -f "$preview"
    ) 9>&- &
  fi

  rm -f "$RECORDING_FILE" "$REC_PID_FILE"
}

# How long the saved recording runs and how big it is, like "1:07 · 12.4 MB".
# Each number goes to omarchy-i18n on its own, so it takes the language's
# digits and decimal separator, and the units live in the catalog.
recording_details() {
  local seconds bytes length="" value unit size
  seconds=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$1" 2>/dev/null)
  if [[ $seconds =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
    seconds=$(LC_ALL=C printf '%.0f' "$seconds")
    if ((seconds >= 3600)); then
      length=$(omarchy-i18n capture.recordingLengthHours $((seconds / 3600)) \
        "$(printf '%02d' $((seconds % 3600 / 60)))" "$(printf '%02d' $((seconds % 60)))")
    else
      length=$(omarchy-i18n capture.recordingLength $((seconds / 60)) "$(printf '%02d' $((seconds % 60)))")
    fi
  fi

  bytes=$(stat -c %s "$1" 2>/dev/null) || bytes=0
  read -r value unit < <(awk -v b="$bytes" 'BEGIN {
    split("B KB MB GB", unit); i = 1
    while (b >= 1000 && i < 4) { b /= 1000; i++ }
    printf(i == 1 ? "%d %s\n" : "%.1f %s\n", b, unit[i])
  }')
  case $unit in
  KB) size=$(omarchy-i18n capture.recordingSizeKB "$value") ;;
  MB) size=$(omarchy-i18n capture.recordingSizeMB "$value") ;;
  GB) size=$(omarchy-i18n capture.recordingSizeGB "$value") ;;
  *) size=$(omarchy-i18n capture.recordingSizeB "$value") ;;
  esac

  if [[ -n $length ]]; then
    omarchy-i18n capture.recordingDetails "$length" "$size"
  else
    echo "$size"
  fi
}

toggle_screenrecording_indicator() {
  omarchy-shell -q omarchy.indicators refresh
}

screenrecording_active() {
  if select_recorder && { (( RECORDER_VERIFIED )) || omarchy-capture-screenrecording-process "${RECORDER[@]}"; }; then
    return 0
  else
    if [[ -f $REC_PID_FILE ]]; then
      wf_audio_cleanup
    fi
    return 1
  fi
}

finalize_recording() {
  local latest
  latest=$(cat "$RECORDING_FILE" 2>/dev/null)
  [[ -f $latest ]] || return

  # Re-encode only when the first GOP contains discardable warmup packets — stream copy can't
  # trim those (it rewinds to the keyframe). Clean recordings stay on the fast stream-copy path.
  local video_codec=(-c:v copy)
  if ffprobe -v error -select_streams v:0 -read_intervals %+0.2 -show_entries packet=flags -of csv=p=0 "$latest" 2>/dev/null | grep -q D; then
    video_codec=(-c:v libx264 -preset veryfast -crf 20)
  fi

  # Trim the first frame, normalize audio to -14 LUFS if present, and move the MP4 index to the
  # front so browsers can start playing before the whole file downloads, in a single pass.
  local args=(-y -ss 0.1 -i "$latest" "${video_codec[@]}" -movflags +faststart)
  if ffprobe -v error -select_streams a -show_entries stream=codec_type -of csv=p=0 "$latest" 2>/dev/null | grep -q audio; then
    # Hard-mute the first 400ms to drop the PipeWire capture-open pop (a near-clipping
    # transient around 130-200ms that a gentle fade-in can't attenuate enough), then a
    # 50ms fade avoids a click at the boundary before loudnorm normalizes the rest.
    #
    # loudnorm declares 192 kHz output, so without -ar the AAC encoder writes
    # 96 kHz from a 48 kHz recording.
    args+=(-ar 48000 -af "volume=enable='lt(t,0.4)':volume=0,afade=t=in:st=0.4:d=0.05,loudnorm=I=-14:TP=-1.5:LRA=11")
  fi

  local processed="${latest%.mp4}-processed.mp4"
  if ffmpeg "${args[@]}" "$processed" -loglevel quiet 2>/dev/null; then
    mv "$processed" "$latest"
  else
    rm -f "$processed"
  fi
}

mkdir -p "$RUNTIME_DIR" || exit 1
# XDG_STATE_HOME may be outside a private home; protect existing fallbacks too.
if [[ -z ${XDG_RUNTIME_DIR:-} ]]; then
  chmod 700 "$RUNTIME_DIR" || exit 1
fi

# Serialize changes to the recorder and its files; background children close 9.
# A busy status query stays read-only so a picker cannot stall the bar.
{
  if [[ $STATUS == "true" ]]; then
    if flock -n 9; then
      screenrecording_active
    else
      select_recorder && { (( RECORDER_VERIFIED )) || omarchy-capture-screenrecording-process "${RECORDER[@]}"; }
    fi
  else
    # A start still in its picker or waiting on its recorder is cancelled, not
    # queued behind: that toggle would otherwise begin another recording.
    # The start reads CANCEL_FILE only after it removes STARTING_FILE, so a
    # request left while STARTING_FILE stands is always seen. One that finds it
    # gone waits its turn, and a request the start used up by then is done.
    if ! flock -w 1 9; then
      touch "$CANCEL_FILE"
      # A start that was killed leaves its marker: it counts only while that
      # start still runs.
      starter=""
      [[ -r $STARTING_FILE ]] && starter=$(<"$STARTING_FILE")
      if [[ $starter =~ ^[0-9]+$ ]] && kill -0 "$starter" 2>/dev/null; then
        exit 0
      fi
      flock 9 || exit 1
      [[ -e $CANCEL_FILE ]] || exit 0
      rm -f "$CANCEL_FILE"
    fi
    if screenrecording_active; then
      stop_screenrecording
    elif [[ $STOP_RECORDING == "true" ]]; then
      exit 1
    else
      rm -f "$CANCEL_FILE"
      echo $$ >"$STARTING_FILE"
      if start_screenrecording; then
        rm -f "$STARTING_FILE"
        # Cancelled while the recording was being saved as started.
        if start_cancelled; then
          end_launched_recorder "$(<"$REC_PID_FILE")"
          wf_audio_cleanup
          cleanup_webcam
          rm -f "$(<"$RECORDING_FILE")" "$REC_PID_FILE" "$RECORDING_FILE"
          toggle_screenrecording_indicator
          rm -f "$CANCEL_FILE"
        fi
        # A request after that check is left for its requester, who stops this
        # recording once it has the lock.
      else
        rm -f "$STARTING_FILE"
        wf_audio_cleanup
        cleanup_webcam
        rm -f "$CANCEL_FILE"
      fi
    fi
  fi
} 9>>"$RUNTIME_DIR/omarchy-screenrecord.lock"
