audioprocessing.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. #!/usr/bin/env python
  2. # processing.py -- various audio processing functions
  3. # Copyright (C) 2008 MUSIC TECHNOLOGY GROUP (MTG)
  4. # UNIVERSITAT POMPEU FABRA
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU Affero General Public License as
  8. # published by the Free Software Foundation, either version 3 of the
  9. # License, or (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU Affero General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Affero General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. # Authors:
  20. # Bram de Jong <bram.dejong at domain.com where domain in gmail>
  21. # 2012, Joar Wandborg <first name at last name dot se>
  22. from PIL import Image, ImageDraw, ImageColor #@UnresolvedImport
  23. from functools import partial
  24. import math
  25. import numpy
  26. import os
  27. import re
  28. import signal
  29. def get_sound_type(input_filename):
  30. sound_type = os.path.splitext(input_filename.lower())[1].strip(".")
  31. if sound_type == "fla":
  32. sound_type = "flac"
  33. elif sound_type == "aif":
  34. sound_type = "aiff"
  35. return sound_type
  36. try:
  37. import scikits.audiolab as audiolab
  38. except ImportError:
  39. print("WARNING: audiolab is not installed so wav2png will not work")
  40. import subprocess
  41. class AudioProcessingException(Exception):
  42. pass
  43. class TestAudioFile(object):
  44. """A class that mimics audiolab.sndfile but generates noise instead of reading
  45. a wave file. Additionally it can be told to have a "broken" header and thus crashing
  46. in the middle of the file. Also useful for testing ultra-short files of 20 samples."""
  47. def __init__(self, num_frames, has_broken_header=False):
  48. self.seekpoint = 0
  49. self.nframes = num_frames
  50. self.samplerate = 44100
  51. self.channels = 1
  52. self.has_broken_header = has_broken_header
  53. def seek(self, seekpoint):
  54. self.seekpoint = seekpoint
  55. def read_frames(self, frames_to_read):
  56. if self.has_broken_header and self.seekpoint + frames_to_read > self.num_frames / 2:
  57. raise RuntimeError()
  58. num_frames_left = self.num_frames - self.seekpoint
  59. will_read = num_frames_left if num_frames_left < frames_to_read else frames_to_read
  60. self.seekpoint += will_read
  61. return numpy.random.random(will_read)*2 - 1
  62. def get_max_level(filename):
  63. max_value = 0
  64. buffer_size = 4096
  65. audio_file = audiolab.Sndfile(filename, 'r')
  66. n_samples_left = audio_file.nframes
  67. while n_samples_left:
  68. to_read = min(buffer_size, n_samples_left)
  69. try:
  70. samples = audio_file.read_frames(to_read)
  71. except RuntimeError:
  72. # this can happen with a broken header
  73. break
  74. # convert to mono by selecting left channel only
  75. if audio_file.channels > 1:
  76. samples = samples[:,0]
  77. max_value = max(max_value, numpy.abs(samples).max())
  78. n_samples_left -= to_read
  79. audio_file.close()
  80. return max_value
  81. class AudioProcessor(object):
  82. """
  83. The audio processor processes chunks of audio an calculates the spectrac centroid and the peak
  84. samples in that chunk of audio.
  85. """
  86. def __init__(self, input_filename, fft_size, window_function=numpy.hanning):
  87. max_level = get_max_level(input_filename)
  88. self.audio_file = audiolab.Sndfile(input_filename, 'r')
  89. self.fft_size = fft_size
  90. self.window = window_function(self.fft_size)
  91. self.spectrum_range = None
  92. self.lower = 100
  93. self.higher = 22050
  94. self.lower_log = math.log10(self.lower)
  95. self.higher_log = math.log10(self.higher)
  96. self.clip = lambda val, low, high: min(high, max(low, val))
  97. # figure out what the maximum value is for an FFT doing the FFT of a DC signal
  98. fft = numpy.fft.rfft(numpy.ones(fft_size) * self.window)
  99. max_fft = (numpy.abs(fft)).max()
  100. # set the scale to normalized audio and normalized FFT
  101. self.scale = 1.0/max_level/max_fft if max_level > 0 else 1
  102. def read(self, start, size, resize_if_less=False):
  103. """ read size samples starting at start, if resize_if_less is True and less than size
  104. samples are read, resize the array to size and fill with zeros """
  105. # number of zeros to add to start and end of the buffer
  106. add_to_start = 0
  107. add_to_end = 0
  108. if start < 0:
  109. # the first FFT window starts centered around zero
  110. if size + start <= 0:
  111. return numpy.zeros(size) if resize_if_less else numpy.array([])
  112. else:
  113. self.audio_file.seek(0)
  114. add_to_start = -start # remember: start is negative!
  115. to_read = size + start
  116. if to_read > self.audio_file.nframes:
  117. add_to_end = to_read - self.audio_file.nframes
  118. to_read = self.audio_file.nframes
  119. else:
  120. self.audio_file.seek(start)
  121. to_read = size
  122. if start + to_read >= self.audio_file.nframes:
  123. to_read = self.audio_file.nframes - start
  124. add_to_end = size - to_read
  125. try:
  126. samples = self.audio_file.read_frames(to_read)
  127. except RuntimeError:
  128. # this can happen for wave files with broken headers...
  129. return numpy.zeros(size) if resize_if_less else numpy.zeros(2)
  130. # convert to mono by selecting left channel only
  131. if self.audio_file.channels > 1:
  132. samples = samples[:,0]
  133. if resize_if_less and (add_to_start > 0 or add_to_end > 0):
  134. if add_to_start > 0:
  135. samples = numpy.concatenate((numpy.zeros(add_to_start), samples), axis=1)
  136. if add_to_end > 0:
  137. samples = numpy.resize(samples, size)
  138. samples[size - add_to_end:] = 0
  139. return samples
  140. def spectral_centroid(self, seek_point, spec_range=110.0):
  141. """ starting at seek_point read fft_size samples, and calculate the spectral centroid """
  142. samples = self.read(seek_point - self.fft_size/2, self.fft_size, True)
  143. samples *= self.window
  144. fft = numpy.fft.rfft(samples)
  145. spectrum = self.scale * numpy.abs(fft) # normalized abs(FFT) between 0 and 1
  146. length = numpy.float64(spectrum.shape[0])
  147. # scale the db spectrum from [- spec_range db ... 0 db] > [0..1]
  148. db_spectrum = ((20*(numpy.log10(spectrum + 1e-60))).clip(-spec_range, 0.0) + spec_range)/spec_range
  149. energy = spectrum.sum()
  150. spectral_centroid = 0
  151. if energy > 1e-60:
  152. # calculate the spectral centroid
  153. if self.spectrum_range == None:
  154. self.spectrum_range = numpy.arange(length)
  155. spectral_centroid = (spectrum * self.spectrum_range).sum() / (energy * (length - 1)) * self.audio_file.samplerate * 0.5
  156. # clip > log10 > scale between 0 and 1
  157. spectral_centroid = (math.log10(self.clip(spectral_centroid, self.lower, self.higher)) - self.lower_log) / (self.higher_log - self.lower_log)
  158. return (spectral_centroid, db_spectrum)
  159. def peaks(self, start_seek, end_seek):
  160. """ read all samples between start_seek and end_seek, then find the minimum and maximum peak
  161. in that range. Returns that pair in the order they were found. So if min was found first,
  162. it returns (min, max) else the other way around. """
  163. # larger blocksizes are faster but take more mem...
  164. # Aha, Watson, a clue, a tradeof!
  165. block_size = 4096
  166. max_index = -1
  167. max_value = -1
  168. min_index = -1
  169. min_value = 1
  170. if start_seek < 0:
  171. start_seek = 0
  172. if end_seek > self.audio_file.nframes:
  173. end_seek = self.audio_file.nframes
  174. if end_seek <= start_seek:
  175. samples = self.read(start_seek, 1)
  176. return (samples[0], samples[0])
  177. if block_size > end_seek - start_seek:
  178. block_size = end_seek - start_seek
  179. for i in range(start_seek, end_seek, block_size):
  180. samples = self.read(i, block_size)
  181. local_max_index = numpy.argmax(samples)
  182. local_max_value = samples[local_max_index]
  183. if local_max_value > max_value:
  184. max_value = local_max_value
  185. max_index = local_max_index
  186. local_min_index = numpy.argmin(samples)
  187. local_min_value = samples[local_min_index]
  188. if local_min_value < min_value:
  189. min_value = local_min_value
  190. min_index = local_min_index
  191. return (min_value, max_value) if min_index < max_index else (max_value, min_value)
  192. def interpolate_colors(colors, flat=False, num_colors=256):
  193. """ given a list of colors, create a larger list of colors interpolating
  194. the first one. If flatten is True a list of numers will be returned. If
  195. False, a list of (r,g,b) tuples. num_colors is the number of colors wanted
  196. in the final list """
  197. palette = []
  198. for i in range(num_colors):
  199. index = (i * (len(colors) - 1))/(num_colors - 1.0)
  200. index_int = int(index)
  201. alpha = index - float(index_int)
  202. if alpha > 0:
  203. r = (1.0 - alpha) * colors[index_int][0] + alpha * colors[index_int + 1][0]
  204. g = (1.0 - alpha) * colors[index_int][1] + alpha * colors[index_int + 1][1]
  205. b = (1.0 - alpha) * colors[index_int][2] + alpha * colors[index_int + 1][2]
  206. else:
  207. r = (1.0 - alpha) * colors[index_int][0]
  208. g = (1.0 - alpha) * colors[index_int][1]
  209. b = (1.0 - alpha) * colors[index_int][2]
  210. if flat:
  211. palette.extend((int(r), int(g), int(b)))
  212. else:
  213. palette.append((int(r), int(g), int(b)))
  214. return palette
  215. def desaturate(rgb, amount):
  216. """
  217. desaturate colors by amount
  218. amount == 0, no change
  219. amount == 1, grey
  220. """
  221. luminosity = sum(rgb) / 3.0
  222. desat = lambda color: color - amount * (color - luminosity)
  223. return tuple(map(int, map(desat, rgb)))
  224. class WaveformImage(object):
  225. """
  226. Given peaks and spectral centroids from the AudioProcessor, this class will construct
  227. a wavefile image which can be saved as PNG.
  228. """
  229. def __init__(self, image_width, image_height, palette=1):
  230. if image_height % 2 == 0:
  231. raise AudioProcessingException("Height should be uneven: images look much better at uneven height")
  232. if palette == 1:
  233. background_color = (0,0,0)
  234. colors = [
  235. (50,0,200),
  236. (0,220,80),
  237. (255,224,0),
  238. (255,70,0),
  239. ]
  240. elif palette == 2:
  241. background_color = (0,0,0)
  242. colors = [self.color_from_value(value/29.0) for value in range(0,30)]
  243. elif palette == 3:
  244. background_color = (213, 217, 221)
  245. colors = map( partial(desaturate, amount=0.7), [
  246. (50,0,200),
  247. (0,220,80),
  248. (255,224,0),
  249. ])
  250. elif palette == 4:
  251. background_color = (213, 217, 221)
  252. colors = map( partial(desaturate, amount=0.8), [self.color_from_value(value/29.0) for value in range(0,30)])
  253. self.image = Image.new("RGB", (image_width, image_height), background_color)
  254. self.image_width = image_width
  255. self.image_height = image_height
  256. self.draw = ImageDraw.Draw(self.image)
  257. self.previous_x, self.previous_y = None, None
  258. self.color_lookup = interpolate_colors(colors)
  259. self.pix = self.image.load()
  260. def color_from_value(self, value):
  261. """ given a value between 0 and 1, return an (r,g,b) tuple """
  262. return ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (int( (1.0 - value) * 360 ), 80, 50))
  263. def draw_peaks(self, x, peaks, spectral_centroid):
  264. """ draw 2 peaks at x using the spectral_centroid for color """
  265. y1 = self.image_height * 0.5 - peaks[0] * (self.image_height - 4) * 0.5
  266. y2 = self.image_height * 0.5 - peaks[1] * (self.image_height - 4) * 0.5
  267. line_color = self.color_lookup[int(spectral_centroid*255.0)]
  268. if self.previous_y != None:
  269. self.draw.line([self.previous_x, self.previous_y, x, y1, x, y2], line_color)
  270. else:
  271. self.draw.line([x, y1, x, y2], line_color)
  272. self.previous_x, self.previous_y = x, y2
  273. self.draw_anti_aliased_pixels(x, y1, y2, line_color)
  274. def draw_anti_aliased_pixels(self, x, y1, y2, color):
  275. """ vertical anti-aliasing at y1 and y2 """
  276. y_max = max(y1, y2)
  277. y_max_int = int(y_max)
  278. alpha = y_max - y_max_int
  279. if alpha > 0.0 and alpha < 1.0 and y_max_int + 1 < self.image_height:
  280. current_pix = self.pix[x, y_max_int + 1]
  281. r = int((1-alpha)*current_pix[0] + alpha*color[0])
  282. g = int((1-alpha)*current_pix[1] + alpha*color[1])
  283. b = int((1-alpha)*current_pix[2] + alpha*color[2])
  284. self.pix[x, y_max_int + 1] = (r,g,b)
  285. y_min = min(y1, y2)
  286. y_min_int = int(y_min)
  287. alpha = 1.0 - (y_min - y_min_int)
  288. if alpha > 0.0 and alpha < 1.0 and y_min_int - 1 >= 0:
  289. current_pix = self.pix[x, y_min_int - 1]
  290. r = int((1-alpha)*current_pix[0] + alpha*color[0])
  291. g = int((1-alpha)*current_pix[1] + alpha*color[1])
  292. b = int((1-alpha)*current_pix[2] + alpha*color[2])
  293. self.pix[x, y_min_int - 1] = (r,g,b)
  294. def save(self, filename):
  295. # draw a zero "zero" line
  296. a = 25
  297. for x in range(self.image_width):
  298. self.pix[x, self.image_height/2] = tuple(map(lambda p: p+a, self.pix[x, self.image_height/2]))
  299. self.image.save(filename)
  300. class SpectrogramImage(object):
  301. """
  302. Given spectra from the AudioProcessor, this class will construct a wavefile image which
  303. can be saved as PNG.
  304. """
  305. def __init__(self, image_width, image_height, fft_size):
  306. self.image_width = image_width
  307. self.image_height = image_height
  308. self.fft_size = fft_size
  309. self.image = Image.new("RGBA", (image_height, image_width))
  310. colors = [
  311. (0, 0, 0, 0),
  312. (58/4, 68/4, 65/4, 255),
  313. (80/2, 100/2, 153/2, 255),
  314. (90, 180, 100, 255),
  315. (224, 224, 44, 255),
  316. (255, 60, 30, 255),
  317. (255, 255, 255, 255)
  318. ]
  319. self.palette = interpolate_colors(colors)
  320. # generate the lookup which translates y-coordinate to fft-bin
  321. self.y_to_bin = []
  322. f_min = 100.0
  323. f_max = 22050.0
  324. y_min = math.log10(f_min)
  325. y_max = math.log10(f_max)
  326. for y in range(self.image_height):
  327. freq = math.pow(10.0, y_min + y / (image_height - 1.0) *(y_max - y_min))
  328. bin = freq / 22050.0 * (self.fft_size/2 + 1)
  329. if bin < self.fft_size/2:
  330. alpha = bin - int(bin)
  331. self.y_to_bin.append((int(bin), alpha * 255))
  332. # this is a bit strange, but using image.load()[x,y] = ... is
  333. # a lot slower than using image.putadata and then rotating the image
  334. # so we store all the pixels in an array and then create the image when saving
  335. self.pixels = []
  336. def draw_spectrum(self, x, spectrum):
  337. # for all frequencies, draw the pixels
  338. for (index, alpha) in self.y_to_bin:
  339. self.pixels.append( self.palette[int((255.0-alpha) * spectrum[index] + alpha * spectrum[index + 1])] )
  340. # if the FFT is too small to fill up the image, fill with black to the top
  341. for y in range(len(self.y_to_bin), self.image_height): #@UnusedVariable
  342. self.pixels.append(self.palette[0])
  343. def save(self, filename, quality=80):
  344. assert filename.lower().endswith(".jpg")
  345. self.image.putdata(self.pixels)
  346. self.image.transpose(Image.ROTATE_90).save(filename, quality=quality)
  347. def create_wave_images(input_filename, output_filename_w, output_filename_s, image_width, image_height, fft_size, progress_callback=None):
  348. """
  349. Utility function for creating both wavefile and spectrum images from an audio input file.
  350. """
  351. processor = AudioProcessor(input_filename, fft_size, numpy.hanning)
  352. samples_per_pixel = processor.audio_file.nframes / float(image_width)
  353. waveform = WaveformImage(image_width, image_height)
  354. spectrogram = SpectrogramImage(image_width, image_height, fft_size)
  355. for x in range(image_width):
  356. if progress_callback and x % (image_width/10) == 0:
  357. progress_callback((x*100)/image_width)
  358. seek_point = int(x * samples_per_pixel)
  359. next_seek_point = int((x + 1) * samples_per_pixel)
  360. (spectral_centroid, db_spectrum) = processor.spectral_centroid(seek_point)
  361. peaks = processor.peaks(seek_point, next_seek_point)
  362. waveform.draw_peaks(x, peaks, spectral_centroid)
  363. spectrogram.draw_spectrum(x, db_spectrum)
  364. if progress_callback:
  365. progress_callback(100)
  366. waveform.save(output_filename_w)
  367. spectrogram.save(output_filename_s)
  368. class NoSpaceLeftException(Exception):
  369. pass
  370. def convert_to_pcm(input_filename, output_filename):
  371. """
  372. converts any audio file type to pcm audio
  373. """
  374. if not os.path.exists(input_filename):
  375. raise AudioProcessingException("file %s does not exist" % input_filename)
  376. sound_type = get_sound_type(input_filename)
  377. if sound_type == "mp3":
  378. cmd = ["lame", "--decode", input_filename, output_filename]
  379. elif sound_type == "ogg":
  380. cmd = ["oggdec", input_filename, "-o", output_filename]
  381. elif sound_type == "flac":
  382. cmd = ["flac", "-f", "-d", "-s", "-o", output_filename, input_filename]
  383. else:
  384. return False
  385. process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  386. (stdout, stderr) = process.communicate()
  387. if process.returncode != 0 or not os.path.exists(output_filename):
  388. if "No space left on device" in stderr + " " + stdout:
  389. raise NoSpaceLeftException
  390. raise AudioProcessingException("failed converting to pcm data:\n" + " ".join(cmd) + "\n" + stderr + "\n" + stdout)
  391. return True
  392. def stereofy_and_find_info(stereofy_executble_path, input_filename, output_filename):
  393. """
  394. converts a pcm wave file to two channel, 16 bit integer
  395. """
  396. if not os.path.exists(input_filename):
  397. raise AudioProcessingException("file %s does not exist" % input_filename)
  398. cmd = [stereofy_executble_path, "--input", input_filename, "--output", output_filename]
  399. process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  400. (stdout, stderr) = process.communicate()
  401. if process.returncode != 0 or not os.path.exists(output_filename):
  402. if "No space left on device" in stderr + " " + stdout:
  403. raise NoSpaceLeftException
  404. raise AudioProcessingException("failed calling stereofy data:\n" + " ".join(cmd) + "\n" + stderr + "\n" + stdout)
  405. stdout = (stdout + " " + stderr).replace("\n", " ")
  406. duration = 0
  407. m = re.match(r".*#duration (?P<duration>[\d\.]+).*", stdout)
  408. if m != None:
  409. duration = float(m.group("duration"))
  410. channels = 0
  411. m = re.match(r".*#channels (?P<channels>\d+).*", stdout)
  412. if m != None:
  413. channels = float(m.group("channels"))
  414. samplerate = 0
  415. m = re.match(r".*#samplerate (?P<samplerate>\d+).*", stdout)
  416. if m != None:
  417. samplerate = float(m.group("samplerate"))
  418. bitdepth = None
  419. m = re.match(r".*#bitdepth (?P<bitdepth>\d+).*", stdout)
  420. if m != None:
  421. bitdepth = float(m.group("bitdepth"))
  422. bitrate = (os.path.getsize(input_filename) * 8.0) / 1024.0 / duration if duration > 0 else 0
  423. return dict(duration=duration, channels=channels, samplerate=samplerate, bitrate=bitrate, bitdepth=bitdepth)
  424. def convert_to_mp3(input_filename, output_filename, quality=70):
  425. """
  426. converts the incoming wave file to a mp3 file
  427. """
  428. if not os.path.exists(input_filename):
  429. raise AudioProcessingException("file %s does not exist" % input_filename)
  430. command = ["lame", "--silent", "--abr", str(quality), input_filename, output_filename]
  431. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  432. (stdout, stderr) = process.communicate()
  433. if process.returncode != 0 or not os.path.exists(output_filename):
  434. raise AudioProcessingException(stdout)
  435. def convert_to_ogg(input_filename, output_filename, quality=1):
  436. """
  437. converts the incoming wave file to n ogg file
  438. """
  439. if not os.path.exists(input_filename):
  440. raise AudioProcessingException("file %s does not exist" % input_filename)
  441. command = ["oggenc", "-q", str(quality), input_filename, "-o", output_filename]
  442. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  443. (stdout, stderr) = process.communicate()
  444. if process.returncode != 0 or not os.path.exists(output_filename):
  445. raise AudioProcessingException(stdout)
  446. def convert_using_ffmpeg(input_filename, output_filename):
  447. """
  448. converts the incoming wave file to stereo pcm using fffmpeg
  449. """
  450. TIMEOUT = 3 * 60
  451. def alarm_handler(signum, frame):
  452. raise AudioProcessingException("timeout while waiting for ffmpeg")
  453. if not os.path.exists(input_filename):
  454. raise AudioProcessingException("file %s does not exist" % input_filename)
  455. command = ["ffmpeg", "-y", "-i", input_filename, "-ac","1","-acodec", "pcm_s16le", "-ar", "44100", output_filename]
  456. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  457. signal.signal(signal.SIGALRM,alarm_handler)
  458. signal.alarm(TIMEOUT)
  459. (stdout, stderr) = process.communicate()
  460. signal.alarm(0)
  461. if process.returncode != 0 or not os.path.exists(output_filename):
  462. raise AudioProcessingException(stdout)