Wednesday, December 16, 2015

Create Animated CSS HTML from Video!

#!/usr/bin/env bash
####################################################################
### Copyrighted by +AMD / Adam Michael Danischewski 2015+ 
### Free for all non-commercial uses, provided this notice remain intact.  
### File: video2css.bsh  Version: v.1.0 
### This script converts a video clip into a CSS animation! =) 
### 
### Make a sandbox directory for the video and its files, then cd to it 
### and run this script with a valid YOUTUBE url as an argument. 
### 
### Requires: avconv, youtube-dl, jp2a, firefox (if you want it to auto 
###           preview w/out failing). 
### Have fun hacking! =)  
#####################################################################

(($#<1)) || [[ "${1}" =~ ^- ]] && echo "Usage: ${0##*/} <\"http://youtube url\"|\"local video file\"> <frames> <step>" && exit 0 

declare    YOUTUBE_URL="${1}"
declare    VIDEO_FILENAME="${1}"
declare -i CSSMOVIE_MAXFRAMES=${2:-320} ## Limit on how many converted frames, its only a preview.
declare -i CSSMOVIE_STEPFRAMES=${3:-5} ## Skip every 5 frames, sensible on my mach. 
declare    CSSMOVIE_STARTTIME="" 
declare    CSSMOVIE_PATHPREFIX=""
declare    CSSMOVIE_HTML="" 
declare -i EXTRACT_DURATION=40 
declare    VIDEO_JPEG_SIZE="200x100"
declare    EXTRACT_STARTTIME="00:00:01.00"

function get_video() { 
 if [[ "${YOUTUBE_URL}" =~ ^http ]]; then 
  VIDEO_FILENAME=$(youtube-dl --get-filename "${YOUTUBE_URL}" 2>/dev/random)
  youtube-dl -f best --no-cache-dir "${YOUTUBE_URL}"
 fi  
 CSSMOVIE_PATHPREFIX="${VIDEO_FILENAME%.*}"
 CSSMOVIE_HTML="${CSSMOVIE_PATHPREFIX}.html" 
} 

function extract_jpegs() { 
 avconv -i "${VIDEO_FILENAME}" -s "${VIDEO_JPEG_SIZE}" -t ${EXTRACT_DURATION} -ss "${EXTRACT_STARTTIME}" "${CSSMOVIE_PATHPREFIX}-%d.jpeg"
} 

function jpeg2css() { 
 local outname=""; 
 for a in "${CSSMOVIE_PATHPREFIX}"*.jpeg; do 
  outname="${a%%.*}" 
  outname="${outname}.html" 
  jp2a --colors --chars="  " --fill --html-fontsize=4 --html-raw "$a" > "${outname}" 
 done 
} 

function print_html_array() { 
 local -i i=1;
 local fcontents=""; 
 while ((${i} < ${CSSMOVIE_MAXFRAMES})); do 
  fcontents=$(< "${CSSMOVIE_PATHPREFIX}-${i}.html")
  echo "imgArr.push(\"${fcontents}\");"
  i+=${CSSMOVIE_STEPFRAMES}
 done
}

function print_html_file() { 
cat<<EOF 
<html>
<body>
<div id="cssMovie"></div>
<script>
var imgArr = new Array($((${CSSMOVIE_MAXFRAMES}/${CSSMOVIE_STEPFRAMES}))); 
EOF
print_html_array
cat <<EOF 
var loopTimer;
function frameLooper() {
 if(imgArr.length > 0) {
  document.getElementById("cssMovie").innerHTML = imgArr.shift(); 
 } else {
  clearTimeout(loopTimer); 
    return false;
 }
 loopTimer = setTimeout('frameLooper()',10);
}
frameLooper();
</script>
</body>
</html>
EOF
}

get_video
extract_jpegs
jpeg2css
print_html_file > "${CSSMOVIE_HTML}" 
firefox "${CSSMOVIE_HTML}"
exit 0 

No comments:

Post a Comment