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