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