1#!/usr/bin/env python2
2
3import sys, subprocess
4
5if len(sys.argv) > 1:
6    ifile  = sys.argv[1]
7    encopt = sys.argv[2:-1]
8    ofile  = sys.argv[-1]
9else:
10    print 'usage: %s <input> [encode_options] <output>' % sys.argv[0]
11    sys.exit(1)
12
13analysis_cmd  = 'ffprobe -v error -of compact=p=0:nk=1 '
14analysis_cmd += '-show_entries frame_tags=lavfi.r128.I -f lavfi '
15analysis_cmd += "amovie='%s',ebur128=metadata=1" % ifile
16try:
17    probe_out = subprocess.check_output(analysis_cmd, shell=True)
18except subprocess.CalledProcessError, e:
19    sys.exit(e.returncode)
20loudness = ref = -23
21for line in probe_out.splitlines():
22    sline = line.rstrip()
23    if sline:
24        loudness = sline
25adjust = ref - float(loudness)
26if abs(adjust) < 0.0001:
27    print 'No normalization needed for ' + ifile
28else:
29    print "Adjust %s by %.1fdB" % (ifile, adjust)
30    norm_cmd  = ['ffmpeg', '-i', ifile, '-af', 'volume=%fdB' % adjust]
31    norm_cmd += encopt + [ofile]
32    print ' => %s' % ' '.join(norm_cmd)
33    subprocess.call(norm_cmd)
34