summaryrefslogtreecommitdiff
path: root/localvideowebencode
blob: bb383aa852c3df81cf8a2fdffeb45996d06d09d8 (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 pixels, modulus 16, max. 480 width (qvga vga 480p 720p).
  99. * Try lower --ref-bpp while visually acceptable, or raise to max. 0.2.
  100. * Expand and compress noisy speech with ladspa.1075 and ladspa.1916.
  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://theproaudiofiles.com/mixing-vocals-dynamics-compression-limiting>
  107. <http://www.internetmarketingnotes.com/2010/07/free-embeddable-flash-video-flv-players-for-commercial-use/>
  108. EOF
  109. }
  110. exit1() {
  111. response="${1:+Error: }${1:-Internal error!}"
  112. echo >&2 "$response"
  113. exit 1
  114. }
  115. # defaults
  116. formats=webm,vp9,mp4
  117. samplestart=0
  118. samplelength=150
  119. bitrate_variable=yes
  120. # parse cmdline options
  121. 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."
  122. eval set -- "$TEMP"
  123. while true ; do
  124. case "$1" in
  125. -h|--help) showhelp; exit;;
  126. -p|--profile) profile="$2"; shift 2;;
  127. -s|--size) size="$2"; shift 2;;
  128. -a|--aspect) aspect="$2"; shift 2;;
  129. -r|--rate) framerate="$2"; shift 2;;
  130. --video) video="$2"; shift 2;;
  131. --refbpp) refbpp="$2"; shift 2;;
  132. -b|--bitrate) bitrate="$2"; bitrate_fixed=yes; bitrate_variable=; shift 2;;
  133. --formats) formats="$2"; shift 2;;
  134. --audio) audio="$2"; shift 2;;
  135. --audioprefilter) audioprefilters="${audioprefilters:+$audioprefilters }-filter $2"; shift 2;;
  136. --loudness) loudness=yes; shift;;
  137. --loudness-data) loudness=yes; loudness_data="$2"; shift 2;;
  138. --filter) filters="${filters:+$filters }-filter $2"; shift 2;;
  139. --stem) stem="$2"; shift 2;;
  140. -t|--title) title="$2"; shift 2;;
  141. --sample) sample=yes; shift;;
  142. --sample-start) sample=yes; samplestart="$2"; shift 2;;
  143. --sample-length) sample=yes; samplelength="$2"; shift 2;;
  144. --) shift; break;;
  145. *) exit1 "Internal error resolving options.";;
  146. esac
  147. done
  148. # Resolve if melt is version 0.9.2 or newer
  149. melt_recent=$(melt -query filter=loudness | grep -qi R128 && echo yes)
  150. # sanitize infiles
  151. infiles=$*
  152. infile_first=$(perl -e 'print pop @ARGV' $infiles)
  153. [ -e "$infile_first" ] || exit1 "Cannot read first input file \"$infile_first\"!"
  154. # resolve stem and title (if not explicitly set)
  155. stem=${stem:-$(basename "$infile_first" | perl -pe 's/\.[^.]*//')}
  156. title=${title:-$stem}
  157. # parse/resolve size and framerate
  158. case "$profile" in
  159. '') :;;
  160. *@*)
  161. while read s r foo; do
  162. profilesize="${size:-$s}"
  163. framerate="${framerate:-$r}"
  164. done << EOF
  165. $(echo "$profile" | perl -F@ -anE 'say join " ", @F')
  166. EOF
  167. ;;
  168. *p*)
  169. while read s r foo; do
  170. profilesize="${size:-${s}p}"
  171. framerate="${framerate:-$r}"
  172. done << EOF
  173. $(echo "$profile" | perl -Fp -anE 'say join " ", @F')
  174. EOF
  175. ;;
  176. *)
  177. profilesize="$profile"
  178. ;;
  179. esac
  180. size=${size:-$profilesize}
  181. case "$size" in
  182. qvga) size=320x240;;
  183. hvga) size=480x360;;
  184. vga) size=640x480;;
  185. svga) size=800x600;;
  186. xga) size=1024x768;;
  187. 240p|wqvga) size=424x240;;
  188. 360p|nhd) size=640x360;;
  189. 480p|wvga) size=848x480;;
  190. 576p|wsvga) size=1024x576;;
  191. 720p|wxga|hd) size=1280x720;;
  192. esac
  193. if [ -n "$size" ]; then
  194. while read w h foo; do
  195. width="${width:-$w}"
  196. height="${height:-$h}"
  197. done << EOF
  198. $(echo "$size" | perl -Fx -anE 'say join " ", @F')
  199. EOF
  200. if [ -z "$width" ] || [ -z "$height" ]; then
  201. exit1 "Failed to parse size \"$size\"."
  202. fi
  203. fi
  204. case "$framerate" in
  205. */*)
  206. while read d n foo; do
  207. framerate_den="${framerate_den:-$d}"
  208. framerate_num="${framerate_num:-$n}"
  209. done << EOF
  210. $(echo "$framerate" | perl -Fx -anE 'say join " ", @F')
  211. EOF
  212. ;;
  213. ?*)
  214. framerate_den=1
  215. framerate_num="$framerate"
  216. ;;
  217. esac
  218. # resolve input size and framerate (needed for computing bitrate)
  219. while read w h r foo; do
  220. width_in="${width_in:-$w}"
  221. height_in="${height_in:-$h}"
  222. framerate_in="${framerate_in:-$r}"
  223. done << EOF
  224. $(mediainfo --Inform="Video;%Width% %Height% %FrameRate%" "$infile_first")
  225. EOF
  226. case "$video" in
  227. talkinghead)
  228. refbpp="${refbpp:-0.1}"
  229. x264tune=film
  230. ;;
  231. action)
  232. refbpp="${refbpp:-0.15}"
  233. x264tune=film
  234. ;;
  235. '')
  236. refbpp="${refbpp:-0.12}"
  237. ;;
  238. *) exit1 "Unknown video style \"$video\".";;
  239. esac
  240. for format in $(echo "$formats" | sed -e 's/,/ /g'); do
  241. case $format in
  242. theora|ogg) ogg=yes;;
  243. h264|mp4) mp4=yes;;
  244. vp8|webm) webm=yes;;
  245. vp9) vp9=yes;;
  246. *) exit1 "Unknown format \"$format\".";;
  247. esac
  248. done
  249. _width="${width:-$width_in}"
  250. _height="${height:-$height_in}"
  251. if [ -n "$_width" ] && [ -n "$_height" ]; then
  252. _pixels="$(($_width*$_height))"
  253. fi
  254. _frames="${framerate:-$framerate_in}"
  255. webmpreset=360p
  256. if [ -n "$_pixels" ] && [ $_pixels -ge $((1024*768)) ]; then
  257. webmpreset=720p
  258. if [ -n "$_frames" ] && [ $_frames -gt 40 ]; then
  259. webmpreset=720p50_60
  260. fi
  261. fi
  262. # compute average bitrate from reference data and "power of .75" rule
  263. bitrate_vp9="$bitrate"
  264. if [ -z "$bitrate" ] && [ -n "$_pixels" ] && [ -n "$_frames" ]; then
  265. bitrate=$(perl -E '$refsize=640*360;' \
  266. -E "say int( +(($_pixels/\$refsize)**0.75*\$refsize*$_frames*$refbpp) )")
  267. bitrate_vp9=$(perl -E "say int( $bitrate/2 )") #"
  268. fi
  269. # default per-codec-channel bitrates
  270. bitrate_vorbis=64
  271. bitrate_opus=64
  272. bitrate_aac=96
  273. channels=-1
  274. maxchannels=2
  275. case "$audio" in
  276. music)
  277. opusapp=audio
  278. ;;
  279. hqspeech)
  280. channels=1
  281. bitrate_vorbis=48
  282. bitrate_opus=32
  283. bitrate_aac=64
  284. opusapp=voip
  285. ;;
  286. speech)
  287. channels=1
  288. bitrate_vorbis=48
  289. bitrate_opus=32
  290. bitrate_aac=64
  291. compress=yes
  292. [ -z "$melt_recent" ] || _melt_loudness="$loudness_data"
  293. limit=yes
  294. opusapp=voip
  295. ;;
  296. silence)
  297. channels=0
  298. ;;
  299. '')
  300. :
  301. ;;
  302. *) exit1 "Unknown audio style \"$audio\".";;
  303. esac
  304. [ $channels -ge 0 ] || channels=$(avprobe -v warning -show_streams "$infile_first" | perl -ne 's/channels=// and print $_' || echo -1)
  305. [ $channels -le $maxchannels ] || channels=$maxchannels
  306. [ $channels -gt 0 ] || channels=
  307. melt="melt -progress"
  308. _melt_sample="$infile_first ${sample:+in=${samplestart:-0} out=$((${samplestart:-0} + samplelength))}"
  309. _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}"
  310. _melt_ogg="$_melt_video f=ogg vcodec=libtheora${bitrate:+ vb=$bitrate}${bitrate_variable:+ qscale=5}"
  311. _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}"
  312. _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"
  313. _melt_img="$_melt_video f=image2"
  314. # CRF ignored with libvpx 1.3
  315. _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"
  316. _melt_audio="${channels:+ac=$channels}"
  317. # limit (i.e. avoid peaks "clipping")
  318. _melt_postfilters_audio="${limit:+-filter ladspa.1077}"
  319. _melt_vorbis="$_melt_audio acodec=libvorbis${channels:+ ab=$(($channels*$bitrate_vorbis))k}"
  320. _melt_opus="$_melt_audio acodec=libopus${channels:+ ab=$(($channels*$bitrate_opus))k}${bitrate_fixed:+ vbr=constrained}${opusapp:+ application=$opusapp}"
  321. _melt_aac="$_melt_audio acodec=aac${channels:+ ab=$(($channels*$bitrate_aac))k}"
  322. avconv="avconv -threads auto -y -v warning"
  323. _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"
  324. _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"
  325. # resolve EBU R128 audio normalizing
  326. if [ -n "$loudness" ] && [ -z "$_melt_loudness" ]; then
  327. echo "Analyzing loudness data..."
  328. $melt ${_melt_sample:-$infiles} $audioprefilters -filter loudness -consumer xml:$stem.xml $_melt_audio video_off=1 all=1
  329. _melt_loudness="$(perl -ne 'm!<property name="results">([^<]+)</property>! and print $1' $stem.xml)"
  330. echo "Loudness data: $_melt_loudness"
  331. fi
  332. if [ -n "$mp4" ] && [ -n "$bitrate_fixed" ]; then
  333. echo "Analyzing complexity for MPEG-4..."
  334. $melt ${_melt_sample:-$infiles} $filters \
  335. -consumer avformat:/dev/null pass=1 fastfirstpass=1 an=1 audio_off=1 $_melt_h264
  336. fi
  337. if [ -n "$webm$vp9" ]; then
  338. echo "Analyzing complexity for WebM..."
  339. $melt ${_melt_sample:-$infiles} $filters \
  340. -consumer avformat:pipe:1 $_melt_video f=yuv4mpegpipe pix_fmt=yuv420p an=1 audio_off=1 \
  341. | $avconv -i pipe:0 \
  342. ${webm:+-f rawvideo $_avconv_vp8 -an -pass 1 -passlogfile ${stem}_vp8 /dev/null} \
  343. ${vp9:+-f rawvideo $_avconv_vp9 -an -pass 1 -passlogfile ${stem}_vp9 /dev/null}
  344. [ -z "$webm" ] || mv -f ${stem}_vp8-*.log ${stem}_vp8_2pass.log
  345. [ -z "$vp9" ] || mv -f ${stem}_vp9-*.log ${stem}_vp9_2pass.log
  346. fi
  347. echo "Encoding video..."
  348. $melt ${_melt_sample:-$infiles} \
  349. ${channels:+$audioprefilters${_melt_loudness:+ -filter loudness results="$_melt_loudness"}} \
  350. $filters${channels:+ $_melt_postfilters_audio} \
  351. ${ogg:+-consumer avformat:$stem.ogv $_melt_ogg $_melt_vorbis} \
  352. ${mp4:+-consumer avformat:$stem.mp4${bitrate_fixed:+ pass=2} $_melt_h264 $_melt_aac} \
  353. ${webm:+-consumer avformat:$stem.webm $_melt_webm pass=2 passlogfile=${stem}_vp8 $_melt_vorbis} \
  354. ${vp9:+-consumer avformat:${stem}_vp9.webm pass=2 passlogfile=${stem}_vp9 $_melt_vp9 $_melt_opus}
  355. if [ -n "$mp4" ] && [ -z "$melt_recent" ]; then
  356. mv "$stem.mp4" "$stem.mp4"~
  357. qt-faststart "$stem.mp4"~ "$stem.mp4"
  358. [ -f "$stem.mp4" ] && rm "$stem.mp4"~ || mv -f "$stem.mp4"~ "$stem.mp4"
  359. fi
  360. # cleanup audio normalize hinting
  361. rm -f $stem.xml
  362. # JPEG preview
  363. $melt $infile_first in=0 out=0 \
  364. -group $filters \
  365. -consumer avformat:$stem.jpg $_melt_img
  366. __width="${_width:+ width=\"$_width\"}"
  367. __height="${_height:+ height=\"$_height\"}"
  368. # Flash object needs extra space for controllers
  369. __heightplus=${_height:+ height=\"$(($_height+4))\"}
  370. _source_ogg="<source src=\"$stem.ogv\" type=\"video/ogg\" />"
  371. _source_webm="<source src=\"$stem.webm\" type=\"video/webm\" />"
  372. _source_vp9="<source src=\"${stem}_vp9.webm\" type='video/ogg; codecs=\"vp9, opus\"' />"
  373. _source_mp4="<source src=\"$stem.mp4\" type=\"video/mp4\" />"
  374. [ -z "$flashplayer" ] || flash=yes
  375. [ -n "$mp4" ] || [ -z "$flash" ] || error1 "Cannot enable flash when mp4 format is disabled."
  376. _object_flash="<object$__width$__heightplus type=\"application/x-shockwave-flash\" data=\"$flashplayer.swf\">"
  377. _param_name="<param name=\"movie\" value=\"$flashplayer.swf\" />"
  378. _param_flashvars="<param name=\"flashvars\" value=\"image=$stem.jpg&amp;file=$stem.mp4\" />"
  379. __oggfile=${ogg:+open format <a href=\"$stem.ogv\">Ogg</a>}
  380. __webmfile=${webm:+open format <a href=\"$stem.webm\">WebM (VP8)</a>}
  381. __vp9file=${vp9:+open format <a href=\"${stem}_vp9.webm\">WebM (VP9/Opus)</a>}
  382. __mp4file=${mp4:+closed format <a href=\"$stem.mp4\">MPEG-4</a>}
  383. cat >"$stem.html" <<EOF
  384. <!-- Video for Everybody, Kroc Camen of Camen Design -->
  385. <video$__width$__height preload controls>
  386. ${mp4:+$_source_mp4
  387. }${vp9:+$_source_vp9
  388. }${webm:+$_source_webm
  389. }${ogg:+$_source_ogg
  390. }${flash:+$_object_flash
  391. $_param_name
  392. $_param_flashvars
  393. }<img src="$stem.jpg"$__width$__height alt="$title"
  394. title="No video playback capabilities, please download the video below" />
  395. ${flash:+</object>
  396. }</video>
  397. <p><strong>Download Video:</strong><ul>
  398. ${vp9:+<li>$__vp9file
  399. }${webm:+<li>$__webmfile
  400. }${ogg:+<li>$__oggfile
  401. }${mp4:+<li>$__mp4file
  402. }</ul></p>
  403. EOF