#!/bin/sh
# Bachir Soussi Chiadmi 06/2016
# https://trac.ffmpeg.org/wiki/Create%20a%20video%20slideshow%20from%20images
# needs ffmep and exiftool

function convertVideo {
  echo 'Video conversion'
  pf=$1
  vf=$2
  ffmpeg -y \
    -framerate $pf \
    -pattern_type glob -i 'public_html/pictures/*.jpg' \
    -r $vf -pix_fmt yuv420p -c:v libx264 \
    videos/timelaps-raw.mp4

  ffmpeg -y -i public_html/videos/timelaps-raw.mp4 -vf "scale=1920:-1, crop=in_w:1080" videos/timelaps-1080p.mp4
  ffmpeg -y -i videos/timelaps-raw.mp4 -vf "scale=1280:-1, crop=in_w:720" videos/timelaps-720p.mp4
  ffmpeg -y -i videos/timelaps-raw.mp4 -vf "scale=720:-1, crop=in_w:480" videos/timelaps-480p.mp4
  ffmpeg -y -i videos/timelaps-raw.mp4 -vf "scale=640:-1, crop=in_w:340" videos/timelaps-360p.mp4
  ffmpeg -y -i videos/timelaps-raw.mp4 -vf "scale=360:-1, crop=in_w:240" videos/timelaps-240p.mp4
}

function exportData {
  echo "metadata export"
  pf=$1
  vf=$2
  f=0

  echo -e "{" > metadata/frames.json
  echo -e '\t"frames":[' >> metadata/frames.json
  for pict in pictures/*.jpg; do
    # TIME
    # time="${pict/pictures\/hehe-/}"
    # time="${time/.jpg/}"
    time=`exiftool 2>/dev/null -S --DateTimeOriginal -p '$DateTimeOriginal' -d %Y/%m/%d-%T "$pict"`
    # GPS
    gps=`exiftool 2>/dev/null -n -p '$GPSLatitude,$GPSLongitude' $pict`

    # FRAME
    frame=$(((60/$vf)*$f))
    echo -e "\t\t{\"pict\":\"$pict\", \"time\":\"$time\", \"gps\":\"$gps\", \"frame\":\"$frame\"}," >> metadata/frames.json
    f=$(($f+1))
  done

  echo -e "\t]" >> metadata/frames.json
  echo -e "}" >> metadata/frames.json

}


function convert {
  now=$(date +"%Y-%m-%d--%T")
  echo "Timelaps conversion | $now"

  pictframerate=12
  videoframerate=24

  echo "pictframerate:$pictframerate, videoframerate=$videoframerate"

  convertVideo $pictframerate $videoframerate
  exportData $pictframerate $videoframerate
}



day=$(date +"%Y-%m-%d")
logfile="logs/convert-$day.log"
touch $logfile
convert | tee -a $logfile
