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