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