# url encode one-liner for soundpost urls
urle () { [[ "${1}" ]] || return 1; local LANG=C i x; for (( i = 0; i < ${#1}; i++ )); do x="${1:$i:1}"; [[ "${x}" == [a-zA-Z0-9.~_-] ]] && echo -n "${x}" || printf '%%%02X' "'${x}"; done; echo; }

# soundpost_download <url> 2:30 30
soundpost_download ()
{
  yt-dlp -f "(bestvideo+bestaudio/best)" $1 --external-downloader ffmpeg --external-downloader-args "ffmpeg_i:-ss $2 -t $3" -o streamclip
  mpv streamclip.webm
}
alias spd="soundpost_download"


# soundpost_crop in_w/4 in_h/2 3*in_w/4 in_h/2
_soundpost_crop ()
{
  crop="crop=$1:$2:$3:$4"
  ffmpeg -y -i streamclip.webm -c:a copy -c:v libvpx -cpu-used -5 -deadline realtime -vf ${crop} soundpost-precrop.webm
  mpv soundpost-precrop.webm
}
alias soundpost_crop="noglob _soundpost_crop"
alias spc="noglob _soundpost_crop"

# soundpost_trim 10 25
soundpost_trim ()
{
  trim=$1
  dur=$2
  ffmpeg -y -i streamclip.webm -c:a copy -c:v libvpx -cpu-used -5 -deadline realtime -ss ${trim} -t ${dur} soundpost-pretrim.webm
  mpv soundpost-pretrim.webm
}
alias spt="soundpost_trim"

# soundpost_finalise
soundpost_finalise ()
{
  ffmpeg -y -i streamclip.webm -c:a copy -c:v libvpx -b:v 10M -crf 5 -vf ${crop} -ss ${trim} -t ${dur} soundpost.webm
  mpv soundpost.webm
}
alias spf="soundpost_finalise"

# soundpost_shrink -1 270
soundpost_shrink ()
{
  ffmpeg -y -i soundpost.webm -vn -c:a copy ${PWD##*/}.ogg
  local target_bitrate=$((24000/$dur*0.99))
  local targ_bv=${target_bitrate%.*}k
  ffmpeg -y -i soundpost.webm -an -c:v libvpx -vf "scale=$1:$2" -b:v $targ_bv -pass 1 ${PWD##*/}.webm
  ffmpeg -y -i soundpost.webm -an -c:v libvpx -vf "scale=$1:$2" -b:v $targ_bv -pass 2 ${PWD##*/}.webm
  mpv ${PWD##*/}.webm
}
alias sps="soundpost_shrink"

# soundpost_upload
soundpost_upload () 
{
  local catbox=`curl -fL -F "reqtype=fileupload" -F "fileToUpload=@${PWD##*/}.ogg" https://catbox.moe/user/api.php`
  local zzht=`curl -fL -F "files[]=@${PWD##*/}.ogg" https://zz.ht/api/upload | jq -c -r '.files[].url'`
  local pomf=`curl -fL -F "files[]=@${PWD##*/}.ogg" https://pomf.cat/upload.php | jq -c -r --arg base https://a.pomf.cat/ '$base + .files[].url'`
  local sound="[sound=$(urle $catbox)][sound=$(urle $zzht)][sound=$(urle $pomf)]"
  mv "${PWD##*/}.webm" "${PWD##*/}${sound}.webm"
  mv "${PWD##*/}${sound}.webm" ../
}
alias spu="soundpost_upload"