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