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