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