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