#!/usr/bin/env bash

# Description:
#   Play the video embedded in a live photo file (or so-called Motion Photo).
#   The literal tags differ between manufacturers, so this script looks for
#   the common 'ftyp' box that indicates the start of an MP4 video stream
#   instead of "MotionPhotoVideo" or "EmbeddedVideo" or anything else.
#
# Requirements:
# - mpv or vlc.
#
# Usage:
# - playlive <file>
# - case `config/scripts/.local/share/applications/playlive.desktop` is installed,
#   right-click on a live photo file in file manager and choose "Open With..." ->
#   "Play Live Photo".

set -euo pipefail

if [ -z "${1:-}" ]; then
    echo "Usage: $0 <file>" >&2
    exit 1
fi


file="$1"

if [ ! -f "$file" ]; then
    echo "Error: File '$file' not found." >&2
    exit 1
fi

tmp_video=$(mktemp --suffix=.mp4)
trap 'rm -f "$tmp_video"' EXIT

offset=$(grep -aobP "ftyp(mp42|isom)" "$file" | tail -n 1 | cut -d: -f1 || true)

if [ -z "$offset" ]; then
    echo "Error: No valid video stream found in '$file'." >&2
    exit 1
fi

mp4_offset=$((offset - 3))

tail -c "+$mp4_offset" "$file" > "$tmp_video"

play_cmd=()
if type mpv >/dev/null 2>&1; then
    play_cmd=(mpv --title="Live Photo View: $file" --keep-open=yes --loop-file=yes --loop-playlist=no --idle=yes)
elif type vlc >/dev/null 2>&1; then
    play_cmd=(vlc --meta-title="Live Photo View: $file")
else
    echo "Error: No suitable media player found." >&2
    exit 1
fi

"${play_cmd[@]}" "$tmp_video"
