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