summaryrefslogtreecommitdiff
path: root/localvideowebencode
blob: d4670da0793879f779df673f0c54e4890d4c584c (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_fixed="$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. _frames="${framerate:-$framerate_in}"
  233. if [ -n "$_pixels" ] && [ $_pixels -ge $((1024*768)) ]; then
  234. webmpreset="${webmpreset:-720p}"
  235. if [ -n "$_frames" ] && [ $_frames -gt 40 ]; then
  236. webmpreset="${webmpreset:-720p50_60}"
  237. fi
  238. fi
  239. bitrate="$bitrate_fixed"
  240. # default per-codec-channel bitrates
  241. bitrate_vorbis=64
  242. bitrate_aac=96
  243. case "$audio" in
  244. music)
  245. channels=2
  246. # limit (i.e. avoid peaks "clipping")
  247. _melt_audio_filters="-filter ladspa.1077"
  248. ;;
  249. speech)
  250. channels=1
  251. bitrate_vorbis=48
  252. bitrate_aac=64
  253. # expand and compress (i.e. lower volume on silent and loud passages)
  254. _melt_audio_filters_early="-filter ladspa.1075 -filter ladspa.1073"
  255. # limit (i.e. avoid peaks "clipping")
  256. _melt_audio_filters="-filter ladspa.1077"
  257. ;;
  258. silence)
  259. channels=0
  260. ;;
  261. '')
  262. channels=$(avprobe -v warning -show_streams "$infile_first" | perl -ne 's/channels=// and print $_')
  263. ;;
  264. *) exit1 "Unknown audio style \"$audio\".";;
  265. esac
  266. [ $channels -le 2 ] || channels=2
  267. [ $channels -gt 0 ] || channels=
  268. # TODO: Check and fail if all needed tools are not available
  269. # TODO: When verified beneficial, add option real_time=-2
  270. melt="melt -progress"
  271. _melt_in="${_melt_in:+$_melt_in }$sample"
  272. _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}"
  273. _melt_ogg="$_melt_video f=ogg vcodec=libtheora${bitrate_fixed:- qscale=5}"
  274. _melt_h264="$_melt_video $_melt_h264${bitrate_fixed:- qscale=5}"
  275. _melt_webm="$_melt_video vpre=libvpx-${webmpreset:-360p}"
  276. _melt_audio="${channels:+ac=$channels}"
  277. _melt_vorbis="$_melt_audio acodec=libvorbis ab=$(($channels*$bitrate_vorbis))k"
  278. _melt_aac="$_melt_audio acodec=aac ab=$(($channels*$bitrate_aac))k"
  279. # resolve EBU R128 audio normalizing
  280. # TODO: normalize each infile separately when xml fed as infile keeps sync
  281. if [ -n "$melt_recent" ] && [ -n "$channels" ]; then
  282. $melt -group $_melt_in $infiles -group $_melt_audio_filters_early -filter loudness -consumer xml:$stem.xml $_melt_audio video_off=1 all=1
  283. _melt_loudness="$(perl -ne 'm!<property name="results">([^<]+)</property>! and print $1' $stem.xml)"
  284. fi
  285. ## Theora/Vorbis/Ogg
  286. $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
  287. ## H.264/AAC/MP4
  288. [ -z "$bitrate_fixed" ] || $melt -group $_melt_in $infiles -group $filters -consumer avformat:/dev/null properties=x264-medium-pass1 $_melt_h264 $_melt_out
  289. $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
  290. if [ -z "$melt_recent" ]; then
  291. mv "$stem.mp4" "$stem.mp4"~
  292. qt-faststart "$stem.mp4"~ "$stem.mp4"
  293. [ -f "$stem.mp4" ] && rm "$stem.mp4"~ || mv -f "$stem.mp4"~ "$stem.mp4"
  294. fi
  295. ## VP8/Vorbis/WebM
  296. # TODO: use two-pass when supported by melt
  297. $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
  298. # cleanup audio normalize hinting
  299. rm -f $stem.xml
  300. ## JPEG preview
  301. ffmpegthumbnailer -s0 -i "$stem.mp4" -o "$stem.jpg"
  302. # resolve width and height from preview image
  303. size=$(jpeginfo "$stem.jpg" | perl -ane 'print "$F[1]x$F[3]"')
  304. width=$(echo "$size" | perl -Fx -ane 'print $F[0]')
  305. height=$(echo "$size" | perl -Fx -ane 'print $F[1]')
  306. heightplus=${height:+$(($height+4))}
  307. # TODO: resolve flash player to use
  308. [ -z "$flashplayer" ] || flash=yes
  309. cat >"$stem.html" <<EOF
  310. <!-- Video for Everybody, Kroc Camen of Camen Design -->
  311. <video width="$width" height="$height" preload controls>
  312. <source src="$stem.mp4" type="video/mp4" />
  313. <source src="$stem.webm" type="video/webm" />
  314. <source src="$stem.ogv" type="video/ogg" />
  315. ${flash:+<object width="$width" height="$heightplus" type="application/x-shockwave-flash" data="$flashplayer.swf">
  316. <param name="movie" value="$flashplayer.swf" />
  317. <param name="flashvars" value="image=$stem.jpg&amp;file=$stem.mp4" />
  318. }<img src="$stem.jpg" width="$width" height="$height" alt="$title"
  319. title="No video playback capabilities, please download the video below" />
  320. ${flash:+</object>
  321. }</video>
  322. <p><strong>Download Video:</strong>
  323. open format <a href="$stem.webm">WebM</a>,
  324. open format <a href="$stem.ogv">Ogg</a>,
  325. closed Format <a href="$stem.mp4">MPEG-4</a>.
  326. </p>
  327. EOF