#!/bin/sh -e
#
# yt-dl-choose - play video with mpv/yt-dlp - lets you select video format
# to download useful when launching e.g. yt videos,
# which often have very high resolution default format that would buffer a lot
#
# usage: yt-dl-choose <URL>
#
# note:
#   - only displays formats that have both audio and video, which have
#     limited quality. for highest resolution, we'd also need to provide
#     options for combined formats with separate audio and video streams.
#   - when given a video in a YouTube playlist, will only play that video.

NO_PLAYLIST=1

if [ "$#" -ne 1 ]; then
  printf '%s\n' "usage: $(basename "$0") <url>"
  exit 1
fi

url="$1"

if [ -n "${NO_PLAYLIST}" ]; then
  url=$(echo "${url}" | sed -e 's/&list=.*&/\&/')
fi

video_formats=$(yt-dlp --list-formats "${url}" \
  | grep "video only" \
  | grep -v mhtml)
printf '%b' "video formats are:\n${video_formats}"
video_format=$(echo "${video_formats}" | fzf | cut -d' ' -f1)

if [ -z "${video_format}" ]; then
  exit 0
fi

mpv --ytdl-format="${video_format}+bestaudio" "${url}"
