* Add hasDuration to output descriptors
[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 using std::string;
21 using std::vector;
22 using std::cerr;
23 using std::endl;
24
25 Notes::Notes(float inputSampleRate, unsigned int apiVersion) :
26     Plugin(inputSampleRate),
27     m_apiVersion(apiVersion),
28     m_ibuf(0),
29     m_fftgrain(0),
30     m_onset(0),
31     m_pv(0),
32     m_peakpick(0),
33     m_onsetdet(0),
34     m_onsettype(aubio_onset_complex),
35     m_pitchdet(0),
36     m_pitchtype(aubio_pitch_yinfft),
37     m_pitchmode(aubio_pitchm_freq),
38     m_threshold(0.3),
39     m_silence(-90),
40     m_median(6),
41     m_minpitch(27),
42     m_maxpitch(95),
43     m_wrapRange(false),
44     m_avoidLeaps(false),
45     m_prevPitch(-1)
46 {
47     if (apiVersion == 1) {
48         cerr << "vamp-aubio: WARNING: using compatibility version 1 of the Vamp API for note\n"
49              << "tracker plugin: upgrade your host to v2 for proper duration support" << endl;
50     } else {
51         cerr << "vamp-aubio: NOTE: using v2 API for true durations" << endl;
52     }
53 }
54
55 Notes::~Notes()
56 {
57     if (m_onsetdet) aubio_onsetdetection_free(m_onsetdet);
58     if (m_pitchdet) del_aubio_pitchdetection(m_pitchdet);
59     if (m_ibuf) del_fvec(m_ibuf);
60     if (m_onset) del_fvec(m_onset);
61     if (m_fftgrain) del_cvec(m_fftgrain);
62     if (m_pv) del_aubio_pvoc(m_pv);
63     if (m_peakpick) del_aubio_peakpicker(m_peakpick);
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     if (m_apiVersion == 1) return 2;
94     return 3;
95 }
96
97 string
98 Notes::getCopyright() const
99 {
100     return "GPL";
101 }
102
103 bool
104 Notes::initialise(size_t channels, size_t stepSize, size_t blockSize)
105 {
106     m_channelCount = channels;
107     m_stepSize = stepSize;
108     m_blockSize = blockSize;
109
110     size_t processingBlockSize;
111     if (m_onsettype == aubio_onset_energy ||
112         m_onsettype == aubio_onset_hfc) {
113         processingBlockSize = stepSize * 2;
114     } else {
115         processingBlockSize = stepSize * 4;
116     }
117
118     m_ibuf = new_fvec(stepSize, channels);
119     m_onset = new_fvec(1, channels);
120     m_fftgrain = new_cvec(processingBlockSize, channels);
121     m_pv = new_aubio_pvoc(processingBlockSize, stepSize, channels);
122     m_peakpick = new_aubio_peakpicker(m_threshold);
123
124     m_onsetdet = new_aubio_onsetdetection(m_onsettype, processingBlockSize, channels);
125
126     m_pitchdet = new_aubio_pitchdetection(processingBlockSize * 4,
127                                           stepSize,
128                                           channels,
129                                           lrintf(m_inputSampleRate),
130                                           m_pitchtype,
131                                           m_pitchmode);
132
133     m_count = 0;
134     m_delay = Vamp::RealTime::frame2RealTime((4 + m_median) * m_stepSize,
135                                        lrintf(m_inputSampleRate));
136     m_currentOnset = Vamp::RealTime::zeroTime;
137     m_haveCurrent = false;
138     m_prevPitch = -1;
139
140     return true;
141 }
142
143 void
144 Notes::reset()
145 {
146 }
147
148 size_t
149 Notes::getPreferredStepSize() const
150 {
151     return 512;
152 }
153
154 size_t
155 Notes::getPreferredBlockSize() const
156 {
157     return 4 * getPreferredStepSize();
158 }
159
160 Notes::ParameterList
161 Notes::getParameterDescriptors() const
162 {
163     ParameterList list;
164     
165     ParameterDescriptor desc;
166     desc.identifier = "onsettype";
167     desc.name = "Onset Detection Function Type";
168     desc.minValue = 0;
169     desc.maxValue = 6;
170     desc.defaultValue = (int)aubio_onset_complex;
171     desc.isQuantized = true;
172     desc.quantizeStep = 1;
173     desc.valueNames.push_back("Energy Based");
174     desc.valueNames.push_back("Spectral Difference");
175     desc.valueNames.push_back("High-Frequency Content");
176     desc.valueNames.push_back("Complex Domain");
177     desc.valueNames.push_back("Phase Deviation");
178     desc.valueNames.push_back("Kullback-Liebler");
179     desc.valueNames.push_back("Modified Kullback-Liebler");
180     list.push_back(desc);
181
182     desc = ParameterDescriptor();
183     desc.identifier = "pitchtype";
184     desc.name = "Pitch Detection Function Type";
185     desc.minValue = 0;
186     desc.maxValue = 4;
187     desc.defaultValue = (int)aubio_pitch_yinfft;
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.minValue = 0;
201     desc.maxValue = 127;
202     desc.defaultValue = 32;
203     desc.unit = "MIDI units";
204     desc.isQuantized = true;
205     desc.quantizeStep = 1;
206     list.push_back(desc);
207
208     desc = ParameterDescriptor();
209     desc.identifier = "maxpitch";
210     desc.name = "Maximum Pitch";
211     desc.minValue = 0;
212     desc.maxValue = 127;
213     desc.defaultValue = 95;
214     desc.unit = "MIDI units";
215     desc.isQuantized = true;
216     desc.quantizeStep = 1;
217     list.push_back(desc);
218
219     desc = ParameterDescriptor();
220     desc.identifier = "wraprange";
221     desc.name = "Fold Higher or Lower Notes into Range";
222     desc.minValue = 0;
223     desc.maxValue = 1;
224     desc.defaultValue = 0;
225     desc.isQuantized = true;
226     desc.quantizeStep = 1;
227     list.push_back(desc);
228
229     desc = ParameterDescriptor();
230     desc.identifier = "avoidleaps";
231     desc.name = "Avoid Multi-Octave Jumps";
232     desc.minValue = 0;
233     desc.maxValue = 1;
234     desc.defaultValue = 0;
235     desc.isQuantized = true;
236     desc.quantizeStep = 1;
237     list.push_back(desc);
238
239     desc = ParameterDescriptor();
240     desc.identifier = "peakpickthreshold";
241     desc.name = "Peak Picker Threshold";
242     desc.minValue = 0;
243     desc.maxValue = 1;
244     desc.defaultValue = 0.3;
245     desc.isQuantized = false;
246     list.push_back(desc);
247
248     desc = ParameterDescriptor();
249     desc.identifier = "silencethreshold";
250     desc.name = "Silence Threshold";
251     desc.minValue = -120;
252     desc.maxValue = 0;
253     desc.defaultValue = -90;
254     desc.unit = "dB";
255     desc.isQuantized = false;
256     list.push_back(desc);
257
258     return list;
259 }
260
261 float
262 Notes::getParameter(std::string param) const
263 {
264     if (param == "onsettype") {
265         return m_onsettype;
266     } else if (param == "pitchtype") {
267         return m_pitchtype;
268     } else if (param == "peakpickthreshold") {
269         return m_threshold;
270     } else if (param == "silencethreshold") {
271         return m_silence;
272     } else if (param == "minpitch") {
273         return m_minpitch;
274     } else if (param == "maxpitch") {
275         return m_maxpitch;
276     } else if (param == "wraprange") {
277         return m_wrapRange ? 1.0 : 0.0;
278     } else if (param == "avoidleaps") {
279         return m_avoidLeaps ? 1.0 : 0.0;
280     } else {
281         return 0.0;
282     }
283 }
284
285 void
286 Notes::setParameter(std::string param, float value)
287 {
288     if (param == "onsettype") {
289         switch (lrintf(value)) {
290         case 0: m_onsettype = aubio_onset_energy; break;
291         case 1: m_onsettype = aubio_onset_specdiff; break;
292         case 2: m_onsettype = aubio_onset_hfc; break;
293         case 3: m_onsettype = aubio_onset_complex; break;
294         case 4: m_onsettype = aubio_onset_phase; break;
295         case 5: m_onsettype = aubio_onset_kl; break;
296         case 6: m_onsettype = aubio_onset_mkl; break;
297         }
298     } else if (param == "pitchtype") {
299         switch (lrintf(value)) {
300         case 0: m_pitchtype = aubio_pitch_yin; break;
301         case 1: m_pitchtype = aubio_pitch_mcomb; break;
302         case 2: m_pitchtype = aubio_pitch_schmitt; break;
303         case 3: m_pitchtype = aubio_pitch_fcomb; break;
304         case 4: m_pitchtype = aubio_pitch_yinfft; break;
305         }
306     } else if (param == "peakpickthreshold") {
307         m_threshold = value;
308     } else if (param == "silencethreshold") {
309         m_silence = value;
310     } else if (param == "minpitch") {
311         m_minpitch = lrintf(value);
312     } else if (param == "maxpitch") {
313         m_maxpitch = lrintf(value);
314     } else if (param == "wraprange") {
315         m_wrapRange = (value > 0.5);
316     } else if (param == "avoidleaps") {
317         m_avoidLeaps = (value > 0.5);
318     }
319 }
320
321 Notes::OutputList
322 Notes::getOutputDescriptors() const
323 {
324     OutputList list;
325
326     OutputDescriptor d;
327     d.identifier = "notes";
328     d.name = "Notes";
329     d.unit = "Hz";
330     d.hasFixedBinCount = true;
331
332     if (m_apiVersion == 1) {
333         d.binCount = 3;
334         d.binNames.push_back("Frequency");
335         d.binNames.push_back("Duration");
336         d.binNames.push_back("Velocity");
337     } else {
338         d.binCount = 2;
339         d.binNames.push_back("Frequency");
340         d.binNames.push_back("Velocity");
341         d.hasDuration = true;
342     }
343
344     d.hasKnownExtents = false;
345     d.isQuantized = false;
346     d.sampleType = OutputDescriptor::VariableSampleRate;
347     d.sampleRate = 0;
348     list.push_back(d);
349
350     return list;
351 }
352
353 Notes::FeatureSet
354 Notes::process(const float *const *inputBuffers, Vamp::RealTime timestamp)
355 {
356     for (size_t i = 0; i < m_stepSize; ++i) {
357         for (size_t j = 0; j < m_channelCount; ++j) {
358             fvec_write_sample(m_ibuf, inputBuffers[j][i], j, i);
359         }
360     }
361
362     aubio_pvoc_do(m_pv, m_ibuf, m_fftgrain);
363     aubio_onsetdetection(m_onsetdet, m_fftgrain, m_onset);
364
365     bool isonset = aubio_peakpick_pimrt(m_onset, m_peakpick);
366
367     float frequency = aubio_pitchdetection(m_pitchdet, m_ibuf);
368
369     m_notebuf.push_back(frequency);
370     if (m_notebuf.size() > m_median) m_notebuf.pop_front();
371
372     float level = aubio_level_detection(m_ibuf, m_silence);
373
374     FeatureSet returnFeatures;
375
376     if (isonset) {
377         if (level == 1.) {
378             isonset = false;
379             m_count = 0;
380             if (m_haveCurrent) pushNote(returnFeatures, timestamp);
381         } else {
382             m_count = 1;
383         }
384     } else {
385         if (m_count > 0) ++m_count;
386         if (m_count == m_median) {
387             if (m_haveCurrent) pushNote(returnFeatures, timestamp);
388             m_currentOnset = timestamp;
389             m_currentLevel = level;
390             m_haveCurrent = true;
391         }
392     }
393
394     m_lastTimeStamp = timestamp;
395     return returnFeatures;
396 }
397
398 Notes::FeatureSet
399 Notes::getRemainingFeatures()
400 {
401     FeatureSet returnFeatures;
402     if (m_haveCurrent) pushNote(returnFeatures, m_lastTimeStamp);
403     return returnFeatures;
404 }
405
406 void
407 Notes::pushNote(FeatureSet &fs, const Vamp::RealTime &offTime)
408 {
409     std::deque<float> toSort = m_notebuf;
410     std::sort(toSort.begin(), toSort.end());
411     float median = toSort[toSort.size()/2];
412     if (median < 45.0) return;
413
414     float freq = median;
415     int midiPitch = (int)floor(aubio_freqtomidi(freq) + 0.5);
416     
417     if (m_avoidLeaps) {
418         if (m_prevPitch >= 0) {
419             while (midiPitch < m_prevPitch - 12) {
420                 midiPitch += 12;
421                 freq *= 2;
422             }
423             while (midiPitch > m_prevPitch + 12) {
424                 midiPitch -= 12;
425                 freq /= 2;
426             }
427         }
428     }
429
430     while (midiPitch < m_minpitch) {
431         if (!m_wrapRange) return;
432         midiPitch += 12;
433         freq *= 2;
434     }
435
436     while (midiPitch > m_maxpitch) {
437         if (!m_wrapRange) return;
438         midiPitch -= 12;
439         freq /= 2;
440     }
441
442     m_prevPitch = midiPitch;
443
444     Feature feature;
445     feature.hasTimestamp = true;
446     if (m_currentOnset < m_delay) m_currentOnset = m_delay;
447     feature.timestamp = m_currentOnset - m_delay;
448     feature.values.push_back(freq);
449
450     if (m_apiVersion == 1) {
451         feature.values.push_back
452             (Vamp::RealTime::realTime2Frame
453              (offTime, lrintf(m_inputSampleRate)) -
454              Vamp::RealTime::realTime2Frame
455              (m_currentOnset, lrintf(m_inputSampleRate)));
456         feature.hasDuration = false;
457     } else {
458         feature.hasDuration = true;
459         feature.duration = offTime - m_currentOnset;
460     }
461
462     feature.values.push_back(m_currentLevel);
463     fs[0].push_back(feature);
464 }
465