Debian Codegraph @

mediafile/utils/soundcheck.py

raw
1 # iTunes Sound Check encoding.
2
3
4 import binascii
5 import codecs
6 import math
7 import struct
8
9
10 def sc_decode(soundcheck):
11 """Convert a Sound Check bytestring value to a (gain, peak) tuple as
12 used by ReplayGain.
13 """
14 # We decode binary data. If one of the formats gives us a text
15 # string, interpret it as UTF-8.
16 if isinstance(soundcheck, str):
17 soundcheck = soundcheck.encode("utf-8")
18
19 # SoundCheck tags consist of 10 numbers, each represented by 8
20 # characters of ASCII hex preceded by a space.
21 try:
22 soundcheck = codecs.decode(soundcheck.replace(b" ", b""), "hex")
23 soundcheck = struct.unpack("!iiiiiiiiii", soundcheck)
24 except (struct.error, TypeError, binascii.Error):
25 # SoundCheck isn't in the format we expect, so return default
26 # values.
27 return 0.0, 0.0
28
29 # SoundCheck stores absolute calculated/measured RMS value in an
30 # unknown unit. We need to find the ratio of this measurement
31 # compared to a reference value of 1000 to get our gain in dB. We
32 # play it safe by using the larger of the two values (i.e., the most
33 # attenuation).
34 maxgain = max(soundcheck[:2])
35 if maxgain > 0:
36 gain = math.log10(maxgain / 1000.0) * -10
37 else:
38 # Invalid gain value found.
39 gain = 0.0
40
41 # SoundCheck stores peak values as the actual value of the sample,
42 # and again separately for the left and right channels. We need to
43 # convert this to a percentage of full scale, which is 32768 for a
44 # 16 bit sample. Once again, we play it safe by using the larger of
45 # the two values.
46 peak = max(soundcheck[6:8]) / 32768.0
47
48 return round(gain, 2), round(peak, 6)
49
50
51 def sc_encode(gain, peak):
52 """Encode ReplayGain gain/peak values as a Sound Check string."""
53 # SoundCheck stores the peak value as the actual value of the
54 # sample, rather than the percentage of full scale that RG uses, so
55 # we do a simple conversion assuming 16 bit samples.
56 peak *= 32768.0
57
58 # SoundCheck stores absolute RMS values in some unknown units rather
59 # than the dB values RG uses. We can calculate these absolute values
60 # from the gain ratio using a reference value of 1000 units. We also
61 # enforce the maximum and minimum value here, which is equivalent to
62 # about -18.2dB and 30.0dB.
63 g1 = int(min(round((10 ** (gain / -10)) * 1000), 65534)) or 1
64 # Same as above, except our reference level is 2500 units.
65 g2 = int(min(round((10 ** (gain / -10)) * 2500), 65534)) or 1
66
67 # The purpose of these values are unknown, but they also seem to be
68 # unused so we just use zero.
69 uk = 0
70 values = (g1, g1, g2, g2, uk, uk, int(peak), int(peak), uk, uk)
71 return (" %08X" * 10) % values