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