summaryrefslogtreecommitdiff
path: root/localvideowebencode
blob: 51e665b77c1587dd596fa7cb2dfbe913adc258ea (plain)
  1. #!/bin/sh
  2. # Copyright © 2010-2014 Jonas Smedegaard <dr@jones.dk>
  3. # Description: Recode a video into web-optimized format(s)
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 3, or (at your option)
  8. # any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful, but
  11. # WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. # General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. #
  18. # Depends: libav-tools melt mediainfo
  19. #
  20. # TODO: offer to skip rendering again if an output file exist already
  21. # TODO: support --width and --height (resolving the other part from input/forced aspect ratio)
  22. set -e
  23. PRG=$(basename "$0")
  24. showhelp() {
  25. cat <<EOF
  26. Usage: $PRG [OPTION...] [--] [ARG=VALUE...] INPUTFILE... [ARG=VALUE...]
  27. Encode video file in multiple web-optimized formats, and provide sample
  28. html favoring open formats with optional non-JavaScript Flash fallback.
  29. --video Video style:
  30. ref-bpp
  31. talkinghead 0.1
  32. action 0.15
  33. (default: none)
  34. -p, --profile Video format - size with optional rate suffix,
  35. delimited by @ (except for widescreen labels):
  36. e.g. 848x480@25 480p25 wvga@25
  37. (default: none)
  38. -s, --size: Video frame size:
  39. [modulus 16]
  40. 320x240 qvga
  41. 640x480 vga 480p 848x480 wvga
  42. 576p 1024x576 wsvga
  43. 1024x768 xga hd 720p 1280x720 wxga
  44. [modulus 8]
  45. 240p 424x240 wqvga
  46. 480x360 hvga nhd 360p 640x360
  47. 800x600 svga
  48. (default: use input size)
  49. -a, --aspect Display Aspect Ratio in melt format e.g. @16/9
  50. (default: no aspect hinting)
  51. -r, --rate Video framerate - integer or fraction:
  52. e.g. 15 1001/24000 25 1001/30000
  53. (default: use input framerate)
  54. --refbpp Reference bits-per-pixel (relative to 360p30),
  55. for computing average bitrate when not fixed.
  56. (default: 0.12)
  57. -b, --bitrate Fixed video bitrate in bytes: e.g. 768k 1M
  58. (default: none - use variable bitrate)
  59. --formats Containers and codecs to use (comma-sparated):
  60. container video codec audio codec
  61. ogg Ogg Theora Vorbis
  62. webm WebM VP8 Vorbis
  63. vp9 WebM VP9 Opus
  64. mp4 MPEG-4 H.264 AAC
  65. (default: webm,vp9,mp4)
  66. --audio Audio style:
  67. channels limit Vorbis Opus AAC
  68. music max 2 64k 64k audio 96k
  69. hqspeech 1 48k 32k voip 64k
  70. speech 1 X 48k 32k voip 64k
  71. silence 0
  72. (default: none - use channel count of 1st input)
  73. --audioprefilter Add melt audio filter before loudness.
  74. --loudness Add EBU R128 loudness filter.
  75. --loudness-results Add EBU R128 loudness filter, applying
  76. precomputed analysis results.
  77. (default: none - compute results on-the-fly)
  78. --filter Add melt filter (applied to all input files)
  79. --stem Stem of output filenames, optionally with path
  80. (default: basename of last input file)
  81. -t, --title Title used in html fallback graphics
  82. (default: stem)
  83. --sample Create only a 150 frames long sample.
  84. --sample-start Create sample, starting at a specific frame.
  85. (default: start at first frame)
  86. --sample-length Create sample, of specified length in frames.
  87. (default: 150 frames - i.e. approx. 5s)
  88. -h, --help This help text
  89. Examples:
  90. $PRG -s qvga -t "Funny guy" intro.dv myvideo.dv
  91. $PRG -p 480p --stem funny --filter "grain noise=20" myvideo.dv
  92. Options before input files are passed to melt producer, and after to
  93. melt avformat consumer.
  94. Recommendations for best results:
  95. * Use square-pixel max. 480 width (vga 480p).
  96. * Use a modulus 16 profile (qvga vga 480p 720p).
  97. * Adjust --video or --ref-bpp until visual unacceptable.
  98. More info:
  99. <http://camendesign.com/code/video_for_everybody>
  100. <http://www.streaminglearningcenter.com/articles/configuring-your-streaming-video-(for-newbies).html>
  101. <http://en.wikipedia.org/wiki/HTML5_video>
  102. <http://www.penguinproducer.com/2012/01/ladspa-noise-removal/>
  103. <http://www.internetmarketingnotes.com/2010/07/free-embeddable-flash-video-flv-players-for-commercial-use/>
  104. EOF
  105. }
  106. exit1() {
  107. response="${1:+Error: }${1:-Internal error!}"
  108. echo >&2 "$response"
  109. exit 1
  110. }
  111. # defaults
  112. formats=webm,vp9,mp4
  113. samplestart=0
  114. samplelength=150
  115. # parse cmdline options
  116. TEMP="`getopt -s sh -o hp:s:a:r:b:t: -l help,profile:,size:,aspect:,rate:,video:,refbpp:,bitrate:,formats:,audio:,audioprefilter:,loudness,loudness-results:,filter:,stem:,title:,sample,sample-start:,sample-length: -n "$PRG" -- "$@"`" || exit1 "Internal getopt error."
  117. eval set -- "$TEMP"
  118. while true ; do
  119. case "$1" in
  120. -h|--help) showhelp; exit;;
  121. -p|--profile) profile="$2"; shift 2;;
  122. -s|--size) size="$2"; shift 2;;
  123. -a|--aspect) aspect="$2"; shift 2;;
  124. -r|--rate) framerate="$2"; shift 2;;
  125. --video) video="$2"; shift 2;;
  126. --refbpp) refbpp="$2"; shift 2;;
  127. -b|--bitrate) bitrate="$2"; bitrate_fixed=yes; shift 2;;
  128. --formats) formats="$2"; shift 2;;
  129. --audio) audio="$2"; shift 2;;
  130. --audioprefilter) audioprefilters="${audioprefilters:+$audioprefilters }-filter $2"; shift 2;;
  131. --loudness) loudness=yes; shift;;
  132. --loudness-results) loudness=yes; loudness_results="$2"; shift 2;;
  133. --filter) filters="${filters:+$filters }-filter $2"; shift 2;;
  134. --stem) stem="$2"; shift 2;;
  135. -t|--title) title="$2"; shift 2;;
  136. --sample) sample=yes; shift;;
  137. --sample-start) sample=yes; samplestart="$2"; shift 2;;
  138. --sample-length) sample=yes; samplelength="$2"; shift 2;;
  139. --) shift; break;;
  140. *) exit1 "Internal error resolving options.";;
  141. esac
  142. done
  143. # Resolve if melt is version 0.9.2 or newer
  144. # TODO: drop when melt 0.9.2 is stable
  145. melt_recent=$(melt -query filter=loudness | grep -qi R128 && echo yes)
  146. while [ $# -gt 0 ] ; do
  147. case "$1" in
  148. *=*) _melt_in="${_melt_in:+$_melt_in }$1"; shift;;
  149. *) break;;
  150. esac
  151. done
  152. while [ $# -gt 0 ] ; do
  153. case "$1" in
  154. *=*) _melt_out="${_melt_out:+$_melt_out }$1"; shift;;
  155. *) infiles="${infiles:+$infiles }$1"; shift;;
  156. esac
  157. done
  158. if [ -z "$infiles" ]; then
  159. showhelp
  160. exit1 "Too few parameters!"
  161. fi
  162. # input filename (mandatory)
  163. infile_first=$(perl -e 'print pop @ARGV' $infiles)
  164. [ -e "$infile_first" ] || exit1 "Input file missing!"
  165. # resolve stem and title (if not explicitly set)
  166. stem=${stem:-$(basename "$infile_first" | perl -pe 's/\.[^.]*//')}
  167. title=${title:-$stem}
  168. case "$profile" in
  169. *@*)
  170. while read s r foo; do
  171. size="${size:-$s}"
  172. framerate="${framerate:-$r}"
  173. done << EOF
  174. $(echo "$profile" | perl -F@ -anE 'say join " ", @F')
  175. EOF
  176. ;;
  177. *p*)
  178. while read s r foo; do
  179. size="${size:-${s}p}"
  180. framerate="${framerate:-$r}"
  181. done << EOF
  182. $(echo "$profile" | perl -Fp -anE 'say join " ", @F')
  183. EOF
  184. ;;
  185. *)
  186. size="$profile"
  187. ;;
  188. esac
  189. case "$size" in
  190. qvga) size=320x240;;
  191. hvga) size=480x360;;
  192. vga) size=640x480;;
  193. svga) size=800x600;;
  194. xga) size=1024x768;;
  195. 240p|wqvga) size=424x240;;
  196. 360p|nhd) size=640x360;;
  197. 480p|wvga) size=848x480;;
  198. 576p|wsvga) size=1024x576;;
  199. 720p|wxga|hd) size=1280x720;;
  200. esac
  201. if [ -n "$size" ]; then
  202. while read w h foo; do
  203. width="${width:-$w}"
  204. height="${height:-$h}"
  205. done << EOF
  206. $(echo "$size" | perl -Fx -anE 'say join " ", @F')
  207. EOF
  208. if [ -z "$width" ] || [ -z "$height" ]; then
  209. exit1 "Failed to parse size \"$size\"."
  210. fi
  211. fi
  212. case "$framerate" in
  213. */*)
  214. while read d n foo; do
  215. framerate_den="${framerate_den:-$d}"
  216. framerate_num="${framerate_num:-$n}"
  217. done << EOF
  218. $(echo "$framerate" | perl -Fx -anE 'say join " ", @F')
  219. EOF
  220. ;;
  221. ?*)
  222. framerate_den=1
  223. framerate_num="$framerate"
  224. ;;
  225. esac
  226. while read w h r foo; do
  227. width_in="${width_in:-$w}"
  228. height_in="${height_in:-$h}"
  229. framerate_in="${framerate_in:-$r}"
  230. done << EOF
  231. $(mediainfo --Inform="Video;%Width% %Height% %FrameRate%" "$infile_first")
  232. EOF
  233. case "$video" in
  234. talkinghead)
  235. refbpp="${refbpp:-0.1}"
  236. x264tune=film
  237. ;;
  238. action)
  239. refbpp="${refbpp:-0.15}"
  240. x264tune=film
  241. ;;
  242. '')
  243. refbpp="${refbpp:-0.12}"
  244. ;;
  245. *) exit1 "Unknown video style \"$video\".";;
  246. esac
  247. for format in $(echo "$formats" | sed -e 's/,/ /g'); do
  248. case $format in
  249. ogg) ogg=yes;;
  250. mp4) mp4=yes;;
  251. webm) webm=yes;;
  252. vp9) vp9=yes;;
  253. *) exit1 "Unknown format \"$format\".";;
  254. esac
  255. done
  256. _width="${width:-$width_in}"
  257. _height="${height:-$height_in}"
  258. if [ -n "$_width" ] && [ -n "$_height" ]; then
  259. _pixels="$(($_width*$_height))"
  260. fi
  261. _frames="${framerate:-$framerate_in}"
  262. webmpreset=360p
  263. if [ -n "$_pixels" ] && [ $_pixels -ge $((1024*768)) ]; then
  264. webmpreset=720p
  265. if [ -n "$_frames" ] && [ $_frames -gt 40 ]; then
  266. webmpreset=720p50_60
  267. fi
  268. fi
  269. # compute average bitrate from reference data and "power of .75" rule
  270. bitrate_vp9="$bitrate"
  271. if [ -z "$bitrate" ] && [ -n "$_pixels" ] && [ -n "$_frames" ]; then
  272. bitrate=$(perl -E '$refsize=640*360;' \
  273. -E "say int( +(($_pixels/\$refsize)**0.75*\$refsize*$_frames*$refbpp) )")
  274. bitrate_vp9=$(perl -E "say int( $bitrate/2 )") #"
  275. fi
  276. # default per-codec-channel bitrates
  277. bitrate_vorbis=64
  278. bitrate_opus=64
  279. bitrate_aac=96
  280. channels=-1
  281. maxchannels=2
  282. case "$audio" in
  283. music)
  284. opusapp=audio
  285. ;;
  286. hqspeech)
  287. channels=1
  288. bitrate_vorbis=48
  289. bitrate_opus=32
  290. bitrate_aac=64
  291. opusapp=voip
  292. ;;
  293. speech)
  294. channels=1
  295. bitrate_vorbis=48
  296. bitrate_opus=32
  297. bitrate_aac=64
  298. compress=yes
  299. [ -z "$melt_recent" ] || _melt_loudness="$loudness_results"
  300. limit=yes
  301. opusapp=voip
  302. ;;
  303. silence)
  304. channels=0
  305. ;;
  306. '')
  307. :
  308. ;;
  309. *) exit1 "Unknown audio style \"$audio\".";;
  310. esac
  311. [ $channels -ge 0 ] || channels=$(avprobe -v warning -show_streams "$infile_first" | perl -ne 's/channels=// and print $_' || echo -1)
  312. [ $channels -le $maxchannels ] || channels=$maxchannels
  313. [ $channels -gt 0 ] || channels=
  314. # TODO: Check and fail if all needed tools are not available
  315. # TODO: When verified beneficial, add option real_time=-2
  316. melt="melt -progress"
  317. _melt_in="${_melt_in:+$_melt_in }${sample:+in=${samplestart:-0} out=$((${samplestart:-0} + samplelength))}"
  318. _melt_video="progressive=1${framerate:+ frame_rate_den="$framerate_den" frame_rate_num="$framerate_num"}${size:+ s=${width:+$width}x${height:+$height}}${aspect:+ aspect=$aspect}"
  319. _melt_ogg="$_melt_video f=ogg vcodec=libtheora${bitrate:+ vb=$bitrate}${bitrate_fixed:- qscale=5}"
  320. _melt_h264="$_melt_video f=mp4 vcodec=libx264 vpre=medium vprofile=baseline${x264tune:+ tune=$x264tune}${bitrate_fixed:+ vb=$bitrate} threads=0 movflags=+faststart${bitrate_fixed:- crf=23}"
  321. _melt_webm="$_melt_video f=webm vcodec=libvpx vpre=libvpx-$webmpreset${bitrate:+ vb=$bitrate}${bitrate_fixed:+ minrate=$bitrate maxrate=$bitrate}{bitrate_fixed:- crf=10} cpu-used=3"
  322. _melt_img="$_melt_video f=image2"
  323. # CRF ignored with libvpx 1.3
  324. _melt_vp9="$_melt_video f=webm vcodec=libvpx-vp9 vpre=libvpx-$webmpreset${bitrate_vp9:+ vb=$bitrate_vp9}${bitrate_fixed:+ minrate=$bitrate_vp9 maxrate=$bitrate_vp9}${bitrate_fixed:- crf=10} cpu-used=5"
  325. _melt_audio="${channels:+ac=$channels}"
  326. # limit (i.e. avoid peaks "clipping")
  327. _melt_postfilters_audio="${limit:+-filter ladspa.1077}"
  328. _melt_vorbis="$_melt_audio acodec=libvorbis${channels:+ ab=$(($channels*$bitrate_vorbis))k}"
  329. _melt_opus="$_melt_audio acodec=libopus${channels:+ ab=$(($channels*$bitrate_opus))k}${bitrate_fixed:+ vbr=constrained}${opusapp:+ application=$opusapp}"
  330. _melt_aac="$_melt_audio acodec=aac${channels:+ ab=$(($channels*$bitrate_aac))k}"
  331. avconv="avconv -threads auto -y -v warning"
  332. _avconv_vp8="-c:v libvpx -pre:v libvpx-$webmpreset${bitrate:+ -b:v $bitrate}${bitrate_fixed:+ -minrate $bitrate -maxrate $bitrate}${bitrate_fixed:- -crf 10} -cpu-used 3"
  333. _avconv_vp9="-c:v libvpx-vp9 -pre:v libvpx-$webmpreset${bitrate_vp9:+ -b:v $bitrate_vp9}${bitrate_fixed:+ -minrate $bitrate_vp9 -maxrate $bitrate_vp9}${bitrate_fixed:- -crf 10} -cpu-used 5"
  334. # resolve EBU R128 audio normalizing
  335. # TODO: normalize each infile separately when xml fed as infile keeps sync
  336. if [ -n "$loudness" ] && [ -z "$_melt_loudness" ]; then
  337. $melt -group $_melt_in $infiles -group $audioprefilters -filter loudness -consumer xml:$stem.xml $_melt_audio video_off=1 all=1
  338. _melt_loudness="$(perl -ne 'm!<property name="results">([^<]+)</property>! and print $1' $stem.xml)"
  339. fi
  340. if [ -n "$mp4" ] && [ -n "$bitrate_fixed" ]; then
  341. $melt -group $_melt_in $infiles -group $filters \
  342. -consumer avformat:/dev/null pass=1 fastfirstpass=1 an=1 audio_off=1 $_melt_h264 $_melt_out
  343. fi
  344. if [ -n "$webm$vp9" ]; then
  345. $melt -group $_melt_in $infiles -group $filters \
  346. -consumer avformat:pipe:1 $_melt_video f=yuv4mpegpipe pix_fmt=yuv420p \
  347. | $avconv -i pipe:0 \
  348. ${webm:+-f rawvideo $_avconv_vp8 -an -pass 1 -passlogfile ${stem}_vp8 /dev/null} \
  349. ${vp9:+-f rawvideo $_avconv_vp9 -an -pass 1 -passlogfile ${stem}_vp9 /dev/null}
  350. [ -z "$webm" ] || mv -f ${stem}_vp8-*.log ${stem}_vp8_2pass.log
  351. [ -z "$vp9" ] || mv -f ${stem}_vp9-*.log ${stem}_vp9_2pass.log
  352. fi
  353. $melt -group $_melt_in $infiles \
  354. -group ${channels:+$audioprefilters${_melt_loudness:+ -filter loudness results="$_melt_loudness"}} \
  355. $filters${channels:+ $_melt_postfilters_audio} \
  356. ${ogg:+-consumer avformat:$stem.ogv $_melt_ogg $_melt_vorbis $_melt_out} \
  357. ${mp4:+-consumer avformat:$stem.mp4${bitrate_fixed:+ pass=2} $_melt_h264 $_melt_aac $_melt_out} \
  358. ${webm:+-consumer avformat:$stem.webm $_melt_webm$ pass=2 passlogfile=${stem}_vp8 $_melt_vorbis $_melt_out} \
  359. ${vp9:+-consumer avformat:${stem}_vp9.webm pass=2 passlogfile=${stem}_vp9 $_melt_vp9 $_melt_opus $_melt_out}
  360. if [ -n "$mp4" ] && [ -z "$melt_recent" ]; then
  361. mv "$stem.mp4" "$stem.mp4"~
  362. qt-faststart "$stem.mp4"~ "$stem.mp4"
  363. [ -f "$stem.mp4" ] && rm "$stem.mp4"~ || mv -f "$stem.mp4"~ "$stem.mp4"
  364. fi
  365. # cleanup audio normalize hinting
  366. rm -f $stem.xml
  367. ## JPEG preview
  368. $melt -group in=0 out=0 $infiles \
  369. -group $filters \
  370. -consumer avformat:$stem.jpg $_melt_img $_melt_out
  371. __width="${_width:+ width=\"$_width\"}"
  372. __height="${_height:+ height=\"$_height\"}"
  373. # Flash object needs extra space for controllers
  374. __heightplus=${_height:+ height=\"$(($_height+4))\"}
  375. _source_ogg="<source src=\"$stem.ogv\" type=\"video/ogg\" />"
  376. _source_webm="<source src=\"$stem.webm\" type=\"video/webm\" />"
  377. _source_vp9="<source src=\"${stem}_vp9.webm\" type='video/ogg; codecs=\"vp9, opus\"' />"
  378. _source_mp4="<source src=\"$stem.mp4\" type=\"video/mp4\" />"
  379. # TODO: resolve flash player to use
  380. [ -z "$flashplayer" ] || flash=yes
  381. [ -n "$mp4" ] || [ -z "$flash" ] || error1 "Cannot enable flash when mp4 format is disabled."
  382. _object_flash="<object$__width$__heightplus type=\"application/x-shockwave-flash\" data=\"$flashplayer.swf\">"
  383. _param_name="<param name=\"movie\" value=\"$flashplayer.swf\" />"
  384. _param_flashvars="<param name=\"flashvars\" value=\"image=$stem.jpg&amp;file=$stem.mp4\" />"
  385. __oggfile=${ogg:+open format <a href=\"$stem.ogv\">Ogg</a>}
  386. __webmfile=${webm:+open format <a href=\"$stem.webm\">WebM (VP8)</a>}
  387. __vp9file=${vp9:+open format <a href=\"${stem}_vp9.webm\">WebM (VP9/Opus)</a>}
  388. __mp4file=${mp4:+closed format <a href=\"$stem.mp4\">MPEG-4</a>}
  389. cat >"$stem.html" <<EOF
  390. <!-- Video for Everybody, Kroc Camen of Camen Design -->
  391. <video$__width$__height preload controls>
  392. ${mp4:+$_source_mp4
  393. }${vp9:+$_source_vp9
  394. }${webm:+$_source_webm
  395. }${ogg:+$_source_ogg
  396. }${flash:+$_object_flash
  397. $_param_name
  398. $_param_flashvars
  399. }<img src="$stem.jpg"$__width$__height alt="$title"
  400. title="No video playback capabilities, please download the video below" />
  401. ${flash:+</object>
  402. }</video>
  403. <p><strong>Download Video:</strong><ul>
  404. ${vp9:+<li>$__vp9file
  405. }${webm:+<li>$__webmfile
  406. }${ogg:+<li>$__oggfile
  407. }${mp4:+<li>$__mp4file
  408. }</ul></p>
  409. EOF