summaryrefslogtreecommitdiff
path: root/localvideowebencode
blob: 26a808ba8456bca1cb1667a72e6634426e7fbda3 (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 ffmpegthumbnailer
  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. mp4 MPEG-4 H.264 AAC
  64. (default: webm,mp4)
  65. --h264profile MPEG-4 AVC target profile: baseline main high
  66. (default: baseline)
  67. --h264preset MPEG-4 AVC target preset: slow ultrafast etc.
  68. (default: medium)
  69. --webmpreset WebM target preset: 360p 720p 720p50_60 etc.
  70. (default: profile-related or 360p)
  71. --audio Audio style:
  72. channels limit
  73. music max 2
  74. hqspeech 1
  75. speech 1 X
  76. silence 0
  77. (default: none - use input channel count)
  78. --audioprefilter Add melt audio filter before loudness.
  79. --loudness Add EBU R128 loudness filter.
  80. --loudness-results Add EBU R128 loudness filter, applying
  81. precomputed analysis results.
  82. (default: none - compute results on-the-fly)
  83. --filter Add melt filter (applied to all input files)
  84. --stem Stem of output filenames, optionally with path
  85. (default: basename of last input file)
  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 480p --stem funny --filter "grain noise=20" myvideo.dv
  97. Options before input files are passed to melt producer, and after to
  98. melt avformat consumer.
  99. Hints:
  100. * Use square-pixel max. 480 width (vga 480p) for widest compatibility.
  101. * Use a modulus 16 profile (qvga vga 480p 720p) for best compression.
  102. * Try lower reference bits-per-pixel until visual quality is affected.
  103. * Raise reference bits-per-pixel if needed, but no higher than 0.2.
  104. (you can inspect actual bits-per-pixel and bitrate with mediainfo)
  105. More info:
  106. <http://camendesign.com/code/video_for_everybody>
  107. <http://www.streaminglearningcenter.com/articles/configuring-your-streaming-video-(for-newbies).html>
  108. <http://en.wikipedia.org/wiki/HTML5_video>
  109. <http://www.penguinproducer.com/2012/01/ladspa-noise-removal/>
  110. <http://www.internetmarketingnotes.com/2010/07/free-embeddable-flash-video-flv-players-for-commercial-use/>
  111. EOF
  112. }
  113. exit1() {
  114. response="${1:+Error: }${1:-Internal error!}"
  115. echo >&2 "$response"
  116. exit 1
  117. }
  118. # defaults
  119. formats=webm,mp4
  120. h264profile=baseline
  121. samplestart=0
  122. samplelength=150
  123. # parse cmdline options
  124. TEMP="`getopt -s sh -o hp:s:a:r:b:t: -l help,profile:,size:,aspect:,rate:,video:,refbpp:,bitrate:,formats:,h264profile:,h264preset:,webmpreset:,audio:,audioprefilter:,loudness,loudness-results:,filter:,stem:,title:,sample,sample-start:,sample-length: -n "$PRG" -- "$@"`" || exit1 "Internal getopt error."
  125. eval set -- "$TEMP"
  126. while true ; do
  127. case "$1" in
  128. -h|--help) showhelp; exit;;
  129. -p|--profile) profile="$2"; shift 2;;
  130. -s|--size) size="$2"; shift 2;;
  131. -a|--aspect) aspect="$2"; shift 2;;
  132. -r|--rate) framerate="$2"; shift 2;;
  133. --video) video="$2"; shift 2;;
  134. --refbpp) refbpp="$2"; shift 2;;
  135. -b|--bitrate) bitrate="$2"; bitrate_fixed=yes; shift 2;;
  136. --formats) formats="$2"; shift 2;;
  137. --h264profile) h264profile="$2"; shift 2;;
  138. --h264preset) h264preset="$2"; shift 2;;
  139. --webmpreset) webmpreset="$2"; shift 2;;
  140. --audio) audio="$2"; shift 2;;
  141. --audioprefilter) audioprefilters="${audioprefilters:+$audioprefilters }-filter $2"; shift 2;;
  142. --loudness) loudness=yes; shift;;
  143. --loudness-results) loudness=yes; loudness_results="$2"; shift 2;;
  144. --filter) filters="${filters:+$filters }-filter $2"; shift 2;;
  145. --stem) stem="$2"; shift 2;;
  146. -t|--title) title="$2"; shift 2;;
  147. --sample) sample=yes; shift;;
  148. --sample-start) sample=yes; samplestart="$2"; shift 2;;
  149. --sample-length) sample=yes; samplelength="$2"; shift 2;;
  150. --) shift; break;;
  151. *) exit1 "Internal error resolving options.";;
  152. esac
  153. done
  154. # Resolve if melt is version 0.9.2 or newer
  155. # TODO: drop when melt 0.9.2 is stable
  156. melt_recent=$(melt -query filter=loudness | grep -qi R128 && echo yes)
  157. while [ $# -gt 0 ] ; do
  158. case "$1" in
  159. *=*) _melt_in="${_melt_in:+$_melt_in }$1"; shift;;
  160. *) break;;
  161. esac
  162. done
  163. while [ $# -gt 0 ] ; do
  164. case "$1" in
  165. *=*) _melt_out="${_melt_out:+$_melt_out }$1"; shift;;
  166. *) infiles="${infiles:+$infiles }$1"; shift;;
  167. esac
  168. done
  169. if [ -z "$infiles" ]; then
  170. showhelp
  171. exit1 "Too few parameters!"
  172. fi
  173. # input filename (mandatory)
  174. infile_first=$(perl -e 'print pop @ARGV' $infiles)
  175. [ -e "$infile_first" ] || exit1 "Input file missing!"
  176. # resolve stem and title (if not explicitly set)
  177. stem=${stem:-$(basename "$infile_first" | perl -pe 's/\.[^.]*//')}
  178. title=${title:-$stem}
  179. case "$profile" in
  180. *@*)
  181. while read s r foo; do
  182. size="${size:-$s}"
  183. framerate="${framerate:-$r}"
  184. done << EOF
  185. $(echo "$profile" | perl -F@ -anE 'say join " ", @F')
  186. EOF
  187. ;;
  188. *p*)
  189. while read s r foo; do
  190. size="${size:-${s}p}"
  191. framerate="${framerate:-$r}"
  192. done << EOF
  193. $(echo "$profile" | perl -Fp -anE 'say join " ", @F')
  194. EOF
  195. ;;
  196. *)
  197. size="$profile"
  198. ;;
  199. esac
  200. case "$size" in
  201. qvga) size=320x240;;
  202. hvga) size=480x360;;
  203. vga) size=640x480;;
  204. svga) size=800x600;;
  205. xga) size=1024x768;;
  206. 240p|wqvga) size=424x240;;
  207. 360p|nhd) size=640x360;;
  208. 480p|wvga) size=848x480;;
  209. 576p|wsvga) size=1024x576;;
  210. 720p|wxga|hd) size=1280x720;;
  211. esac
  212. if [ -n "$size" ]; then
  213. while read w h foo; do
  214. width="${width:-$w}"
  215. height="${height:-$h}"
  216. done << EOF
  217. $(echo "$size" | perl -Fx -anE 'say join " ", @F')
  218. EOF
  219. if [ -z "$width" ] || [ -z "$height" ]; then
  220. exit1 "Failed to parse size \"$size\"."
  221. fi
  222. fi
  223. case "$framerate" in
  224. */*)
  225. while read d n foo; do
  226. framerate_den="${framerate_den:-$d}"
  227. framerate_num="${framerate_num:-$n}"
  228. done << EOF
  229. $(echo "$framerate" | perl -Fx -anE 'say join " ", @F')
  230. EOF
  231. ;;
  232. ?*)
  233. framerate_den=1
  234. framerate_num="$framerate"
  235. ;;
  236. esac
  237. while read w h r foo; do
  238. width_in="${width_in:-$w}"
  239. height_in="${height_in:-$h}"
  240. framerate_in="${framerate_in:-$r}"
  241. done << EOF
  242. $(mediainfo --Inform="Video;%Width% %Height% %FrameRate%" "$infile_first")
  243. EOF
  244. case "$video" in
  245. talkinghead)
  246. refbpp="${refbpp:-0.1}"
  247. ;;
  248. action)
  249. refbpp="${refbpp:-0.15}"
  250. ;;
  251. '')
  252. refbpp="${refbpp:-0.12}"
  253. ;;
  254. *) exit1 "Unknown video style \"$video\".";;
  255. esac
  256. for format in $(echo "$formats" | sed -e 's/,/ /g'); do
  257. case $format in
  258. ogg) ogg=yes;;
  259. mp4) mp4=yes;;
  260. webm) webm=yes;;
  261. *) exit1 "Unknown format \"$format\".";;
  262. esac
  263. done
  264. case "$h264profile" in
  265. baseline|main)
  266. _melt_h264="properties=x264-medium-$h264profile ${h264preset:+-vpre=libx264-$h264preset}"
  267. ;;
  268. high)
  269. _melt_h264="properties=x264-medium ${h264preset:+-vpre=libx264-$h264preset}"
  270. ;;
  271. *) exit1 "Unknown MPEG-4 AVC profile \"$h264profile\".";;
  272. esac
  273. _width="${width:-$width_in}"
  274. _height="${height:-$height_in}"
  275. if [ -n "$_width" ] && [ -n "$_height" ]; then
  276. _pixels="$(($_width*$_height))"
  277. fi
  278. _frames="${framerate:-$framerate_in}"
  279. if [ -n "$_pixels" ] && [ $_pixels -ge $((1024*768)) ]; then
  280. webmpreset="${webmpreset:-720p}"
  281. if [ -n "$_frames" ] && [ $_frames -gt 40 ]; then
  282. webmpreset="${webmpreset:-720p50_60}"
  283. fi
  284. fi
  285. # compute average bitrate from reference data and "power of .75" rule
  286. if [ -z "$bitrate" ] && [ -n "$_pixels" ] && [ -n "$_frames" ]; then
  287. bitrate=$(perl -E '$refsize=640*360;' \
  288. -E "say int( +(($_pixels/\$refsize)**0.75*\$refsize*$_frames*$refbpp) )")
  289. fi
  290. # default per-codec-channel bitrates
  291. bitrate_vorbis=64
  292. bitrate_aac=96
  293. case "$audio" in
  294. music)
  295. channels=2
  296. ;;
  297. hqspeech)
  298. channels=1
  299. bitrate_vorbis=48
  300. bitrate_aac=64
  301. ;;
  302. speech)
  303. channels=1
  304. bitrate_vorbis=48
  305. bitrate_aac=64
  306. compress=yes
  307. [ -z "$melt_recent" ] || _melt_loudness="$loudness_results"
  308. limit=yes
  309. ;;
  310. silence)
  311. channels=0
  312. ;;
  313. '')
  314. channels=$(avprobe -v warning -show_streams "$infile_first" | perl -ne 's/channels=// and print $_')
  315. ;;
  316. *) exit1 "Unknown audio style \"$audio\".";;
  317. esac
  318. [ $channels -le 2 ] || channels=2
  319. [ $channels -gt 0 ] || channels=
  320. # TODO: Check and fail if all needed tools are not available
  321. # TODO: When verified beneficial, add option real_time=-2
  322. melt="melt -progress"
  323. _melt_in="${_melt_in:+$_melt_in }${sample:+in=${samplestart:-0} out=$((${samplestart:-0} + samplelength))}"
  324. _melt_video="progressive=1${framerate:+ frame_rate_den="$framerate_den" frame_rate_num="$framerate_num"}${bitrate:+ vb=$bitrate}${size:+ s=${width:+$width}x${height:+$height}}${aspect:+ aspect=$aspect}"
  325. _melt_ogg="$_melt_video f=ogg vcodec=libtheora${bitrate_fixed:- qscale=5}"
  326. _melt_h264="$_melt_video $_melt_h264${bitrate_fixed:- crf=23}"
  327. _melt_webm="$_melt_video vpre=libvpx-${webmpreset:-360p} qmin=0 qmax=63${bitrate_fixed:- crf=23}"
  328. _melt_audio="${channels:+ac=$channels}"
  329. # limit (i.e. avoid peaks "clipping")
  330. _melt_postfilters_audio="${limit:+-filter ladspa.1077}"
  331. _melt_vorbis="$_melt_audio acodec=libvorbis ab=$(($channels*$bitrate_vorbis))k"
  332. _melt_aac="$_melt_audio acodec=aac ab=$(($channels*$bitrate_aac))k"
  333. # resolve EBU R128 audio normalizing
  334. # TODO: normalize each infile separately when xml fed as infile keeps sync
  335. if [ -n "$loudness" ] && [ -z "$_melt_loudness" ]; then
  336. $melt -group $_melt_in $infiles -group $audioprefilters -filter loudness -consumer xml:$stem.xml $_melt_audio video_off=1 all=1
  337. _melt_loudness="$(perl -ne 'm!<property name="results">([^<]+)</property>! and print $1' $stem.xml)"
  338. fi
  339. if [ -n "$ogg" ]; then
  340. $melt -group $_melt_in $infiles -group ${channels:+$audioprefilters${_melt_loudness:+ -filter loudness results="$_melt_loudness"}} $filters${channels:+ $_melt_postfilters_audio} -consumer avformat:"$stem.ogv" $_melt_ogg $_melt_vorbis $_melt_out
  341. fi
  342. if [ -n "$mp4" ]; then
  343. [ -z "$bitrate_fixed" ] || $melt -group $_melt_in $infiles -group $filters -consumer avformat:/dev/null properties=x264-medium-pass1 $_melt_h264 $_melt_out
  344. $melt -group $_melt_in $infiles -group ${channels:+$audioprefilters${_melt_loudness:+ -filter loudness results="$_melt_loudness"}} $filters${channels:+ $_melt_postfilters_audio} -consumer avformat:"$stem.mp4" ${bitrate_fixed:+pass=2} $_melt_h264 $_melt_aac $_melt_out
  345. if [ -z "$melt_recent" ]; then
  346. mv "$stem.mp4" "$stem.mp4"~
  347. qt-faststart "$stem.mp4"~ "$stem.mp4"
  348. [ -f "$stem.mp4" ] && rm "$stem.mp4"~ || mv -f "$stem.mp4"~ "$stem.mp4"
  349. fi
  350. fi
  351. if [ -n "$webm" ]; then
  352. # TODO: use two-pass when supported by melt
  353. $melt -group $_melt_in $infiles -group ${channels:+$audioprefilters${_melt_loudness:+ -filter loudness results="$_melt_loudness"}} $filters${channels:+ $_melt_postfilters_audio} -consumer avformat:"$stem.webm" properties=webm $_melt_webm $_melt_vorbis $_melt_out
  354. fi
  355. # cleanup audio normalize hinting
  356. rm -f $stem.xml
  357. ## JPEG preview
  358. ffmpegthumbnailer -s0 -i "$stem.mp4" -o "$stem.jpg"
  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_mp4="<source src=\"$stem.mp4\" type=\"video/mp4\" />"
  366. # TODO: resolve flash player to use
  367. [ -z "$flashplayer" ] || flash=yes
  368. [ -n "$mp4" ] || [ -z "$flash" ] || error1 "Cannot enable flash when mp4 format is disabled."
  369. _object_flash="<object$__width$__heightplus type=\"application/x-shockwave-flash\" data=\"$flashplayer.swf\">"
  370. _param_name="<param name=\"movie\" value=\"$flashplayer.swf\" />"
  371. _param_flashvars="<param name=\"flashvars\" value=\"image=$stem.jpg&amp;file=$stem.mp4\" />"
  372. __oggfile=${ogg:+open format <a href=\"$stem.ogv\">Ogg</a>}
  373. __webmfile=${webm:+open format <a href=\"$stem.webm\">WebM</a>}
  374. __mp4file=${mp4:+closed Format <a href=\"$stem.mp4\">MPEG-4</a>}
  375. [ -z "$webm" ] || [ -z "$ogg$mp4" ] || webm_and_more=yes
  376. [ -z "$ogg" ] || [ -z "$mp4" ] || ogg_and_mp4=yes
  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. }${webm:+$_source_webm
  382. }${ogg:+$_source_ogg
  383. }${flash:+$_object_flash
  384. $_param_name
  385. $_param_flashvars
  386. }<img src="$stem.jpg"$__width$__height alt="$title"
  387. title="No video playback capabilities, please download the video below" />
  388. ${flash:+</object>
  389. }</video>
  390. <p><strong>Download Video:</strong>
  391. $__webmfile${webm_and_more:+,
  392. }$__oggfile${ogg_and_mp4:+,
  393. }$__mp4file.
  394. </p>
  395. EOF