Merge 0.4.0
[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.minValue = 0;
166     desc.maxValue = 7;
167     desc.defaultValue = (int)OnsetComplex;
168     desc.isQuantized = true;
169     desc.quantizeStep = 1;
170     desc.valueNames.push_back("Energy Based");
171     desc.valueNames.push_back("Spectral Difference");
172     desc.valueNames.push_back("High-Frequency Content");
173     desc.valueNames.push_back("Complex Domain");
174     desc.valueNames.push_back("Phase Deviation");
175     desc.valueNames.push_back("Kullback-Liebler");
176     desc.valueNames.push_back("Modified Kullback-Liebler");
177     desc.valueNames.push_back("Spectral Flux");
178     list.push_back(desc);
179
180     desc = ParameterDescriptor();
181     desc.identifier = "pitchtype";
182     desc.name = "Pitch Detection Function Type";
183     desc.minValue = 0;
184     desc.maxValue = 4;
185     desc.defaultValue = (int)PitchYinFFT;
186     desc.isQuantized = true;
187     desc.quantizeStep = 1;
188     desc.valueNames.push_back("YIN Frequency Estimator");
189     desc.valueNames.push_back("Spectral Comb");
190     desc.valueNames.push_back("Schmitt");
191     desc.valueNames.push_back("Fast Harmonic Comb");
192     desc.valueNames.push_back("YIN with FFT");
193     list.push_back(desc);
194
195     desc = ParameterDescriptor();
196     desc.identifier = "minpitch";
197     desc.name = "Minimum Pitch";
198     desc.minValue = 0;
199     desc.maxValue = 127;
200     desc.defaultValue = 32;
201     desc.unit = "MIDI units";
202     desc.isQuantized = true;
203     desc.quantizeStep = 1;
204     list.push_back(desc);
205
206     desc = ParameterDescriptor();
207     desc.identifier = "maxpitch";
208     desc.name = "Maximum Pitch";
209     desc.minValue = 0;
210     desc.maxValue = 127;
211     desc.defaultValue = 95;
212     desc.unit = "MIDI units";
213     desc.isQuantized = true;
214     desc.quantizeStep = 1;
215     list.push_back(desc);
216
217     desc = ParameterDescriptor();
218     desc.identifier = "wraprange";
219     desc.name = "Fold Higher or Lower Notes into Range";
220     desc.minValue = 0;
221     desc.maxValue = 1;
222     desc.defaultValue = 0;
223     desc.isQuantized = true;
224     desc.quantizeStep = 1;
225     list.push_back(desc);
226
227     desc = ParameterDescriptor();
228     desc.identifier = "avoidleaps";
229     desc.name = "Avoid Multi-Octave Jumps";
230     desc.minValue = 0;
231     desc.maxValue = 1;
232     desc.defaultValue = 0;
233     desc.isQuantized = true;
234     desc.quantizeStep = 1;
235     list.push_back(desc);
236
237     desc = ParameterDescriptor();
238     desc.identifier = "peakpickthreshold";
239     desc.name = "Peak Picker Threshold";
240     desc.minValue = 0;
241     desc.maxValue = 1;
242     desc.defaultValue = 0.3;
243     desc.isQuantized = false;
244     list.push_back(desc);
245
246     desc = ParameterDescriptor();
247     desc.identifier = "silencethreshold";
248     desc.name = "Silence Threshold";
249     desc.minValue = -120;
250     desc.maxValue = 0;
251     desc.defaultValue = -70;
252     desc.unit = "dB";
253     desc.isQuantized = false;
254     list.push_back(desc);
255
256     desc = ParameterDescriptor();
257     desc.identifier = "minioi";
258     desc.name = "Minimum Inter-Onset Interval";
259     desc.minValue = 0;
260     desc.maxValue = 40;
261     desc.defaultValue = 4;
262     desc.unit = "ms";
263     desc.isQuantized = true;
264     desc.quantizeStep = 1;
265     list.push_back(desc);
266
267     return list;
268 }
269
270 float
271 Notes::getParameter(std::string param) const
272 {
273     if (param == "onsettype") {
274         return m_onsettype;
275     } else if (param == "pitchtype") {
276         return m_pitchtype;
277     } else if (param == "peakpickthreshold") {
278         return m_threshold;
279     } else if (param == "silencethreshold") {
280         return m_silence;
281     } else if (param == "minpitch") {
282         return m_minpitch;
283     } else if (param == "maxpitch") {
284         return m_maxpitch;
285     } else if (param == "wraprange") {
286         return m_wrapRange ? 1.0 : 0.0;
287     } else if (param == "avoidleaps") {
288         return m_avoidLeaps ? 1.0 : 0.0;
289     } else if (param == "minioi") {
290         return m_minioi;
291     } else {
292         return 0.0;
293     }
294 }
295
296 void
297 Notes::setParameter(std::string param, float value)
298 {
299     if (param == "onsettype") {
300         switch (lrintf(value)) {
301         case 0: m_onsettype = OnsetEnergy; break;
302         case 1: m_onsettype = OnsetSpecDiff; break;
303         case 2: m_onsettype = OnsetHFC; break;
304         case 3: m_onsettype = OnsetComplex; break;
305         case 4: m_onsettype = OnsetPhase; break;
306         case 5: m_onsettype = OnsetKL; break;
307         case 6: m_onsettype = OnsetMKL; break;
308         case 7: m_onsettype = OnsetSpecFlux; break;
309         }
310     } else if (param == "pitchtype") {
311         switch (lrintf(value)) {
312         case 0: m_pitchtype = PitchYin; break;
313         case 1: m_pitchtype = PitchMComb; break;
314         case 2: m_pitchtype = PitchSchmitt; break;
315         case 3: m_pitchtype = PitchFComb; break;
316         case 4: m_pitchtype = PitchYinFFT; break;
317         }
318     } else if (param == "peakpickthreshold") {
319         m_threshold = value;
320     } else if (param == "silencethreshold") {
321         m_silence = value;
322     } else if (param == "minpitch") {
323         m_minpitch = lrintf(value);
324     } else if (param == "maxpitch") {
325         m_maxpitch = lrintf(value);
326     } else if (param == "wraprange") {
327         m_wrapRange = (value > 0.5);
328     } else if (param == "avoidleaps") {
329         m_avoidLeaps = (value > 0.5);
330     } else if (param == "minioi") {
331         m_minioi = value;
332     }
333 }
334
335 Notes::OutputList
336 Notes::getOutputDescriptors() const
337 {
338     OutputList list;
339
340     OutputDescriptor d;
341     d.identifier = "notes";
342     d.name = "Notes";
343     d.unit = "Hz";
344     d.hasFixedBinCount = true;
345
346     d.binCount = 2;
347     d.binNames.push_back("Frequency");
348     d.binNames.push_back("Velocity");
349     d.hasDuration = true;
350
351     d.hasKnownExtents = false;
352     d.isQuantized = false;
353     d.sampleType = OutputDescriptor::VariableSampleRate;
354     d.sampleRate = 0;
355     list.push_back(d);
356
357     return list;
358 }
359
360 Notes::FeatureSet
361 Notes::process(const float *const *inputBuffers, Vamp::RealTime timestamp)
362 {
363     for (size_t i = 0; i < m_stepSize; ++i) {
364         fvec_write_sample(m_ibuf, inputBuffers[0][i], i);
365     }
366
367     aubio_onset_do(m_onsetdet, m_ibuf, m_onset);
368     aubio_pitch_do(m_pitchdet, m_ibuf, m_pitch);
369
370     bool isonset = m_onset->data[0];
371     float frequency = m_pitch->data[0];
372
373     m_notebuf.push_back(frequency);
374     if (m_notebuf.size() > m_median) m_notebuf.pop_front();
375
376     float level = aubio_level_detection(m_ibuf, m_silence);
377
378     FeatureSet returnFeatures;
379
380     if (isonset) {
381         if (level == 1.) {
382             isonset = false;
383             m_count = 0;
384             if (m_haveCurrent) pushNote(returnFeatures, timestamp);
385         } else {
386             m_count = 1;
387         }
388     } else {
389         if (m_count > 0) ++m_count;
390         if (m_count == m_median) {
391             if (m_haveCurrent) pushNote(returnFeatures, timestamp);
392             m_currentOnset = timestamp;
393             m_currentLevel = level;
394             m_haveCurrent = true;
395         }
396     }
397
398     m_lastTimeStamp = timestamp;
399     return returnFeatures;
400 }
401
402 Notes::FeatureSet
403 Notes::getRemainingFeatures()
404 {
405     FeatureSet returnFeatures;
406     if (m_haveCurrent) pushNote(returnFeatures, m_lastTimeStamp);
407     return returnFeatures;
408 }
409
410 void
411 Notes::pushNote(FeatureSet &fs, const Vamp::RealTime &offTime)
412 {
413     std::deque<float> toSort = m_notebuf;
414     std::sort(toSort.begin(), toSort.end());
415     float median = toSort[toSort.size()/2];
416     if (median < 45.0) return;
417
418     float freq = median;
419     int midiPitch = (int)floor(aubio_freqtomidi(freq) + 0.5);
420     
421     if (m_avoidLeaps) {
422         if (m_prevPitch >= 0) {
423             while (midiPitch < m_prevPitch - 12) {
424                 midiPitch += 12;
425                 freq *= 2;
426             }
427             while (midiPitch > m_prevPitch + 12) {
428                 midiPitch -= 12;
429                 freq /= 2;
430             }
431         }
432     }
433
434     while (midiPitch < m_minpitch) {
435         if (!m_wrapRange) return;
436         midiPitch += 12;
437         freq *= 2;
438     }
439
440     while (midiPitch > m_maxpitch) {
441         if (!m_wrapRange) return;
442         midiPitch -= 12;
443         freq /= 2;
444     }
445
446     m_prevPitch = midiPitch;
447
448     Feature feature;
449     feature.hasTimestamp = true;
450     if (m_currentOnset < m_delay) m_currentOnset = m_delay;
451     feature.timestamp = m_currentOnset - m_delay;
452     feature.values.push_back(freq);
453
454     feature.values.push_back
455         (Vamp::RealTime::realTime2Frame
456          (offTime, lrintf(m_inputSampleRate)) -
457          Vamp::RealTime::realTime2Frame
458          (m_currentOnset, lrintf(m_inputSampleRate)));
459     feature.hasDuration = false;
460
461     feature.values.push_back(m_currentLevel);
462     fs[0].push_back(feature);
463 }
464