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