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