sndhdr.py 6.9 KB

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