You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sndhdr.py 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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, IOError 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. def what(filename):
  27. """Guess the type of a sound file"""
  28. res = whathdr(filename)
  29. return res
  30. def whathdr(filename):
  31. """Recognize sound headers"""
  32. f = open(filename, 'r')
  33. h = f.read(512)
  34. for tf in tests:
  35. res = tf(h, f)
  36. if res:
  37. return res
  38. return None
  39. #-----------------------------------#
  40. # Subroutines per sound header type #
  41. #-----------------------------------#
  42. tests = []
  43. def test_aifc(h, f):
  44. import aifc
  45. if h[:4] != 'FORM':
  46. return None
  47. if h[8:12] == 'AIFC':
  48. fmt = 'aifc'
  49. elif h[8:12] == 'AIFF':
  50. fmt = 'aiff'
  51. else:
  52. return None
  53. f.seek(0)
  54. try:
  55. a = aifc.openfp(f, 'r')
  56. except (EOFError, aifc.Error):
  57. return None
  58. return (fmt, a.getframerate(), a.getnchannels(), \
  59. a.getnframes(), 8*a.getsampwidth())
  60. tests.append(test_aifc)
  61. def test_au(h, f):
  62. if h[:4] == '.snd':
  63. f = get_long_be
  64. elif h[:4] in ('\0ds.', 'dns.'):
  65. f = get_long_le
  66. else:
  67. return None
  68. type = 'au'
  69. hdr_size = f(h[4:8])
  70. data_size = f(h[8:12])
  71. encoding = f(h[12:16])
  72. rate = f(h[16:20])
  73. nchannels = f(h[20:24])
  74. sample_size = 1 # default
  75. if encoding == 1:
  76. sample_bits = 'U'
  77. elif encoding == 2:
  78. sample_bits = 8
  79. elif encoding == 3:
  80. sample_bits = 16
  81. sample_size = 2
  82. else:
  83. sample_bits = '?'
  84. frame_size = sample_size * nchannels
  85. return type, rate, nchannels, data_size/frame_size, sample_bits
  86. tests.append(test_au)
  87. def test_hcom(h, f):
  88. if h[65:69] != 'FSSD' or h[128:132] != 'HCOM':
  89. return None
  90. divisor = get_long_be(h[128+16:128+20])
  91. return 'hcom', 22050/divisor, 1, -1, 8
  92. tests.append(test_hcom)
  93. def test_voc(h, f):
  94. if h[:20] != 'Creative Voice File\032':
  95. return None
  96. sbseek = get_short_le(h[20:22])
  97. rate = 0
  98. if 0 <= sbseek < 500 and h[sbseek] == '\1':
  99. ratecode = ord(h[sbseek+4])
  100. rate = int(1000000.0 / (256 - ratecode))
  101. return 'voc', rate, 1, -1, 8
  102. tests.append(test_voc)
  103. def test_wav(h, f):
  104. # 'RIFF' <len> 'WAVE' 'fmt ' <len>
  105. if h[:4] != 'RIFF' or h[8:12] != 'WAVE' or h[12:16] != 'fmt ':
  106. return None
  107. style = get_short_le(h[20:22])
  108. nchannels = get_short_le(h[22:24])
  109. rate = get_long_le(h[24:28])
  110. sample_bits = get_short_le(h[34:36])
  111. return 'wav', rate, nchannels, -1, sample_bits
  112. tests.append(test_wav)
  113. def test_8svx(h, f):
  114. if h[:4] != 'FORM' or h[8:12] != '8SVX':
  115. return None
  116. # Should decode it to get #channels -- assume always 1
  117. return '8svx', 0, 1, 0, 8
  118. tests.append(test_8svx)
  119. def test_sndt(h, f):
  120. if h[:5] == 'SOUND':
  121. nsamples = get_long_le(h[8:12])
  122. rate = get_short_le(h[20:22])
  123. return 'sndt', rate, 1, nsamples, 8
  124. tests.append(test_sndt)
  125. def test_sndr(h, f):
  126. if h[:2] == '\0\0':
  127. rate = get_short_le(h[2:4])
  128. if 4000 <= rate <= 25000:
  129. return 'sndr', rate, 1, -1, 8
  130. tests.append(test_sndr)
  131. #---------------------------------------------#
  132. # Subroutines to extract numbers from strings #
  133. #---------------------------------------------#
  134. def get_long_be(s):
  135. return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3])
  136. def get_long_le(s):
  137. return (ord(s[3])<<24) | (ord(s[2])<<16) | (ord(s[1])<<8) | ord(s[0])
  138. def get_short_be(s):
  139. return (ord(s[0])<<8) | ord(s[1])
  140. def get_short_le(s):
  141. return (ord(s[1])<<8) | ord(s[0])
  142. #--------------------#
  143. # Small test program #
  144. #--------------------#
  145. def test():
  146. import sys
  147. recursive = 0
  148. if sys.argv[1:] and sys.argv[1] == '-r':
  149. del sys.argv[1:2]
  150. recursive = 1
  151. try:
  152. if sys.argv[1:]:
  153. testall(sys.argv[1:], recursive, 1)
  154. else:
  155. testall(['.'], recursive, 1)
  156. except KeyboardInterrupt:
  157. sys.stderr.write('\n[Interrupted]\n')
  158. sys.exit(1)
  159. def testall(list, recursive, toplevel):
  160. import sys
  161. import os
  162. for filename in list:
  163. if os.path.isdir(filename):
  164. print filename + '/:',
  165. if recursive or toplevel:
  166. print 'recursing down:'
  167. import glob
  168. names = glob.glob(os.path.join(filename, '*'))
  169. testall(names, recursive, 0)
  170. else:
  171. print '*** directory (use -r) ***'
  172. else:
  173. print filename + ':',
  174. sys.stdout.flush()
  175. try:
  176. print what(filename)
  177. except IOError:
  178. print '*** not found ***'
  179. if __name__ == '__main__':
  180. test()