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