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