sndhdr.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. import warnings
  24. warnings._deprecated(__name__, remove=(3, 13))
  25. # The file structure is top-down except that the test program and its
  26. # subroutine come last.
  27. __all__ = ['what', 'whathdr']
  28. from collections import namedtuple
  29. SndHeaders = namedtuple('SndHeaders',
  30. 'filetype framerate nchannels nframes sampwidth')
  31. SndHeaders.filetype.__doc__ = ("""The value for type indicates the data type
  32. and will be one of the strings 'aifc', 'aiff', 'au','hcom',
  33. 'sndr', 'sndt', 'voc', 'wav', '8svx', 'sb', 'ub', or 'ul'.""")
  34. SndHeaders.framerate.__doc__ = ("""The sampling_rate will be either the actual
  35. value or 0 if unknown or difficult to decode.""")
  36. SndHeaders.nchannels.__doc__ = ("""The number of channels or 0 if it cannot be
  37. determined or if the value is difficult to decode.""")
  38. SndHeaders.nframes.__doc__ = ("""The value for frames will be either the number
  39. of frames or -1.""")
  40. SndHeaders.sampwidth.__doc__ = ("""Either the sample size in bits or
  41. 'A' for A-LAW or 'U' for u-LAW.""")
  42. def what(filename):
  43. """Guess the type of a sound file."""
  44. res = whathdr(filename)
  45. return res
  46. def whathdr(filename):
  47. """Recognize sound headers."""
  48. with open(filename, 'rb') as f:
  49. h = f.read(512)
  50. for tf in tests:
  51. res = tf(h, f)
  52. if res:
  53. return SndHeaders(*res)
  54. return None
  55. #-----------------------------------#
  56. # Subroutines per sound header type #
  57. #-----------------------------------#
  58. tests = []
  59. def test_aifc(h, f):
  60. """AIFC and AIFF files"""
  61. with warnings.catch_warnings():
  62. warnings.simplefilter('ignore', category=DeprecationWarning)
  63. import aifc
  64. if not h.startswith(b'FORM'):
  65. return None
  66. if h[8:12] == b'AIFC':
  67. fmt = 'aifc'
  68. elif h[8:12] == b'AIFF':
  69. fmt = 'aiff'
  70. else:
  71. return None
  72. f.seek(0)
  73. try:
  74. a = aifc.open(f, 'r')
  75. except (EOFError, aifc.Error):
  76. return None
  77. return (fmt, a.getframerate(), a.getnchannels(),
  78. a.getnframes(), 8 * a.getsampwidth())
  79. tests.append(test_aifc)
  80. def test_au(h, f):
  81. """AU and SND files"""
  82. if h.startswith(b'.snd'):
  83. func = get_long_be
  84. elif h[:4] in (b'\0ds.', b'dns.'):
  85. func = get_long_le
  86. else:
  87. return None
  88. filetype = 'au'
  89. hdr_size = func(h[4:8])
  90. data_size = func(h[8:12])
  91. encoding = func(h[12:16])
  92. rate = func(h[16:20])
  93. nchannels = func(h[20:24])
  94. sample_size = 1 # default
  95. if encoding == 1:
  96. sample_bits = 'U'
  97. elif encoding == 2:
  98. sample_bits = 8
  99. elif encoding == 3:
  100. sample_bits = 16
  101. sample_size = 2
  102. else:
  103. sample_bits = '?'
  104. frame_size = sample_size * nchannels
  105. if frame_size:
  106. nframe = data_size / frame_size
  107. else:
  108. nframe = -1
  109. return filetype, rate, nchannels, nframe, sample_bits
  110. tests.append(test_au)
  111. def test_hcom(h, f):
  112. """HCOM file"""
  113. if h[65:69] != b'FSSD' or h[128:132] != b'HCOM':
  114. return None
  115. divisor = get_long_be(h[144:148])
  116. if divisor:
  117. rate = 22050 / divisor
  118. else:
  119. rate = 0
  120. return 'hcom', rate, 1, -1, 8
  121. tests.append(test_hcom)
  122. def test_voc(h, f):
  123. """VOC file"""
  124. if not h.startswith(b'Creative Voice File\032'):
  125. return None
  126. sbseek = get_short_le(h[20:22])
  127. rate = 0
  128. if 0 <= sbseek < 500 and h[sbseek] == 1:
  129. ratecode = 256 - h[sbseek+4]
  130. if ratecode:
  131. rate = int(1000000.0 / ratecode)
  132. return 'voc', rate, 1, -1, 8
  133. tests.append(test_voc)
  134. def test_wav(h, f):
  135. """WAV file"""
  136. import wave
  137. # 'RIFF' <len> 'WAVE' 'fmt ' <len>
  138. if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ':
  139. return None
  140. f.seek(0)
  141. try:
  142. w = wave.open(f, 'r')
  143. except (EOFError, wave.Error):
  144. return None
  145. return ('wav', w.getframerate(), w.getnchannels(),
  146. w.getnframes(), 8*w.getsampwidth())
  147. tests.append(test_wav)
  148. def test_8svx(h, f):
  149. """8SVX file"""
  150. if not h.startswith(b'FORM') or h[8:12] != b'8SVX':
  151. return None
  152. # Should decode it to get #channels -- assume always 1
  153. return '8svx', 0, 1, 0, 8
  154. tests.append(test_8svx)
  155. def test_sndt(h, f):
  156. """SNDT file"""
  157. if h.startswith(b'SOUND'):
  158. nsamples = get_long_le(h[8:12])
  159. rate = get_short_le(h[20:22])
  160. return 'sndt', rate, 1, nsamples, 8
  161. tests.append(test_sndt)
  162. def test_sndr(h, f):
  163. """SNDR file"""
  164. if h.startswith(b'\0\0'):
  165. rate = get_short_le(h[2:4])
  166. if 4000 <= rate <= 25000:
  167. return 'sndr', rate, 1, -1, 8
  168. tests.append(test_sndr)
  169. #-------------------------------------------#
  170. # Subroutines to extract numbers from bytes #
  171. #-------------------------------------------#
  172. def get_long_be(b):
  173. return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]
  174. def get_long_le(b):
  175. return (b[3] << 24) | (b[2] << 16) | (b[1] << 8) | b[0]
  176. def get_short_be(b):
  177. return (b[0] << 8) | b[1]
  178. def get_short_le(b):
  179. return (b[1] << 8) | b[0]
  180. #--------------------#
  181. # Small test program #
  182. #--------------------#
  183. def test():
  184. import sys
  185. recursive = 0
  186. if sys.argv[1:] and sys.argv[1] == '-r':
  187. del sys.argv[1:2]
  188. recursive = 1
  189. try:
  190. if sys.argv[1:]:
  191. testall(sys.argv[1:], recursive, 1)
  192. else:
  193. testall(['.'], recursive, 1)
  194. except KeyboardInterrupt:
  195. sys.stderr.write('\n[Interrupted]\n')
  196. sys.exit(1)
  197. def testall(list, recursive, toplevel):
  198. import sys
  199. import os
  200. for filename in list:
  201. if os.path.isdir(filename):
  202. print(filename + '/:', end=' ')
  203. if recursive or toplevel:
  204. print('recursing down:')
  205. import glob
  206. names = glob.glob(os.path.join(glob.escape(filename), '*'))
  207. testall(names, recursive, 0)
  208. else:
  209. print('*** directory (use -r) ***')
  210. else:
  211. print(filename + ':', end=' ')
  212. sys.stdout.flush()
  213. try:
  214. print(what(filename))
  215. except OSError:
  216. print('*** not found ***')
  217. if __name__ == '__main__':
  218. test()