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