annotate BeatRootProcessor.h @ 2:7d4e6b1ff3d1

Minor further updates
author Chris Cannam
date Fri, 17 Jun 2011 18:17:16 +0100
parents 791398eaf639
children a821f49c42f0
rev   line source
Chris@1 1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
Chris@1 2
Chris@1 3 /*
Chris@1 4 Vamp feature extraction plugin for the BeatRoot beat tracker.
Chris@1 5
Chris@1 6 Centre for Digital Music, Queen Mary, University of London.
Chris@1 7 This file copyright 2011 Simon Dixon, Chris Cannam and QMUL.
Chris@1 8
Chris@1 9 This program is free software; you can redistribute it and/or
Chris@1 10 modify it under the terms of the GNU General Public License as
Chris@1 11 published by the Free Software Foundation; either version 2 of the
Chris@1 12 License, or (at your option) any later version. See the file
Chris@1 13 COPYING included with this distribution for more information.
Chris@1 14 */
Chris@1 15
Chris@1 16 #ifndef _BEATROOT_PROCESSOR_H_
Chris@1 17 #define _BEATROOT_PROCESSOR_H_
Chris@1 18
Chris@2 19 #include <vector>
Chris@2 20
Chris@2 21 using std::vector;
Chris@2 22
Chris@1 23 class BeatRootProcessor
Chris@1 24 {
Chris@1 25 protected:
Chris@1 26 /** Sample rate of audio */
Chris@1 27 float sampleRate;
Chris@1 28
Chris@1 29 /** Spacing of audio frames (determines the amount of overlap or
Chris@1 30 * skip between frames). This value is expressed in
Chris@1 31 * seconds. (Default = 0.020s) */
Chris@1 32 double hopTime;
Chris@1 33
Chris@1 34 /** The approximate size of an FFT frame in seconds. (Default =
Chris@1 35 * 0.04644s). The value is adjusted so that <code>fftSize</code>
Chris@1 36 * is always power of 2. */
Chris@1 37 double fftTime;
Chris@1 38
Chris@1 39 /** Spacing of audio frames in samples (see <code>hopTime</code>) */
Chris@1 40 int hopSize;
Chris@1 41
Chris@1 42 /** The size of an FFT frame in samples (see <code>fftTime</code>) */
Chris@1 43 int fftSize;
Chris@1 44
Chris@1 45 /** The number of overlapping frames of audio data which have been read. */
Chris@1 46 int frameCount;
Chris@1 47
Chris@1 48 /** RMS amplitude of the current frame. */
Chris@1 49 double frameRMS;
Chris@1 50
Chris@1 51 /** Long term average frame energy (in frequency domain representation). */
Chris@1 52 double ltAverage;
Chris@1 53
Chris@1 54 /** Spectral flux onset detection function, indexed by frame. */
Chris@1 55 vector<int> spectralFlux;
Chris@1 56
Chris@1 57 /** A mapping function for mapping FFT bins to final frequency bins.
Chris@1 58 * The mapping is linear (1-1) until the resolution reaches 2 points per
Chris@1 59 * semitone, then logarithmic with a semitone resolution. e.g. for
Chris@1 60 * 44.1kHz sampling rate and fftSize of 2048 (46ms), bin spacing is
Chris@1 61 * 21.5Hz, which is mapped linearly for bins 0-34 (0 to 732Hz), and
Chris@1 62 * logarithmically for the remaining bins (midi notes 79 to 127, bins 35 to
Chris@1 63 * 83), where all energy above note 127 is mapped into the final bin. */
Chris@1 64 vector<int> freqMap;
Chris@1 65
Chris@1 66 /** The number of entries in <code>freqMap</code>. Note that the length of
Chris@1 67 * the array is greater, because its size is not known at creation time. */
Chris@1 68 int freqMapSize;
Chris@1 69
Chris@1 70 /** The magnitude spectrum of the most recent frame. Used for
Chris@1 71 * calculating the spectral flux. */
Chris@1 72 vector<double> prevFrame;
Chris@1 73
Chris@1 74 /** The magnitude spectrum of the current frame. */
Chris@1 75 vector<double> newFrame;
Chris@1 76
Chris@1 77 /** The magnitude spectra of all frames, used for plotting the spectrogram. */
Chris@1 78 vector<vector<double> > frames; //!!! do we need this? much cheaper to lose it if we don't
Chris@1 79
Chris@1 80 /** The RMS energy of all frames. */
Chris@1 81 vector<double> energy; //!!! unused in beat tracking?
Chris@1 82
Chris@1 83 /** The estimated onset times from peak-picking the onset
Chris@1 84 * detection function(s). */
Chris@1 85 vector<double> onsets;
Chris@1 86
Chris@1 87 /** The estimated onset times and their saliences. */
Chris@1 88 //!!!EventList onsetList;
Chris@1 89 vector<double> onsetList; //!!! corresponding to keyDown member of events in list
Chris@1 90
Chris@1 91 /** Total number of audio frames if known, or -1 for live or compressed input. */
Chris@1 92 int totalFrames;
Chris@1 93
Chris@1 94 /** Flag for enabling or disabling debugging output */
Chris@2 95 static bool debug;
Chris@1 96
Chris@1 97 /** Flag for suppressing all standard output messages except results. */
Chris@2 98 static bool silent;
Chris@1 99
Chris@1 100 /** RMS frame energy below this value results in the frame being
Chris@1 101 * set to zero, so that normalisation does not have undesired
Chris@1 102 * side-effects. */
Chris@2 103 static double silenceThreshold; //!!!??? energy of what? should not be static?
Chris@1 104
Chris@1 105 /** For dynamic range compression, this value is added to the log
Chris@1 106 * magnitude in each frequency bin and any remaining negative
Chris@1 107 * values are then set to zero.
Chris@1 108 */
Chris@2 109 static double rangeThreshold; //!!! sim
Chris@1 110
Chris@1 111 /** Determines method of normalisation. Values can be:<ul>
Chris@1 112 * <li>0: no normalisation</li>
Chris@1 113 * <li>1: normalisation by current frame energy</li>
Chris@1 114 * <li>2: normalisation by exponential average of frame energy</li>
Chris@1 115 * </ul>
Chris@1 116 */
Chris@2 117 static int normaliseMode;
Chris@1 118
Chris@1 119 /** Ratio between rate of sampling the signal energy (for the
Chris@1 120 * amplitude envelope) and the hop size */
Chris@2 121 static int energyOversampleFactor; //!!! not used?
Chris@1 122
Chris@1 123 public:
Chris@1 124
Chris@1 125 /** Constructor: note that streams are not opened until the input
Chris@1 126 * file is set (see <code>setInputFile()</code>). */
Chris@2 127 BeatRootProcessor() {
Chris@1 128 cbIndex = 0;
Chris@1 129 frameRMS = 0;
Chris@1 130 ltAverage = 0;
Chris@1 131 frameCount = 0;
Chris@1 132 hopSize = 0;
Chris@1 133 fftSize = 0;
Chris@1 134 hopTime = 0.010; // DEFAULT, overridden with -h
Chris@1 135 fftTime = 0.04644; // DEFAULT, overridden with -f
Chris@1 136 } // constructor
Chris@1 137
Chris@2 138 protected:
Chris@1 139 /** Allocates memory for arrays, based on parameter settings */
Chris@2 140 void init() {
Chris@1 141 hopSize = (int) Math.round(sampleRate * hopTime);
Chris@1 142 fftSize = (int) Math.round(Math.pow(2,
Chris@1 143 Math.round( Math.log(fftTime * sampleRate) / Math.log(2))));
Chris@1 144 makeFreqMap(fftSize, sampleRate);
Chris@1 145 int buffSize = hopSize * channels * 2;
Chris@1 146 if ((inputBuffer == null) || (inputBuffer.length != buffSize))
Chris@1 147 inputBuffer = new byte[buffSize];
Chris@1 148 if ((circBuffer == null) || (circBuffer.length != fftSize)) {
Chris@1 149 circBuffer = new double[fftSize];
Chris@1 150 reBuffer = new double[fftSize];
Chris@1 151 imBuffer = new double[fftSize];
Chris@1 152 prevPhase = new double[fftSize];
Chris@1 153 prevPrevPhase = new double[fftSize];
Chris@1 154 prevFrame = new double[fftSize];
Chris@1 155 window = FFT.makeWindow(FFT.HAMMING, fftSize, fftSize);
Chris@1 156 for (int i=0; i < fftSize; i++)
Chris@1 157 window[i] *= Math.sqrt(fftSize);
Chris@1 158 }
Chris@1 159 if (pcmInputStream == rawInputStream)
Chris@1 160 totalFrames = (int)(pcmInputStream.getFrameLength() / hopSize);
Chris@1 161 else
Chris@1 162 totalFrames = (int) (MAX_LENGTH / hopTime);
Chris@1 163 if ((newFrame == null) || (newFrame.length != freqMapSize)) {
Chris@1 164 newFrame = new double[freqMapSize];
Chris@1 165 frames = new double[totalFrames][freqMapSize];
Chris@1 166 } else if (frames.length != totalFrames)
Chris@1 167 frames = new double[totalFrames][freqMapSize];
Chris@1 168 energy = new double[totalFrames*energyOversampleFactor];
Chris@1 169 phaseDeviation = new double[totalFrames];
Chris@1 170 spectralFlux = new double[totalFrames];
Chris@1 171 frameCount = 0;
Chris@1 172 cbIndex = 0;
Chris@1 173 frameRMS = 0;
Chris@1 174 ltAverage = 0;
Chris@1 175 } // init()
Chris@1 176
Chris@1 177 /** Closes the input stream(s) associated with this object. */
Chris@2 178 void closeStreams() {
Chris@1 179 if (pcmInputStream != null) {
Chris@1 180 try {
Chris@1 181 pcmInputStream.close();
Chris@1 182 if (pcmInputStream != rawInputStream)
Chris@1 183 rawInputStream.close();
Chris@1 184 if (audioOut != null) {
Chris@1 185 audioOut.drain();
Chris@1 186 audioOut.close();
Chris@1 187 }
Chris@1 188 } catch (Exception e) {}
Chris@1 189 pcmInputStream = null;
Chris@1 190 audioOut = null;
Chris@1 191 }
Chris@1 192 } // closeStreams()
Chris@1 193
Chris@1 194 /** Creates a map of FFT frequency bins to comparison bins.
Chris@1 195 * Where the spacing of FFT bins is less than 0.5 semitones, the mapping is
Chris@1 196 * one to one. Where the spacing is greater than 0.5 semitones, the FFT
Chris@1 197 * energy is mapped into semitone-wide bins. No scaling is performed; that
Chris@1 198 * is the energy is summed into the comparison bins. See also
Chris@1 199 * processFrame()
Chris@1 200 */
Chris@2 201 void makeFreqMap(int fftSize, float sampleRate) {
Chris@1 202 freqMap = new int[fftSize/2+1];
Chris@1 203 double binWidth = sampleRate / fftSize;
Chris@1 204 int crossoverBin = (int)(2 / (Math.pow(2, 1/12.0) - 1));
Chris@1 205 int crossoverMidi = (int)Math.round(Math.log(crossoverBin*binWidth/440)/
Chris@1 206 Math.log(2) * 12 + 69);
Chris@1 207 // freq = 440 * Math.pow(2, (midi-69)/12.0) / binWidth;
Chris@1 208 int i = 0;
Chris@1 209 while (i <= crossoverBin)
Chris@1 210 freqMap[i++] = i;
Chris@1 211 while (i <= fftSize/2) {
Chris@1 212 double midi = Math.log(i*binWidth/440) / Math.log(2) * 12 + 69;
Chris@1 213 if (midi > 127)
Chris@1 214 midi = 127;
Chris@1 215 freqMap[i++] = crossoverBin + (int)Math.round(midi) - crossoverMidi;
Chris@1 216 }
Chris@1 217 freqMapSize = freqMap[i-1] + 1;
Chris@1 218 } // makeFreqMap()
Chris@1 219
Chris@1 220 /** Calculates the weighted phase deviation onset detection function.
Chris@1 221 * Not used.
Chris@1 222 * TODO: Test the change to WPD fn */
Chris@2 223 void weightedPhaseDeviation() {
Chris@1 224 if (frameCount < 2)
Chris@1 225 phaseDeviation[frameCount] = 0;
Chris@1 226 else {
Chris@1 227 for (int i = 0; i < fftSize; i++) {
Chris@1 228 double pd = imBuffer[i] - 2 * prevPhase[i] + prevPrevPhase[i];
Chris@1 229 double pd1 = Math.abs(Math.IEEEremainder(pd, 2 * Math.PI));
Chris@1 230 phaseDeviation[frameCount] += pd1 * reBuffer[i];
Chris@1 231 // System.err.printf("%7.3f %7.3f\n", pd/Math.PI, pd1/Math.PI);
Chris@1 232 }
Chris@1 233 }
Chris@1 234 phaseDeviation[frameCount] /= fftSize * Math.PI;
Chris@1 235 double[] tmp = prevPrevPhase;
Chris@1 236 prevPrevPhase = prevPhase;
Chris@1 237 prevPhase = imBuffer;
Chris@1 238 imBuffer = tmp;
Chris@1 239 } // weightedPhaseDeviation()
Chris@1 240
Chris@1 241 /** Reads a frame of input data, averages the channels to mono, scales
Chris@1 242 * to a maximum possible absolute value of 1, and stores the audio data
Chris@1 243 * in a circular input buffer.
Chris@1 244 * @return true if a frame (or part of a frame, if it is the final frame)
Chris@1 245 * is read. If a complete frame cannot be read, the InputStream is set
Chris@1 246 * to null.
Chris@1 247 */
Chris@2 248 bool getFrame() {
Chris@1 249 if (pcmInputStream == null)
Chris@1 250 return false;
Chris@1 251 try {
Chris@1 252 int bytesRead = (int) pcmInputStream.read(inputBuffer);
Chris@1 253 if ((audioOut != null) && (bytesRead > 0))
Chris@1 254 if (audioOut.write(inputBuffer, 0, bytesRead) != bytesRead)
Chris@1 255 System.err.println("Error writing to audio device");
Chris@1 256 if (bytesRead < inputBuffer.length) {
Chris@1 257 if (!silent)
Chris@1 258 System.err.println("End of input: " + audioFileName);
Chris@1 259 closeStreams();
Chris@1 260 return false;
Chris@1 261 }
Chris@1 262 } catch (IOException e) {
Chris@1 263 e.printStackTrace();
Chris@1 264 closeStreams();
Chris@1 265 return false;
Chris@1 266 }
Chris@1 267 frameRMS = 0;
Chris@1 268 double sample;
Chris@1 269 switch(channels) {
Chris@1 270 case 1:
Chris@1 271 for (int i = 0; i < inputBuffer.length; i += 2) {
Chris@1 272 sample = ((inputBuffer[i+1]<<8) |
Chris@1 273 (inputBuffer[i]&0xff)) / 32768.0;
Chris@1 274 frameRMS += sample * sample;
Chris@1 275 circBuffer[cbIndex++] = sample;
Chris@1 276 if (cbIndex == fftSize)
Chris@1 277 cbIndex = 0;
Chris@1 278 }
Chris@1 279 break;
Chris@1 280 case 2: // saves ~0.1% of RT (total input overhead ~0.4%) :)
Chris@1 281 for (int i = 0; i < inputBuffer.length; i += 4) {
Chris@1 282 sample = (((inputBuffer[i+1]<<8) | (inputBuffer[i]&0xff)) +
Chris@1 283 ((inputBuffer[i+3]<<8) | (inputBuffer[i+2]&0xff)))
Chris@1 284 / 65536.0;
Chris@1 285 frameRMS += sample * sample;
Chris@1 286 circBuffer[cbIndex++] = sample;
Chris@1 287 if (cbIndex == fftSize)
Chris@1 288 cbIndex = 0;
Chris@1 289 }
Chris@1 290 break;
Chris@1 291 default:
Chris@1 292 for (int i = 0; i < inputBuffer.length; ) {
Chris@1 293 sample = 0;
Chris@1 294 for (int j = 0; j < channels; j++, i+=2)
Chris@1 295 sample += (inputBuffer[i+1]<<8) | (inputBuffer[i]&0xff);
Chris@1 296 sample /= 32768.0 * channels;
Chris@1 297 frameRMS += sample * sample;
Chris@1 298 circBuffer[cbIndex++] = sample;
Chris@1 299 if (cbIndex == fftSize)
Chris@1 300 cbIndex = 0;
Chris@1 301 }
Chris@1 302 }
Chris@1 303 frameRMS = Math.sqrt(frameRMS / inputBuffer.length * 2 * channels);
Chris@1 304 return true;
Chris@1 305 } // getFrame()
Chris@1 306
Chris@1 307 /** Processes a frame of audio data by first computing the STFT with a
Chris@1 308 * Hamming window, then mapping the frequency bins into a part-linear
Chris@1 309 * part-logarithmic array, then computing the spectral flux
Chris@1 310 * then (optionally) normalising and calculating onsets.
Chris@1 311 */
Chris@2 312 void processFrame() {
Chris@1 313 if (getFrame()) {
Chris@1 314 for (int i = 0; i < fftSize; i++) {
Chris@1 315 reBuffer[i] = window[i] * circBuffer[cbIndex];
Chris@1 316 if (++cbIndex == fftSize)
Chris@1 317 cbIndex = 0;
Chris@1 318 }
Chris@1 319 Arrays.fill(imBuffer, 0);
Chris@1 320 FFT.magnitudePhaseFFT(reBuffer, imBuffer);
Chris@1 321 Arrays.fill(newFrame, 0);
Chris@1 322 double flux = 0;
Chris@1 323 for (int i = 0; i <= fftSize/2; i++) {
Chris@1 324 if (reBuffer[i] > prevFrame[i])
Chris@1 325 flux += reBuffer[i] - prevFrame[i];
Chris@1 326 newFrame[freqMap[i]] += reBuffer[i];
Chris@1 327 }
Chris@1 328 spectralFlux[frameCount] = flux;
Chris@1 329 for (int i = 0; i < freqMapSize; i++)
Chris@1 330 frames[frameCount][i] = newFrame[i];
Chris@1 331 int index = cbIndex - (fftSize - hopSize);
Chris@1 332 if (index < 0)
Chris@1 333 index += fftSize;
Chris@1 334 int sz = (fftSize - hopSize) / energyOversampleFactor;
Chris@1 335 for (int j = 0; j < energyOversampleFactor; j++) {
Chris@1 336 double newEnergy = 0;
Chris@1 337 for (int i = 0; i < sz; i++) {
Chris@1 338 newEnergy += circBuffer[index] * circBuffer[index];
Chris@1 339 if (++index == fftSize)
Chris@1 340 index = 0;
Chris@1 341 }
Chris@1 342 energy[frameCount * energyOversampleFactor + j] =
Chris@1 343 newEnergy / sz <= 1e-6? 0: Math.log(newEnergy / sz) + 13.816;
Chris@1 344 }
Chris@1 345 double decay = frameCount >= 200? 0.99:
Chris@1 346 (frameCount < 100? 0: (frameCount - 100) / 100.0);
Chris@1 347 if (ltAverage == 0)
Chris@1 348 ltAverage = frameRMS;
Chris@1 349 else
Chris@1 350 ltAverage = ltAverage * decay + frameRMS * (1.0 - decay);
Chris@1 351 if (frameRMS <= silenceThreshold)
Chris@1 352 for (int i = 0; i < freqMapSize; i++)
Chris@1 353 frames[frameCount][i] = 0;
Chris@1 354 else {
Chris@1 355 if (normaliseMode == 1)
Chris@1 356 for (int i = 0; i < freqMapSize; i++)
Chris@1 357 frames[frameCount][i] /= frameRMS;
Chris@1 358 else if (normaliseMode == 2)
Chris@1 359 for (int i = 0; i < freqMapSize; i++)
Chris@1 360 frames[frameCount][i] /= ltAverage;
Chris@1 361 for (int i = 0; i < freqMapSize; i++) {
Chris@1 362 frames[frameCount][i] = Math.log(frames[frameCount][i]) + rangeThreshold;
Chris@1 363 if (frames[frameCount][i] < 0)
Chris@1 364 frames[frameCount][i] = 0;
Chris@1 365 }
Chris@1 366 }
Chris@1 367 // weightedPhaseDeviation();
Chris@1 368 // if (debug)
Chris@1 369 // System.err.printf("PhaseDev: t=%7.3f phDev=%7.3f RMS=%7.3f\n",
Chris@1 370 // frameCount * hopTime,
Chris@1 371 // phaseDeviation[frameCount],
Chris@1 372 // frameRMS);
Chris@1 373 double[] tmp = prevFrame;
Chris@1 374 prevFrame = reBuffer;
Chris@1 375 reBuffer = tmp;
Chris@1 376 frameCount++;
Chris@1 377 if ((frameCount % 100) == 0) {
Chris@1 378 if (!silent) {
Chris@1 379 System.err.printf("Progress: %1d %5.3f %5.3f\n",
Chris@1 380 frameCount, frameRMS, ltAverage);
Chris@1 381 Profile.report();
Chris@1 382 }
Chris@1 383 if ((progressCallback != null) && (totalFrames > 0))
Chris@1 384 progressCallback.setFraction((double)frameCount/totalFrames);
Chris@1 385 }
Chris@1 386 }
Chris@1 387 } // processFrame()
Chris@1 388
Chris@1 389 /** Processes a complete file of audio data. */
Chris@2 390 void processFile() {
Chris@1 391 while (pcmInputStream != null) {
Chris@1 392 // Profile.start(0);
Chris@1 393 processFrame();
Chris@1 394 // Profile.log(0);
Chris@1 395 if (Thread.currentThread().isInterrupted()) {
Chris@1 396 System.err.println("info: INTERRUPTED in processFile()");
Chris@1 397 return;
Chris@1 398 }
Chris@1 399 }
Chris@1 400
Chris@1 401 // double[] x1 = new double[phaseDeviation.length];
Chris@1 402 // for (int i = 0; i < x1.length; i++) {
Chris@1 403 // x1[i] = i * hopTime;
Chris@1 404 // phaseDeviation[i] = (phaseDeviation[i] - 0.4) * 100;
Chris@1 405 // }
Chris@1 406 // double[] x2 = new double[energy.length];
Chris@1 407 // for (int i = 0; i < x2.length; i++)
Chris@1 408 // x2[i] = i * hopTime / energyOversampleFactor;
Chris@1 409 // // plot.clear();
Chris@1 410 // plot.addPlot(x1, phaseDeviation, Color.green, 7);
Chris@1 411 // plot.addPlot(x2, energy, Color.red, 7);
Chris@1 412 // plot.setTitle("Test phase deviation");
Chris@1 413 // plot.fitAxes();
Chris@1 414
Chris@1 415 // double[] slope = new double[energy.length];
Chris@1 416 // double hop = hopTime / energyOversampleFactor;
Chris@1 417 // Peaks.getSlope(energy, hop, 15, slope);
Chris@1 418 // LinkedList<Integer> peaks = Peaks.findPeaks(slope, (int)Math.round(0.06 / hop), 10);
Chris@1 419
Chris@1 420 double hop = hopTime;
Chris@1 421 Peaks.normalise(spectralFlux);
Chris@1 422 LinkedList<Integer> peaks = Peaks.findPeaks(spectralFlux, (int)Math.round(0.06 / hop), 0.35, 0.84, true);
Chris@1 423 onsets = new double[peaks.size()];
Chris@1 424 double[] y2 = new double[onsets.length];
Chris@1 425 Iterator<Integer> it = peaks.iterator();
Chris@1 426 onsetList = new EventList();
Chris@1 427 double minSalience = Peaks.min(spectralFlux);
Chris@1 428 for (int i = 0; i < onsets.length; i++) {
Chris@1 429 int index = it.next();
Chris@1 430 onsets[i] = index * hop;
Chris@1 431 y2[i] = spectralFlux[index];
Chris@1 432 Event e = BeatTrackDisplay.newBeat(onsets[i], 0);
Chris@1 433 // if (debug)
Chris@1 434 // System.err.printf("Onset: %8.3f %8.3f %8.3f\n",
Chris@1 435 // onsets[i], energy[index], slope[index]);
Chris@1 436 // e.salience = slope[index]; // or combination of energy + slope??
Chris@1 437 // Note that salience must be non-negative or the beat tracking system fails!
Chris@1 438 e.salience = spectralFlux[index] - minSalience;
Chris@1 439 onsetList.add(e);
Chris@1 440 }
Chris@1 441 if (progressCallback != null)
Chris@1 442 progressCallback.setFraction(1.0);
Chris@1 443 if (doOnsetPlot) {
Chris@1 444 double[] x1 = new double[spectralFlux.length];
Chris@1 445 for (int i = 0; i < x1.length; i++)
Chris@1 446 x1[i] = i * hopTime;
Chris@1 447 plot.addPlot(x1, spectralFlux, Color.red, 4);
Chris@1 448 plot.addPlot(onsets, y2, Color.green, 3);
Chris@1 449 plot.setTitle("Spectral flux and onsets");
Chris@1 450 plot.fitAxes();
Chris@1 451 }
Chris@1 452 if (debug) {
Chris@1 453 System.err.printf("Onsets: %d\nContinue? ", onsets.length);
Chris@1 454 readLine();
Chris@1 455 }
Chris@1 456 } // processFile()
Chris@1 457
Chris@1 458 /** Reads a text file containing a list of whitespace-separated feature values.
Chris@1 459 * Created for paper submitted to ICASSP'07.
Chris@1 460 * @param fileName File containing the data
Chris@1 461 * @return An array containing the feature values
Chris@1 462 */
Chris@2 463 static double[] getFeatures(String fileName) {
Chris@1 464 ArrayList<Double> l = new ArrayList<Double>();
Chris@1 465 try {
Chris@1 466 BufferedReader b = new BufferedReader(new FileReader(fileName));
Chris@1 467 while (true) {
Chris@1 468 String s = b.readLine();
Chris@1 469 if (s == null)
Chris@1 470 break;
Chris@1 471 int start = 0;
Chris@1 472 while (start < s.length()) {
Chris@1 473 int len = s.substring(start).indexOf(' ');
Chris@1 474 String t = null;
Chris@1 475 if (len < 0)
Chris@1 476 t = s.substring(start);
Chris@1 477 else if (len > 0) {
Chris@1 478 t = s.substring(start, start + len);
Chris@1 479 }
Chris@1 480 if (t != null)
Chris@1 481 try {
Chris@1 482 l.add(Double.parseDouble(t));
Chris@1 483 } catch (NumberFormatException e) {
Chris@1 484 System.err.println(e);
Chris@1 485 if (l.size() == 0)
Chris@1 486 l.add(new Double(0));
Chris@1 487 else
Chris@1 488 l.add(new Double(l.get(l.size()-1)));
Chris@1 489 }
Chris@1 490 start += len + 1;
Chris@1 491 if (len < 0)
Chris@1 492 break;
Chris@1 493 }
Chris@1 494 }
Chris@1 495 double[] features = new double[l.size()];
Chris@1 496 Iterator<Double> it = l.iterator();
Chris@1 497 for (int i = 0; it.hasNext(); i++)
Chris@1 498 features[i] = it.next().doubleValue();
Chris@1 499 return features;
Chris@1 500 } catch (FileNotFoundException e) {
Chris@1 501 e.printStackTrace();
Chris@1 502 return null;
Chris@1 503 } catch (IOException e) {
Chris@1 504 e.printStackTrace();
Chris@1 505 return null;
Chris@1 506 } catch (NumberFormatException e) {
Chris@1 507 e.printStackTrace();
Chris@1 508 return null;
Chris@1 509 }
Chris@1 510 } // getFeatures()
Chris@1 511
Chris@1 512 /** Reads a file of feature values, treated as an onset detection function,
Chris@1 513 * and finds peaks, which are stored in <code>onsetList</code> and <code>onsets</code>.
Chris@1 514 * @param fileName The file of feature values
Chris@1 515 * @param hopTime The spacing of feature values in time
Chris@1 516 */
Chris@2 517 void processFeatures(String fileName, double hopTime) {
Chris@1 518 double hop = hopTime;
Chris@1 519 double[] features = getFeatures(fileName);
Chris@1 520 Peaks.normalise(features);
Chris@1 521 LinkedList<Integer> peaks = Peaks.findPeaks(features, (int)Math.round(0.06 / hop), 0.35, 0.84, true);
Chris@1 522 onsets = new double[peaks.size()];
Chris@1 523 double[] y2 = new double[onsets.length];
Chris@1 524 Iterator<Integer> it = peaks.iterator();
Chris@1 525 onsetList = new EventList();
Chris@1 526 double minSalience = Peaks.min(features);
Chris@1 527 for (int i = 0; i < onsets.length; i++) {
Chris@1 528 int index = it.next();
Chris@1 529 onsets[i] = index * hop;
Chris@1 530 y2[i] = features[index];
Chris@1 531 Event e = BeatTrackDisplay.newBeat(onsets[i], 0);
Chris@1 532 e.salience = features[index] - minSalience;
Chris@1 533 onsetList.add(e);
Chris@1 534 }
Chris@1 535 } // processFeatures()
Chris@1 536
Chris@1 537 /** Copies output of audio processing to the display panel. */
Chris@2 538 void setDisplay(BeatTrackDisplay btd) {
Chris@1 539 int energy2[] = new int[totalFrames*energyOversampleFactor];
Chris@1 540 double time[] = new double[totalFrames*energyOversampleFactor];
Chris@1 541 for (int i = 0; i < totalFrames*energyOversampleFactor; i++) {
Chris@1 542 energy2[i] = (int) (energy[i] * 4 * energyOversampleFactor);
Chris@1 543 time[i] = i * hopTime / energyOversampleFactor;
Chris@1 544 }
Chris@1 545 btd.setMagnitudes(energy2);
Chris@1 546 btd.setEnvTimes(time);
Chris@1 547 btd.setSpectro(frames, totalFrames, hopTime, 0);//fftTime/hopTime);
Chris@1 548 btd.setOnsets(onsets);
Chris@1 549 btd.setOnsetList(onsetList);
Chris@1 550 } // setDisplay()
Chris@1 551
Chris@1 552 } // class AudioProcessor
Chris@1 553
Chris@1 554
Chris@1 555 #endif