1 | n/a | """Routines to help recognizing sound files. |
---|
2 | n/a | |
---|
3 | n/a | Function whathdr() recognizes various types of sound file headers. |
---|
4 | n/a | It understands almost all headers that SOX can decode. |
---|
5 | n/a | |
---|
6 | n/a | The return tuple contains the following items, in this order: |
---|
7 | n/a | - file type (as SOX understands it) |
---|
8 | n/a | - sampling rate (0 if unknown or hard to decode) |
---|
9 | n/a | - number of channels (0 if unknown or hard to decode) |
---|
10 | n/a | - number of frames in the file (-1 if unknown or hard to decode) |
---|
11 | n/a | - number of bits/sample, or 'U' for U-LAW, or 'A' for A-LAW |
---|
12 | n/a | |
---|
13 | n/a | If the file doesn't have a recognizable type, it returns None. |
---|
14 | n/a | If the file can't be opened, OSError is raised. |
---|
15 | n/a | |
---|
16 | n/a | To compute the total time, divide the number of frames by the |
---|
17 | n/a | sampling rate (a frame contains a sample for each channel). |
---|
18 | n/a | |
---|
19 | n/a | Function what() calls whathdr(). (It used to also use some |
---|
20 | n/a | heuristics for raw data, but this doesn't work very well.) |
---|
21 | n/a | |
---|
22 | n/a | Finally, the function test() is a simple main program that calls |
---|
23 | n/a | what() for all files mentioned on the argument list. For directory |
---|
24 | n/a | arguments it calls what() for all files in that directory. Default |
---|
25 | n/a | argument is "." (testing all files in the current directory). The |
---|
26 | n/a | option -r tells it to recurse down directories found inside |
---|
27 | n/a | explicitly given directories. |
---|
28 | n/a | """ |
---|
29 | n/a | |
---|
30 | n/a | # The file structure is top-down except that the test program and its |
---|
31 | n/a | # subroutine come last. |
---|
32 | n/a | |
---|
33 | n/a | __all__ = ['what', 'whathdr'] |
---|
34 | n/a | |
---|
35 | n/a | from collections import namedtuple |
---|
36 | n/a | |
---|
37 | n/a | SndHeaders = namedtuple('SndHeaders', |
---|
38 | n/a | 'filetype framerate nchannels nframes sampwidth') |
---|
39 | n/a | |
---|
40 | n/a | SndHeaders.filetype.__doc__ = ("""The value for type indicates the data type |
---|
41 | n/a | and will be one of the strings 'aifc', 'aiff', 'au','hcom', |
---|
42 | n/a | 'sndr', 'sndt', 'voc', 'wav', '8svx', 'sb', 'ub', or 'ul'.""") |
---|
43 | n/a | SndHeaders.framerate.__doc__ = ("""The sampling_rate will be either the actual |
---|
44 | n/a | value or 0 if unknown or difficult to decode.""") |
---|
45 | n/a | SndHeaders.nchannels.__doc__ = ("""The number of channels or 0 if it cannot be |
---|
46 | n/a | determined or if the value is difficult to decode.""") |
---|
47 | n/a | SndHeaders.nframes.__doc__ = ("""The value for frames will be either the number |
---|
48 | n/a | of frames or -1.""") |
---|
49 | n/a | SndHeaders.sampwidth.__doc__ = ("""Either the sample size in bits or |
---|
50 | n/a | 'A' for A-LAW or 'U' for u-LAW.""") |
---|
51 | n/a | |
---|
52 | n/a | def what(filename): |
---|
53 | n/a | """Guess the type of a sound file.""" |
---|
54 | n/a | res = whathdr(filename) |
---|
55 | n/a | return res |
---|
56 | n/a | |
---|
57 | n/a | |
---|
58 | n/a | def whathdr(filename): |
---|
59 | n/a | """Recognize sound headers.""" |
---|
60 | n/a | with open(filename, 'rb') as f: |
---|
61 | n/a | h = f.read(512) |
---|
62 | n/a | for tf in tests: |
---|
63 | n/a | res = tf(h, f) |
---|
64 | n/a | if res: |
---|
65 | n/a | return SndHeaders(*res) |
---|
66 | n/a | return None |
---|
67 | n/a | |
---|
68 | n/a | |
---|
69 | n/a | #-----------------------------------# |
---|
70 | n/a | # Subroutines per sound header type # |
---|
71 | n/a | #-----------------------------------# |
---|
72 | n/a | |
---|
73 | n/a | tests = [] |
---|
74 | n/a | |
---|
75 | n/a | def test_aifc(h, f): |
---|
76 | n/a | import aifc |
---|
77 | n/a | if not h.startswith(b'FORM'): |
---|
78 | n/a | return None |
---|
79 | n/a | if h[8:12] == b'AIFC': |
---|
80 | n/a | fmt = 'aifc' |
---|
81 | n/a | elif h[8:12] == b'AIFF': |
---|
82 | n/a | fmt = 'aiff' |
---|
83 | n/a | else: |
---|
84 | n/a | return None |
---|
85 | n/a | f.seek(0) |
---|
86 | n/a | try: |
---|
87 | n/a | a = aifc.open(f, 'r') |
---|
88 | n/a | except (EOFError, aifc.Error): |
---|
89 | n/a | return None |
---|
90 | n/a | return (fmt, a.getframerate(), a.getnchannels(), |
---|
91 | n/a | a.getnframes(), 8 * a.getsampwidth()) |
---|
92 | n/a | |
---|
93 | n/a | tests.append(test_aifc) |
---|
94 | n/a | |
---|
95 | n/a | |
---|
96 | n/a | def test_au(h, f): |
---|
97 | n/a | if h.startswith(b'.snd'): |
---|
98 | n/a | func = get_long_be |
---|
99 | n/a | elif h[:4] in (b'\0ds.', b'dns.'): |
---|
100 | n/a | func = get_long_le |
---|
101 | n/a | else: |
---|
102 | n/a | return None |
---|
103 | n/a | filetype = 'au' |
---|
104 | n/a | hdr_size = func(h[4:8]) |
---|
105 | n/a | data_size = func(h[8:12]) |
---|
106 | n/a | encoding = func(h[12:16]) |
---|
107 | n/a | rate = func(h[16:20]) |
---|
108 | n/a | nchannels = func(h[20:24]) |
---|
109 | n/a | sample_size = 1 # default |
---|
110 | n/a | if encoding == 1: |
---|
111 | n/a | sample_bits = 'U' |
---|
112 | n/a | elif encoding == 2: |
---|
113 | n/a | sample_bits = 8 |
---|
114 | n/a | elif encoding == 3: |
---|
115 | n/a | sample_bits = 16 |
---|
116 | n/a | sample_size = 2 |
---|
117 | n/a | else: |
---|
118 | n/a | sample_bits = '?' |
---|
119 | n/a | frame_size = sample_size * nchannels |
---|
120 | n/a | if frame_size: |
---|
121 | n/a | nframe = data_size / frame_size |
---|
122 | n/a | else: |
---|
123 | n/a | nframe = -1 |
---|
124 | n/a | return filetype, rate, nchannels, nframe, sample_bits |
---|
125 | n/a | |
---|
126 | n/a | tests.append(test_au) |
---|
127 | n/a | |
---|
128 | n/a | |
---|
129 | n/a | def test_hcom(h, f): |
---|
130 | n/a | if h[65:69] != b'FSSD' or h[128:132] != b'HCOM': |
---|
131 | n/a | return None |
---|
132 | n/a | divisor = get_long_be(h[144:148]) |
---|
133 | n/a | if divisor: |
---|
134 | n/a | rate = 22050 / divisor |
---|
135 | n/a | else: |
---|
136 | n/a | rate = 0 |
---|
137 | n/a | return 'hcom', rate, 1, -1, 8 |
---|
138 | n/a | |
---|
139 | n/a | tests.append(test_hcom) |
---|
140 | n/a | |
---|
141 | n/a | |
---|
142 | n/a | def test_voc(h, f): |
---|
143 | n/a | if not h.startswith(b'Creative Voice File\032'): |
---|
144 | n/a | return None |
---|
145 | n/a | sbseek = get_short_le(h[20:22]) |
---|
146 | n/a | rate = 0 |
---|
147 | n/a | if 0 <= sbseek < 500 and h[sbseek] == 1: |
---|
148 | n/a | ratecode = 256 - h[sbseek+4] |
---|
149 | n/a | if ratecode: |
---|
150 | n/a | rate = int(1000000.0 / ratecode) |
---|
151 | n/a | return 'voc', rate, 1, -1, 8 |
---|
152 | n/a | |
---|
153 | n/a | tests.append(test_voc) |
---|
154 | n/a | |
---|
155 | n/a | |
---|
156 | n/a | def test_wav(h, f): |
---|
157 | n/a | import wave |
---|
158 | n/a | # 'RIFF' <len> 'WAVE' 'fmt ' <len> |
---|
159 | n/a | if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ': |
---|
160 | n/a | return None |
---|
161 | n/a | f.seek(0) |
---|
162 | n/a | try: |
---|
163 | n/a | w = wave.openfp(f, 'r') |
---|
164 | n/a | except (EOFError, wave.Error): |
---|
165 | n/a | return None |
---|
166 | n/a | return ('wav', w.getframerate(), w.getnchannels(), |
---|
167 | n/a | w.getnframes(), 8*w.getsampwidth()) |
---|
168 | n/a | |
---|
169 | n/a | tests.append(test_wav) |
---|
170 | n/a | |
---|
171 | n/a | |
---|
172 | n/a | def test_8svx(h, f): |
---|
173 | n/a | if not h.startswith(b'FORM') or h[8:12] != b'8SVX': |
---|
174 | n/a | return None |
---|
175 | n/a | # Should decode it to get #channels -- assume always 1 |
---|
176 | n/a | return '8svx', 0, 1, 0, 8 |
---|
177 | n/a | |
---|
178 | n/a | tests.append(test_8svx) |
---|
179 | n/a | |
---|
180 | n/a | |
---|
181 | n/a | def test_sndt(h, f): |
---|
182 | n/a | if h.startswith(b'SOUND'): |
---|
183 | n/a | nsamples = get_long_le(h[8:12]) |
---|
184 | n/a | rate = get_short_le(h[20:22]) |
---|
185 | n/a | return 'sndt', rate, 1, nsamples, 8 |
---|
186 | n/a | |
---|
187 | n/a | tests.append(test_sndt) |
---|
188 | n/a | |
---|
189 | n/a | |
---|
190 | n/a | def test_sndr(h, f): |
---|
191 | n/a | if h.startswith(b'\0\0'): |
---|
192 | n/a | rate = get_short_le(h[2:4]) |
---|
193 | n/a | if 4000 <= rate <= 25000: |
---|
194 | n/a | return 'sndr', rate, 1, -1, 8 |
---|
195 | n/a | |
---|
196 | n/a | tests.append(test_sndr) |
---|
197 | n/a | |
---|
198 | n/a | |
---|
199 | n/a | #-------------------------------------------# |
---|
200 | n/a | # Subroutines to extract numbers from bytes # |
---|
201 | n/a | #-------------------------------------------# |
---|
202 | n/a | |
---|
203 | n/a | def get_long_be(b): |
---|
204 | n/a | return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3] |
---|
205 | n/a | |
---|
206 | n/a | def get_long_le(b): |
---|
207 | n/a | return (b[3] << 24) | (b[2] << 16) | (b[1] << 8) | b[0] |
---|
208 | n/a | |
---|
209 | n/a | def get_short_be(b): |
---|
210 | n/a | return (b[0] << 8) | b[1] |
---|
211 | n/a | |
---|
212 | n/a | def get_short_le(b): |
---|
213 | n/a | return (b[1] << 8) | b[0] |
---|
214 | n/a | |
---|
215 | n/a | |
---|
216 | n/a | #--------------------# |
---|
217 | n/a | # Small test program # |
---|
218 | n/a | #--------------------# |
---|
219 | n/a | |
---|
220 | n/a | def test(): |
---|
221 | n/a | import sys |
---|
222 | n/a | recursive = 0 |
---|
223 | n/a | if sys.argv[1:] and sys.argv[1] == '-r': |
---|
224 | n/a | del sys.argv[1:2] |
---|
225 | n/a | recursive = 1 |
---|
226 | n/a | try: |
---|
227 | n/a | if sys.argv[1:]: |
---|
228 | n/a | testall(sys.argv[1:], recursive, 1) |
---|
229 | n/a | else: |
---|
230 | n/a | testall(['.'], recursive, 1) |
---|
231 | n/a | except KeyboardInterrupt: |
---|
232 | n/a | sys.stderr.write('\n[Interrupted]\n') |
---|
233 | n/a | sys.exit(1) |
---|
234 | n/a | |
---|
235 | n/a | def testall(list, recursive, toplevel): |
---|
236 | n/a | import sys |
---|
237 | n/a | import os |
---|
238 | n/a | for filename in list: |
---|
239 | n/a | if os.path.isdir(filename): |
---|
240 | n/a | print(filename + '/:', end=' ') |
---|
241 | n/a | if recursive or toplevel: |
---|
242 | n/a | print('recursing down:') |
---|
243 | n/a | import glob |
---|
244 | n/a | names = glob.glob(os.path.join(filename, '*')) |
---|
245 | n/a | testall(names, recursive, 0) |
---|
246 | n/a | else: |
---|
247 | n/a | print('*** directory (use -r) ***') |
---|
248 | n/a | else: |
---|
249 | n/a | print(filename + ':', end=' ') |
---|
250 | n/a | sys.stdout.flush() |
---|
251 | n/a | try: |
---|
252 | n/a | print(what(filename)) |
---|
253 | n/a | except OSError: |
---|
254 | n/a | print('*** not found ***') |
---|
255 | n/a | |
---|
256 | n/a | if __name__ == '__main__': |
---|
257 | n/a | test() |
---|