* First bit of Vamp v2 work -- add an optional duration to features in
[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     }
51 }
52
53 Notes::~Notes()
54 {
55     if (m_onsetdet) aubio_onsetdetection_free(m_onsetdet);
56     if (m_pitchdet) del_aubio_pitchdetection(m_pitchdet);
57     if (m_ibuf) del_fvec(m_ibuf);
58     if (m_onset) del_fvec(m_onset);
59     if (m_fftgrain) del_cvec(m_fftgrain);
60     if (m_pv) del_aubio_pvoc(m_pv);
61     if (m_peakpick) del_aubio_peakpicker(m_peakpick);
62 }
63
64 string
65 Notes::getIdentifier() const
66 {
67     return "aubionotes";
68 }
69
70 string
71 Notes::getName() const
72 {
73     return "Aubio Note Tracker";
74 }
75
76 string
77 Notes::getDescription() const
78 {
79     return "Estimate note onset positions, pitches and durations";
80 }
81
82 string
83 Notes::getMaker() const
84 {
85     return "Paul Brossier (plugin by Chris Cannam)";
86 }
87
88 int
89 Notes::getPluginVersion() const
90 {
91     if (m_apiVersion == 1) return 2;
92     return 3;
93 }
94
95 string
96 Notes::getCopyright() const
97 {
98     return "GPL";
99 }
100
101 bool
102 Notes::initialise(size_t channels, size_t stepSize, size_t blockSize)
103 {
104     m_channelCount = channels;
105     m_stepSize = stepSize;
106     m_blockSize = blockSize;
107
108     size_t processingBlockSize;
109     if (m_onsettype == aubio_onset_energy ||
110         m_onsettype == aubio_onset_hfc) {
111         processingBlockSize = stepSize * 2;
112     } else {
113         processingBlockSize = stepSize * 4;
114     }
115
116     m_ibuf = new_fvec(stepSize, channels);
117     m_onset = new_fvec(1, channels);
118     m_fftgrain = new_cvec(processingBlockSize, channels);
119     m_pv = new_aubio_pvoc(processingBlockSize, stepSize, channels);
120     m_peakpick = new_aubio_peakpicker(m_threshold);
121
122     m_onsetdet = new_aubio_onsetdetection(m_onsettype, processingBlockSize, channels);
123
124     m_pitchdet = new_aubio_pitchdetection(processingBlockSize * 4,
125                                           stepSize,
126                                           channels,
127                                           lrintf(m_inputSampleRate),
128                                           m_pitchtype,
129                                           m_pitchmode);
130
131     m_count = 0;
132     m_delay = Vamp::RealTime::frame2RealTime((4 + m_median) * m_stepSize,
133                                        lrintf(m_inputSampleRate));
134     m_currentOnset = Vamp::RealTime::zeroTime;
135     m_haveCurrent = false;
136     m_prevPitch = -1;
137
138     return true;
139 }
140
141 void
142 Notes::reset()
143 {
144 }
145
146 size_t
147 Notes::getPreferredStepSize() const
148 {
149     return 512;
150 }
151
152 size_t
153 Notes::getPreferredBlockSize() const
154 {
155     return 4 * getPreferredStepSize();
156 }
157
158 Notes::ParameterList
159 Notes::getParameterDescriptors() const
160 {
161     ParameterList list;
162     
163     ParameterDescriptor desc;
164     desc.identifier = "onsettype";
165     desc.name = "Onset Detection Function Type";
166     desc.minValue = 0;
167     desc.maxValue = 6;
168     desc.defaultValue = (int)aubio_onset_complex;
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     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)aubio_pitch_yinfft;
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 = -90;
252     desc.unit = "dB";
253     desc.isQuantized = false;
254     list.push_back(desc);
255
256     return list;
257 }
258
259 float
260 Notes::getParameter(std::string param) const
261 {
262     if (param == "onsettype") {
263         return m_onsettype;
264     } else if (param == "pitchtype") {
265         return m_pitchtype;
266     } else if (param == "peakpickthreshold") {
267         return m_threshold;
268     } else if (param == "silencethreshold") {
269         return m_silence;
270     } else if (param == "minpitch") {
271         return m_minpitch;
272     } else if (param == "maxpitch") {
273         return m_maxpitch;
274     } else if (param == "wraprange") {
275         return m_wrapRange ? 1.0 : 0.0;
276     } else if (param == "avoidleaps") {
277         return m_avoidLeaps ? 1.0 : 0.0;
278     } else {
279         return 0.0;
280     }
281 }
282
283 void
284 Notes::setParameter(std::string param, float value)
285 {
286     if (param == "onsettype") {
287         switch (lrintf(value)) {
288         case 0: m_onsettype = aubio_onset_energy; break;
289         case 1: m_onsettype = aubio_onset_specdiff; break;
290         case 2: m_onsettype = aubio_onset_hfc; break;
291         case 3: m_onsettype = aubio_onset_complex; break;
292         case 4: m_onsettype = aubio_onset_phase; break;
293         case 5: m_onsettype = aubio_onset_kl; break;
294         case 6: m_onsettype = aubio_onset_mkl; break;
295         }
296     } else if (param == "pitchtype") {
297         switch (lrintf(value)) {
298         case 0: m_pitchtype = aubio_pitch_yin; break;
299         case 1: m_pitchtype = aubio_pitch_mcomb; break;
300         case 2: m_pitchtype = aubio_pitch_schmitt; break;
301         case 3: m_pitchtype = aubio_pitch_fcomb; break;
302         case 4: m_pitchtype = aubio_pitch_yinfft; break;
303         }
304     } else if (param == "peakpickthreshold") {
305         m_threshold = value;
306     } else if (param == "silencethreshold") {
307         m_silence = value;
308     } else if (param == "minpitch") {
309         m_minpitch = lrintf(value);
310     } else if (param == "maxpitch") {
311         m_maxpitch = lrintf(value);
312     } else if (param == "wraprange") {
313         m_wrapRange = (value > 0.5);
314     } else if (param == "avoidleaps") {
315         m_avoidLeaps = (value > 0.5);
316     }
317 }
318
319 Notes::OutputList
320 Notes::getOutputDescriptors() const
321 {
322     OutputList list;
323
324     OutputDescriptor d;
325     d.identifier = "notes";
326     d.name = "Notes";
327     d.unit = "Hz";
328     d.hasFixedBinCount = true;
329
330     if (m_apiVersion == 1) {
331         d.binCount = 3;
332         d.binNames.push_back("Frequency");
333         d.binNames.push_back("Duration");
334         d.binNames.push_back("Velocity");
335     } else {
336         d.binCount = 2;
337         d.binNames.push_back("Frequency");
338         d.binNames.push_back("Velocity");
339     }
340
341     d.hasKnownExtents = false;
342     d.isQuantized = false;
343     d.sampleType = OutputDescriptor::VariableSampleRate;
344     d.sampleRate = 0;
345     list.push_back(d);
346
347     return list;
348 }
349
350 Notes::FeatureSet
351 Notes::process(const float *const *inputBuffers, Vamp::RealTime timestamp)
352 {
353     for (size_t i = 0; i < m_stepSize; ++i) {
354         for (size_t j = 0; j < m_channelCount; ++j) {
355             fvec_write_sample(m_ibuf, inputBuffers[j][i], j, i);
356         }
357     }
358
359     aubio_pvoc_do(m_pv, m_ibuf, m_fftgrain);
360     aubio_onsetdetection(m_onsetdet, m_fftgrain, m_onset);
361
362     bool isonset = aubio_peakpick_pimrt(m_onset, m_peakpick);
363
364     float frequency = aubio_pitchdetection(m_pitchdet, m_ibuf);
365
366     m_notebuf.push_back(frequency);
367     if (m_notebuf.size() > m_median) m_notebuf.pop_front();
368
369     float level = aubio_level_detection(m_ibuf, m_silence);
370
371     FeatureSet returnFeatures;
372
373     if (isonset) {
374         if (level == 1.) {
375             isonset = false;
376             m_count = 0;
377             if (m_haveCurrent) pushNote(returnFeatures, timestamp);
378         } else {
379             m_count = 1;
380         }
381     } else {
382         if (m_count > 0) ++m_count;
383         if (m_count == m_median) {
384             if (m_haveCurrent) pushNote(returnFeatures, timestamp);
385             m_currentOnset = timestamp;
386             m_currentLevel = level;
387             m_haveCurrent = true;
388         }
389     }
390
391     m_lastTimeStamp = timestamp;
392     return returnFeatures;
393 }
394
395 Notes::FeatureSet
396 Notes::getRemainingFeatures()
397 {
398     FeatureSet returnFeatures;
399     if (m_haveCurrent) pushNote(returnFeatures, m_lastTimeStamp);
400     return returnFeatures;
401 }
402
403 void
404 Notes::pushNote(FeatureSet &fs, const Vamp::RealTime &offTime)
405 {
406     std::deque<float> toSort = m_notebuf;
407     std::sort(toSort.begin(), toSort.end());
408     float median = toSort[toSort.size()/2];
409     if (median < 45.0) return;
410
411     float freq = median;
412     int midiPitch = (int)floor(aubio_freqtomidi(freq) + 0.5);
413     
414     if (m_avoidLeaps) {
415         if (m_prevPitch >= 0) {
416             while (midiPitch < m_prevPitch - 12) {
417                 midiPitch += 12;
418                 freq *= 2;
419             }
420             while (midiPitch > m_prevPitch + 12) {
421                 midiPitch -= 12;
422                 freq /= 2;
423             }
424         }
425     }
426
427     while (midiPitch < m_minpitch) {
428         if (!m_wrapRange) return;
429         midiPitch += 12;
430         freq *= 2;
431     }
432
433     while (midiPitch > m_maxpitch) {
434         if (!m_wrapRange) return;
435         midiPitch -= 12;
436         freq /= 2;
437     }
438
439     m_prevPitch = midiPitch;
440
441     Feature feature;
442     feature.hasTimestamp = true;
443     if (m_currentOnset < m_delay) m_currentOnset = m_delay;
444     feature.timestamp = m_currentOnset - m_delay;
445     feature.values.push_back(freq);
446
447     if (m_apiVersion == 1) {
448         feature.values.push_back
449             (Vamp::RealTime::realTime2Frame
450              (offTime, lrintf(m_inputSampleRate)) -
451              Vamp::RealTime::realTime2Frame
452              (m_currentOnset, lrintf(m_inputSampleRate)));
453         feature.hasDuration = false;
454     } else {
455         feature.hasDuration = true;
456         feature.duration = offTime - m_currentOnset;
457     }
458
459     feature.values.push_back(m_currentLevel);
460     fs[0].push_back(feature);
461 }
462