plugins/Mfcc.{cpp,h}: added first Mfcc drafts
[vamp-aubio-plugins.git] / plugins / Notes.cpp
1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*-  vi:set ts=8 sts=4 sw=4: */
2
3 /*
4     Vamp feature extraction plugins using Paul Brossier's Aubio library.
5
6     Centre for Digital Music, Queen Mary, University of London.
7     This file copyright 2006-2008 Chris Cannam 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
17 #include <math.h>
18 #include "Notes.h"
19
20 #include <algorithm>
21
22 using std::string;
23 using std::vector;
24 using std::cerr;
25 using std::endl;
26
27 Notes::Notes(float inputSampleRate) :
28     Plugin(inputSampleRate),
29     m_ibuf(0),
30     m_onset(0),
31     m_pitch(0),
32     m_onsetdet(0),
33     m_onsettype(OnsetComplex),
34     m_pitchdet(0),
35     m_pitchtype(PitchYinFFT),
36     m_threshold(0.3),
37     m_silence(-70),
38     m_minioi(4),
39     m_median(6),
40     m_minpitch(32),
41     m_maxpitch(95),
42     m_wrapRange(false),
43     m_avoidLeaps(false),
44     m_prevPitch(-1)
45 {
46 }
47
48 Notes::~Notes()
49 {
50     if (m_onsetdet) del_aubio_onset(m_onsetdet);
51     if (m_pitchdet) del_aubio_pitch(m_pitchdet);
52     if (m_ibuf) del_fvec(m_ibuf);
53     if (m_onset) del_fvec(m_onset);
54     if (m_pitch) del_fvec(m_pitch);
55 }
56
57 string
58 Notes::getIdentifier() const
59 {
60     return "aubionotes";
61 }
62
63 string
64 Notes::getName() const
65 {
66     return "Aubio Note Tracker";
67 }
68
69 string
70 Notes::getDescription() const
71 {
72     return "Estimate note onset positions, pitches and durations";
73 }
74
75 string
76 Notes::getMaker() const
77 {
78     return "Paul Brossier (plugin by Chris Cannam)";
79 }
80
81 int
82 Notes::getPluginVersion() const
83 {
84     return 4;
85 }
86
87 string
88 Notes::getCopyright() const
89 {
90     return "GPL";
91 }
92
93 bool
94 Notes::initialise(size_t channels, size_t stepSize, size_t blockSize)
95 {
96     if (channels != 1) {
97         std::cerr << "Notes::initialise: channels must be 1" << std::endl;
98         return false;
99     }
100
101     m_stepSize = stepSize;
102     m_blockSize = blockSize;
103
104     m_ibuf = new_fvec(stepSize);
105     m_onset = new_fvec(1);
106     m_pitch = new_fvec(1);
107
108     reset();
109
110     return true;
111 }
112
113 void
114 Notes::reset()
115 {
116     if (m_onsetdet) del_aubio_onset(m_onsetdet);
117     if (m_pitchdet) del_aubio_pitch(m_pitchdet);
118
119     m_onsetdet = new_aubio_onset
120         (const_cast<char *>(getAubioNameForOnsetType(m_onsettype)),
121          m_blockSize,
122          m_stepSize,
123          lrintf(m_inputSampleRate));
124     
125     aubio_onset_set_threshold(m_onsetdet, m_threshold);
126     aubio_onset_set_silence(m_onsetdet, m_silence);
127     aubio_onset_set_minioi(m_onsetdet, m_minioi);
128
129     m_pitchdet = new_aubio_pitch
130         (const_cast<char *>(getAubioNameForPitchType(m_pitchtype)),
131          m_blockSize,
132          m_stepSize,
133          lrintf(m_inputSampleRate));
134
135     aubio_pitch_set_unit(m_pitchdet, const_cast<char *>("freq"));
136
137     m_count = 0;
138     m_delay = Vamp::RealTime::frame2RealTime((4 + m_median) * m_stepSize,
139                                        lrintf(m_inputSampleRate));
140     m_currentOnset = Vamp::RealTime::zeroTime;
141     m_haveCurrent = false;
142     m_prevPitch = -1;
143 }
144
145 size_t
146 Notes::getPreferredStepSize() const
147 {
148     return 512;
149 }
150
151 size_t
152 Notes::getPreferredBlockSize() const
153 {
154     return 4 * getPreferredStepSize();
155 }
156
157 Notes::ParameterList
158 Notes::getParameterDescriptors() const
159 {
160     ParameterList list;
161     
162     ParameterDescriptor desc;
163     desc.identifier = "onsettype";
164     desc.name = "Onset Detection Function Type";
165     desc.description = "Type of onset detection function to use";
166     desc.minValue = 0;
167     desc.maxValue = 7;
168     desc.defaultValue = (int)OnsetComplex;
169     desc.isQuantized = true;
170     desc.quantizeStep = 1;
171     desc.valueNames.push_back("Energy Based");
172     desc.valueNames.push_back("Spectral Difference");
173     desc.valueNames.push_back("High-Frequency Content");
174     desc.valueNames.push_back("Complex Domain");
175     desc.valueNames.push_back("Phase Deviation");
176     desc.valueNames.push_back("Kullback-Liebler");
177     desc.valueNames.push_back("Modified Kullback-Liebler");
178     desc.valueNames.push_back("Spectral Flux");
179     list.push_back(desc);
180
181     desc = ParameterDescriptor();
182     desc.identifier = "pitchtype";
183     desc.name = "Pitch Detection Function Type";
184     desc.description = "Type of pitch detection function to use";
185     desc.minValue = 0;
186     desc.maxValue = 4;
187     desc.defaultValue = (int)PitchYinFFT;
188     desc.isQuantized = true;
189     desc.quantizeStep = 1;
190     desc.valueNames.push_back("YIN Frequency Estimator");
191     desc.valueNames.push_back("Spectral Comb");
192     desc.valueNames.push_back("Schmitt");
193     desc.valueNames.push_back("Fast Harmonic Comb");
194     desc.valueNames.push_back("YIN with FFT");
195     list.push_back(desc);
196
197     desc = ParameterDescriptor();
198     desc.identifier = "minpitch";
199     desc.name = "Minimum Pitch";
200     desc.description = "Lower pitch value to look for";
201     desc.minValue = 0;
202     desc.maxValue = 127;
203     desc.defaultValue = 32;
204     desc.unit = "MIDI units";
205     desc.isQuantized = true;
206     desc.quantizeStep = 1;
207     list.push_back(desc);
208
209     desc = ParameterDescriptor();
210     desc.identifier = "maxpitch";
211     desc.name = "Maximum Pitch";
212     desc.description = "Highest pitch value to look for";
213     desc.minValue = 0;
214     desc.maxValue = 127;
215     desc.defaultValue = 95;
216     desc.unit = "MIDI units";
217     desc.isQuantized = true;
218     desc.quantizeStep = 1;
219     list.push_back(desc);
220
221     desc = ParameterDescriptor();
222     desc.identifier = "wraprange";
223     desc.name = "Fold Higher or Lower Notes into Range";
224     desc.description = "Notes detected outside the range will be transposed to higher or lower octaves";
225     desc.minValue = 0;
226     desc.maxValue = 1;
227     desc.defaultValue = 0;
228     desc.isQuantized = true;
229     desc.quantizeStep = 1;
230     list.push_back(desc);
231
232     desc = ParameterDescriptor();
233     desc.identifier = "avoidleaps";
234     desc.name = "Avoid Multi-Octave Jumps";
235     desc.description = "Minimize octave jumps by transposing to the octave of the previously detected note";
236     desc.minValue = 0;
237     desc.maxValue = 1;
238     desc.defaultValue = 0;
239     desc.isQuantized = true;
240     desc.quantizeStep = 1;
241     list.push_back(desc);
242
243     desc = ParameterDescriptor();
244     desc.identifier = "peakpickthreshold";
245     desc.name = "Peak Picker Threshold";
246     desc.description = "Peak picking threshold, the higher the least detection";
247     desc.minValue = 0;
248     desc.maxValue = 1;
249     desc.defaultValue = 0.3;
250     desc.isQuantized = false;
251     list.push_back(desc);
252
253     desc = ParameterDescriptor();
254     desc.identifier = "silencethreshold";
255     desc.name = "Silence Threshold";
256     desc.description = "Silence threshold, the higher the least detection";
257     desc.minValue = -120;
258     desc.maxValue = 0;
259     desc.defaultValue = -70;
260     desc.unit = "dB";
261     desc.isQuantized = false;
262     list.push_back(desc);
263
264     desc = ParameterDescriptor();
265     desc.identifier = "minioi";
266     desc.name = "Minimum Inter-Onset Interval";
267     desc.description = "Time interval below which two consecutive onsets should be merged";
268     desc.minValue = 0;
269     desc.maxValue = 40;
270     desc.defaultValue = 4;
271     desc.unit = "ms";
272     desc.isQuantized = true;
273     desc.quantizeStep = 1;
274     list.push_back(desc);
275
276     return list;
277 }
278
279 float
280 Notes::getParameter(std::string param) const
281 {
282     if (param == "onsettype") {
283         return m_onsettype;
284     } else if (param == "pitchtype") {
285         return m_pitchtype;
286     } else if (param == "peakpickthreshold") {
287         return m_threshold;
288     } else if (param == "silencethreshold") {
289         return m_silence;
290     } else if (param == "minpitch") {
291         return m_minpitch;
292     } else if (param == "maxpitch") {
293         return m_maxpitch;
294     } else if (param == "wraprange") {
295         return m_wrapRange ? 1.0 : 0.0;
296     } else if (param == "avoidleaps") {
297         return m_avoidLeaps ? 1.0 : 0.0;
298     } else if (param == "minioi") {
299         return m_minioi;
300     } else {
301         return 0.0;
302     }
303 }
304
305 void
306 Notes::setParameter(std::string param, float value)
307 {
308     if (param == "onsettype") {
309         switch (lrintf(value)) {
310         case 0: m_onsettype = OnsetEnergy; break;
311         case 1: m_onsettype = OnsetSpecDiff; break;
312         case 2: m_onsettype = OnsetHFC; break;
313         case 3: m_onsettype = OnsetComplex; break;
314         case 4: m_onsettype = OnsetPhase; break;
315         case 5: m_onsettype = OnsetKL; break;
316         case 6: m_onsettype = OnsetMKL; break;
317         case 7: m_onsettype = OnsetSpecFlux; break;
318         }
319     } else if (param == "pitchtype") {
320         switch (lrintf(value)) {
321         case 0: m_pitchtype = PitchYin; break;
322         case 1: m_pitchtype = PitchMComb; break;
323         case 2: m_pitchtype = PitchSchmitt; break;
324         case 3: m_pitchtype = PitchFComb; break;
325         case 4: m_pitchtype = PitchYinFFT; break;
326         }
327     } else if (param == "peakpickthreshold") {
328         m_threshold = value;
329     } else if (param == "silencethreshold") {
330         m_silence = value;
331     } else if (param == "minpitch") {
332         m_minpitch = lrintf(value);
333     } else if (param == "maxpitch") {
334         m_maxpitch = lrintf(value);
335     } else if (param == "wraprange") {
336         m_wrapRange = (value > 0.5);
337     } else if (param == "avoidleaps") {
338         m_avoidLeaps = (value > 0.5);
339     } else if (param == "minioi") {
340         m_minioi = value;
341     }
342 }
343
344 Notes::OutputList
345 Notes::getOutputDescriptors() const
346 {
347     OutputList list;
348
349     OutputDescriptor d;
350     d.identifier = "notes";
351     d.name = "Notes";
352     d.description = "List of notes detected, with their frequency and velocity";
353     d.unit = "Hz";
354     d.hasFixedBinCount = true;
355
356     d.binCount = 2;
357     d.binNames.push_back("Frequency");
358     d.binNames.push_back("Velocity");
359     d.hasDuration = true;
360
361     d.hasKnownExtents = false;
362     d.isQuantized = false;
363     d.sampleType = OutputDescriptor::VariableSampleRate;
364     d.sampleRate = 0;
365     list.push_back(d);
366
367     return list;
368 }
369
370 Notes::FeatureSet
371 Notes::process(const float *const *inputBuffers, Vamp::RealTime timestamp)
372 {
373     for (size_t i = 0; i < m_stepSize; ++i) {
374         fvec_set_sample(m_ibuf, inputBuffers[0][i], i);
375     }
376
377     aubio_onset_do(m_onsetdet, m_ibuf, m_onset);
378     aubio_pitch_do(m_pitchdet, m_ibuf, m_pitch);
379
380     bool isonset = m_onset->data[0];
381     float frequency = m_pitch->data[0];
382
383     m_notebuf.push_back(frequency);
384     if (m_notebuf.size() > m_median) m_notebuf.pop_front();
385
386     float level = aubio_level_detection(m_ibuf, m_silence);
387
388     FeatureSet returnFeatures;
389
390     if (isonset) {
391         if (level == 1.) {
392             isonset = false;
393             m_count = 0;
394             if (m_haveCurrent) pushNote(returnFeatures, timestamp);
395         } else {
396             m_count = 1;
397         }
398     } else {
399         if (m_count > 0) ++m_count;
400         if (m_count == m_median) {
401             if (m_haveCurrent) pushNote(returnFeatures, timestamp);
402             m_currentOnset = timestamp;
403             m_currentLevel = level;
404             m_haveCurrent = true;
405         }
406     }
407
408     m_lastTimeStamp = timestamp;
409     return returnFeatures;
410 }
411
412 Notes::FeatureSet
413 Notes::getRemainingFeatures()
414 {
415     FeatureSet returnFeatures;
416     if (m_haveCurrent) pushNote(returnFeatures, m_lastTimeStamp);
417     return returnFeatures;
418 }
419
420 void
421 Notes::pushNote(FeatureSet &fs, const Vamp::RealTime &offTime)
422 {
423     std::deque<float> toSort = m_notebuf;
424     std::sort(toSort.begin(), toSort.end());
425     float median = toSort[toSort.size()/2];
426     if (median < 45.0) return;
427
428     float freq = median;
429     int midiPitch = (int)floor(aubio_freqtomidi(freq) + 0.5);
430     
431     if (m_avoidLeaps) {
432         if (m_prevPitch >= 0) {
433             while (midiPitch < m_prevPitch - 12) {
434                 midiPitch += 12;
435                 freq *= 2;
436             }
437             while (midiPitch > m_prevPitch + 12) {
438                 midiPitch -= 12;
439                 freq /= 2;
440             }
441         }
442     }
443
444     while (midiPitch < m_minpitch) {
445         if (!m_wrapRange) return;
446         midiPitch += 12;
447         freq *= 2;
448     }
449
450     while (midiPitch > m_maxpitch) {
451         if (!m_wrapRange) return;
452         midiPitch -= 12;
453         freq /= 2;
454     }
455
456     m_prevPitch = midiPitch;
457
458     Feature feature;
459     feature.hasTimestamp = true;
460     if (m_currentOnset < m_delay) m_currentOnset = m_delay;
461     feature.timestamp = m_currentOnset - m_delay;
462     feature.values.push_back(freq);
463
464     feature.values.push_back
465         (Vamp::RealTime::realTime2Frame
466          (offTime, lrintf(m_inputSampleRate)) -
467          Vamp::RealTime::realTime2Frame
468          (m_currentOnset, lrintf(m_inputSampleRate)));
469     feature.hasDuration = false;
470
471     feature.values.push_back(m_currentLevel);
472     fs[0].push_back(feature);
473 }
474