DownBeat.cpp
Go to the documentation of this file.
1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
2 
3 /*
4  QM DSP Library
5 
6  Centre for Digital Music, Queen Mary, University of London.
7  This file copyright 2008-2009 Matthew Davies and QMUL.
8 
9  This program is free software; you can redistribute it and/or
10  modify it under the terms of the GNU General Public License as
11  published by the Free Software Foundation; either version 2 of the
12  License, or (at your option) any later version. See the file
13  COPYING included with this distribution for more information.
14 */
15 
16 #include "DownBeat.h"
17 
18 #include "maths/MathAliases.h"
19 #include "maths/MathUtilities.h"
20 #include "maths/KLDivergence.h"
21 #include "dsp/transforms/FFT.h"
22 
23 #include <iostream>
24 #include <cstdlib>
25 
26 using std::vector;
27 
28 DownBeat::DownBeat(float originalSampleRate,
29  size_t decimationFactor,
30  size_t dfIncrement) :
31  m_bpb(0),
32  m_rate(originalSampleRate),
33  m_factor(decimationFactor),
34  m_increment(dfIncrement),
35  m_decimator1(0),
36  m_decimator2(0),
37  m_buffer(0),
38  m_decbuf(0),
39  m_bufsiz(0),
40  m_buffill(0),
41  m_beatframesize(0),
42  m_beatframe(0)
43 {
44  // beat frame size is next power of two up from 1.3 seconds at the
45  // downsampled rate (happens to produce 4096 for 44100 or 48000 at
46  // 16x decimation, which is our expected normal situation)
48  (int((m_rate / decimationFactor) * 1.3));
49  if (m_beatframesize < 2) {
50  m_beatframesize = 2;
51  }
52  m_beatframe = new double[m_beatframesize];
53  m_fftRealOut = new double[m_beatframesize];
54  m_fftImagOut = new double[m_beatframesize];
56 }
57 
59 {
60  delete m_decimator1;
61  delete m_decimator2;
62  if (m_buffer) free(m_buffer);
63  delete[] m_decbuf;
64  delete[] m_beatframe;
65  delete[] m_fftRealOut;
66  delete[] m_fftImagOut;
67  delete m_fft;
68 }
69 
70 void
72 {
73  m_bpb = bpb;
74 }
75 
76 void
78 {
79  if (m_factor < 2) return;
80  size_t highest = Decimator::getHighestSupportedFactor();
81  if (m_factor <= highest) {
83  return;
84  }
85  m_decimator1 = new Decimator(m_increment, highest);
86  m_decimator2 = new Decimator(m_increment / highest, m_factor / highest);
87  m_decbuf = new float[m_increment / highest];
88 }
89 
90 void
91 DownBeat::pushAudioBlock(const float *audio)
92 {
93  if (m_buffill + (m_increment / m_factor) > m_bufsiz) {
94  if (m_bufsiz == 0) m_bufsiz = m_increment * 16;
95  else m_bufsiz = m_bufsiz * 2;
96  if (!m_buffer) {
97  m_buffer = (float *)malloc(m_bufsiz * sizeof(float));
98  } else {
99  m_buffer = (float *)realloc(m_buffer, m_bufsiz * sizeof(float));
100  }
101  }
102  if (!m_decimator1 && m_factor > 1) {
103  makeDecimators();
104  }
105  if (m_decimator2) {
106  m_decimator1->process(audio, m_decbuf);
108  } else if (m_decimator1) {
110  } else {
111  // just copy across (m_factor is presumably 1)
112  for (size_t i = 0; i < m_increment; ++i) {
113  (m_buffer + m_buffill)[i] = audio[i];
114  }
115  }
117 }
118 
119 const float *
120 DownBeat::getBufferedAudio(size_t &length) const
121 {
122  length = m_buffill;
123  return m_buffer;
124 }
125 
126 void
128 {
129  if (m_buffer) {
130  free(m_buffer);
131  }
132  m_buffer = 0;
133  m_buffill = 0;
134  m_bufsiz = 0;
135 }
136 
137 void
138 DownBeat::findDownBeats(const float *audio,
139  size_t audioLength,
140  const d_vec_t &beats,
141  i_vec_t &downbeats)
142 {
143  // FIND DOWNBEATS BY PARTITIONING THE INPUT AUDIO FILE INTO BEAT SEGMENTS
144  // WHERE THE AUDIO FRAMES ARE DOWNSAMPLED BY A FACTOR OF 16 (fs ~= 2700Hz)
145  // THEN TAKING THE JENSEN-SHANNON DIVERGENCE BETWEEN BEAT SYNCHRONOUS SPECTRAL FRAMES
146 
147  // IMPLEMENTATION (MOSTLY) FOLLOWS:
148  // DAVIES AND PLUMBLEY "A SPECTRAL DIFFERENCE APPROACH TO EXTRACTING DOWNBEATS IN MUSICAL AUDIO"
149  // EUSIPCO 2006, FLORENCE, ITALY
150 
151  d_vec_t newspec(m_beatframesize / 2); // magnitude spectrum of current beat
152  d_vec_t oldspec(m_beatframesize / 2); // magnitude spectrum of previous beat
153 
154  m_beatsd.clear();
155 
156  if (audioLength == 0) return;
157 
158  for (size_t i = 0; i + 1 < beats.size(); ++i) {
159 
160  // Copy the extents of the current beat from downsampled array
161  // into beat frame buffer
162 
163  size_t beatstart = (beats[i] * m_increment) / m_factor;
164  size_t beatend = (beats[i+1] * m_increment) / m_factor;
165  if (beatend >= audioLength) beatend = audioLength - 1;
166  if (beatend < beatstart) beatend = beatstart;
167  size_t beatlen = beatend - beatstart;
168 
169  // Also apply a Hanning window to the beat frame buffer, sized
170  // to the beat extents rather than the frame size. (Because
171  // the size varies, it's easier to do this by hand than use
172  // our Window abstraction.)
173 
174  for (size_t j = 0; j < beatlen && j < m_beatframesize; ++j) {
175  double mul = 0.5 * (1.0 - cos(TWO_PI * (double(j) / double(beatlen))));
176  m_beatframe[j] = audio[beatstart + j] * mul;
177  }
178 
179  for (size_t j = beatlen; j < m_beatframesize; ++j) {
180  m_beatframe[j] = 0.0;
181  }
182 
183  // Now FFT beat frame
184 
186 
187  // Calculate magnitudes
188 
189  for (size_t j = 0; j < m_beatframesize/2; ++j) {
190  newspec[j] = sqrt(m_fftRealOut[j] * m_fftRealOut[j] +
191  m_fftImagOut[j] * m_fftImagOut[j]);
192  }
193 
194  // Preserve peaks by applying adaptive threshold
195 
197 
198  // Calculate JS divergence between new and old spectral frames
199 
200  if (i > 0) { // otherwise we have no previous frame
201  m_beatsd.push_back(measureSpecDiff(oldspec, newspec));
202  }
203 
204  // Copy newspec across to old
205 
206  for (size_t j = 0; j < m_beatframesize/2; ++j) {
207  oldspec[j] = newspec[j];
208  }
209  }
210 
211  // We now have all spectral difference measures in specdiff
212 
213  int timesig = m_bpb;
214  if (timesig == 0) timesig = 4;
215 
216  d_vec_t dbcand(timesig); // downbeat candidates
217 
218  for (int beat = 0; beat < timesig; ++beat) {
219  dbcand[beat] = 0;
220  }
221 
222  // look for beat transition which leads to greatest spectral change
223  for (int beat = 0; beat < timesig; ++beat) {
224  int count = 0;
225  for (int example = beat-1; example < (int)m_beatsd.size(); example += timesig) {
226  if (example < 0) continue;
227  dbcand[beat] += (m_beatsd[example]) / timesig;
228  ++count;
229  }
230  if (count > 0) {
231  dbcand[beat] /= count;
232  }
233  }
234 
235  // first downbeat is beat at index of maximum value of dbcand
236  int dbind = MathUtilities::getMax(dbcand);
237 
238  // remaining downbeats are at timesig intervals from the first
239  for (int i = dbind; i < (int)beats.size(); i += timesig) {
240  downbeats.push_back(i);
241  }
242 }
243 
244 double
246 {
247  // JENSEN-SHANNON DIVERGENCE BETWEEN SPECTRAL FRAMES
248 
249  int SPECSIZE = 512; // ONLY LOOK AT FIRST 512 SAMPLES OF SPECTRUM.
250  if (SPECSIZE > int(oldspec.size())/4) {
251  SPECSIZE = int(oldspec.size())/4;
252  }
253  double SD = 0.;
254  double sd1 = 0.;
255 
256  double sumnew = 0.;
257  double sumold = 0.;
258 
259  for (int i = 0;i < SPECSIZE;i++) {
260 
261  newspec[i] +=EPS;
262  oldspec[i] +=EPS;
263 
264  sumnew+=newspec[i];
265  sumold+=oldspec[i];
266  }
267 
268  for (int i = 0;i < SPECSIZE;i++) {
269 
270  newspec[i] /= (sumnew);
271  oldspec[i] /= (sumold);
272 
273  // IF ANY SPECTRAL VALUES ARE 0 (SHOULDN'T BE ANY!) SET THEM TO 1
274  if (newspec[i] == 0) {
275  newspec[i] = 1.;
276  }
277 
278  if (oldspec[i] == 0) {
279  oldspec[i] = 1.;
280  }
281 
282  // JENSEN-SHANNON CALCULATION
283  sd1 = 0.5*oldspec[i] + 0.5*newspec[i];
284  SD = SD + (-sd1*log(sd1)) +
285  (0.5*(oldspec[i]*log(oldspec[i]))) +
286  (0.5*(newspec[i]*log(newspec[i])));
287  }
288 
289  return SD;
290 }
291 
292 void
293 DownBeat::getBeatSD(vector<double> &beatsd) const
294 {
295  for (int i = 0; i < (int)m_beatsd.size(); ++i) {
296  beatsd.push_back(m_beatsd[i]);
297  }
298 }
299 
void process(const double *src, double *dst)
Process inLength samples (as supplied to constructor) from src and write inLength / decFactor samples...
Definition: Decimator.cpp:195
static void adaptiveThreshold(std::vector< double > &data)
Threshold the input/output vector data against a moving-mean average filter.
double * m_fftRealOut
Definition: DownBeat.h:129
void getBeatSD(std::vector< double > &beatsd) const
Return the beat spectral difference function.
Definition: DownBeat.cpp:293
void findDownBeats(const float *audio, size_t audioLength, const std::vector< double > &beats, std::vector< int > &downbeats)
Estimate which beats are down-beats.
Definition: DownBeat.cpp:138
size_t m_bufsiz
Definition: DownBeat.h:124
size_t m_beatframesize
Definition: DownBeat.h:126
static int getHighestSupportedFactor()
Definition: Decimator.h:57
std::vector< int > i_vec_t
Definition: DownBeat.h:108
void pushAudioBlock(const float *audio)
For your downsampling convenience: call this function repeatedly with input audio blocks containing d...
Definition: DownBeat.cpp:91
DownBeat(float originalSampleRate, size_t decimationFactor, size_t dfIncrement)
Construct a downbeat locator that will operate on audio at the downsampled by the given decimation fa...
Definition: DownBeat.cpp:28
size_t m_factor
Definition: DownBeat.h:118
const float * getBufferedAudio(size_t &length) const
Retrieve the accumulated audio produced by pushAudioBlock calls.
Definition: DownBeat.cpp:120
void forward(const double *realIn, double *realOut, double *imagOut)
Carry out a forward real-to-complex transform of size nsamples, where nsamples is the value provided ...
Definition: FFT.cpp:184
float * m_decbuf
Definition: DownBeat.h:123
float * m_buffer
Definition: DownBeat.h:122
static int getMax(double *data, int length, double *max=0)
#define EPS
size_t m_buffill
Definition: DownBeat.h:125
double * m_fftImagOut
Definition: DownBeat.h:130
void makeDecimators()
Definition: DownBeat.cpp:77
Decimator * m_decimator2
Definition: DownBeat.h:121
double * m_beatframe
Definition: DownBeat.h:127
void resetAudioBuffer()
Clear any buffered downsampled audio data.
Definition: DownBeat.cpp:127
#define TWO_PI
Definition: MathAliases.h:21
Definition: FFT.h:52
Decimator * m_decimator1
Definition: DownBeat.h:120
static int nextPowerOfTwo(int x)
Return the next higher integer power of two from x, e.g.
size_t m_increment
Definition: DownBeat.h:119
std::vector< double > d_vec_t
Definition: DownBeat.h:110
int m_bpb
Definition: DownBeat.h:116
Decimator carries out a fast downsample by a power-of-two factor.
Definition: Decimator.h:24
void setBeatsPerBar(int bpb)
Definition: DownBeat.cpp:71
d_vec_t m_beatsd
Definition: DownBeat.h:131
FFTReal * m_fft
Definition: DownBeat.h:128
double measureSpecDiff(d_vec_t oldspec, d_vec_t newspec)
Definition: DownBeat.cpp:245
float m_rate
Definition: DownBeat.h:117
~DownBeat()
Definition: DownBeat.cpp:58