2 # -*- coding: utf-8 -*-
4 """aubio command line tool
6 This file was written by Paul Brossier <piem@aubio.org> and is released under
9 Note: this script is mostly about parsing command line arguments. For more
10 readable code examples, check out the `python/demos` folder."""
17 epilog = 'use "%(prog)s <command> --help" for more info about each command'
18 parser = argparse.ArgumentParser(epilog=epilog)
19 parser.add_argument('-V', '--version', help="show version",
20 action="store_true", dest="show_version")
22 subparsers = parser.add_subparsers(title='commands', dest='command',
25 parser_add_subcommand_onset(subparsers)
26 parser_add_subcommand_pitch(subparsers)
27 parser_add_subcommand_beat(subparsers)
28 parser_add_subcommand_tempo(subparsers)
29 parser_add_subcommand_notes(subparsers)
30 parser_add_subcommand_mfcc(subparsers)
31 parser_add_subcommand_melbands(subparsers)
32 parser_add_subcommand_quiet(subparsers)
36 def parser_add_subcommand_onset(subparsers):
38 subparser = subparsers.add_parser('onset',
39 help='estimate time of onsets (beginning of sound event)',
40 formatter_class = argparse.ArgumentDefaultsHelpFormatter)
41 parser_add_input(subparser)
42 parser_add_buf_hop_size(subparser)
43 helpstr = "onset novelty function"
44 helpstr += " <default|energy|hfc|complex|phase|specdiff|kl|mkl|specflux>"
45 parser_add_method(subparser, helpstr=helpstr)
46 parser_add_threshold(subparser)
47 parser_add_silence(subparser)
48 parser_add_minioi(subparser)
49 parser_add_time_format(subparser)
50 parser_add_verbose_help(subparser)
51 subparser.set_defaults(process=process_onset)
53 def parser_add_subcommand_pitch(subparsers):
55 subparser = subparsers.add_parser('pitch',
56 help='estimate fundamental frequency (monophonic)')
57 parser_add_input(subparser)
58 parser_add_buf_hop_size(subparser, buf_size=2048)
59 helpstr = "pitch detection method <default|yinfft|yin|mcomb|fcomb|schmitt>"
60 parser_add_method(subparser, helpstr=helpstr)
61 parser_add_threshold(subparser)
62 parser_add_pitch_unit(subparser)
63 parser_add_silence(subparser)
64 parser_add_time_format(subparser)
65 parser_add_verbose_help(subparser)
66 subparser.set_defaults(process=process_pitch)
68 def parser_add_subcommand_beat(subparsers):
70 subparser = subparsers.add_parser('beat',
71 help='estimate location of beats')
72 parser_add_input(subparser)
73 parser_add_buf_hop_size(subparser, buf_size=1024, hop_size=512)
74 parser_add_time_format(subparser)
75 parser_add_verbose_help(subparser)
76 subparser.set_defaults(process=process_beat)
78 def parser_add_subcommand_tempo(subparsers):
80 subparser = subparsers.add_parser('tempo',
81 help='estimate overall tempo in bpm')
82 parser_add_input(subparser)
83 parser_add_buf_hop_size(subparser, buf_size=1024, hop_size=512)
84 parser_add_time_format(subparser)
85 parser_add_verbose_help(subparser)
86 subparser.set_defaults(process=process_tempo)
88 def parser_add_subcommand_notes(subparsers):
90 subparser = subparsers.add_parser('notes',
91 help='estimate midi-like notes (monophonic)')
92 parser_add_input(subparser)
93 parser_add_buf_hop_size(subparser)
94 parser_add_time_format(subparser)
95 parser_add_verbose_help(subparser)
96 subparser.set_defaults(process=process_notes)
98 def parser_add_subcommand_mfcc(subparsers):
100 subparser = subparsers.add_parser('mfcc',
101 help='extract Mel-Frequency Cepstrum Coefficients')
102 parser_add_input(subparser)
103 parser_add_buf_hop_size(subparser)
104 parser_add_time_format(subparser)
105 parser_add_verbose_help(subparser)
106 subparser.set_defaults(process=process_mfcc)
108 def parser_add_subcommand_melbands(subparsers):
109 # melbands subcommand
110 subparser = subparsers.add_parser('melbands',
111 help='extract energies in Mel-frequency bands')
112 parser_add_input(subparser)
113 parser_add_buf_hop_size(subparser)
114 parser_add_time_format(subparser)
115 parser_add_verbose_help(subparser)
116 subparser.set_defaults(process=process_melbands)
118 def parser_add_subcommand_quiet(subparsers):
120 subparser = subparsers.add_parser('quiet',
122 parser_add_input(subparser)
123 parser_add_hop_size(subparser)
124 parser_add_silence(subparser)
125 parser_add_time_format(subparser)
126 parser_add_verbose_help(subparser)
127 subparser.set_defaults(process=process_quiet)
129 def parser_add_input(parser):
130 parser.add_argument("source_uri", default=None, nargs='?',
131 help="input sound file to analyse", metavar = "<source_uri>")
132 parser.add_argument("-i", "--input", dest = "source_uri2",
133 help="input sound file to analyse", metavar = "<source_uri>")
134 parser.add_argument("-r", "--samplerate",
135 metavar = "<freq>", type=int,
136 action="store", dest="samplerate", default=0,
137 help="samplerate at which the file should be represented")
139 def parser_add_verbose_help(parser):
140 parser.add_argument("-v","--verbose",
141 action="count", dest="verbose", default=1,
142 help="make lots of noise [default]")
143 parser.add_argument("-q","--quiet",
144 action="store_const", dest="verbose", const=0,
147 def parser_add_buf_hop_size(parser, buf_size=512, hop_size=256):
148 parser_add_buf_size(parser, buf_size=buf_size)
149 parser_add_hop_size(parser, hop_size=hop_size)
151 def parser_add_buf_size(parser, buf_size=512):
152 parser.add_argument("-B","--bufsize",
153 action="store", dest="buf_size", default=buf_size,
154 metavar = "<size>", type=int,
155 help="buffer size [default=%d]" % buf_size)
157 def parser_add_hop_size(parser, hop_size=256):
158 parser.add_argument("-H","--hopsize",
159 metavar = "<size>", type=int,
160 action="store", dest="hop_size", default=hop_size,
161 help="overlap size [default=%d]" % hop_size)
163 def parser_add_method(parser, method='default', helpstr='method'):
164 parser.add_argument("-m","--method",
165 metavar = "<method>", type=str,
166 action="store", dest="method", default=method,
167 help="%s [default=%s]" % (helpstr, method))
169 def parser_add_threshold(parser, default=None):
170 parser.add_argument("-t","--threshold",
171 metavar = "<threshold>", type=float,
172 action="store", dest="threshold", default=default,
173 help="threshold [default=%s]" % default)
175 def parser_add_silence(parser):
176 parser.add_argument("-s", "--silence",
177 metavar = "<value>", type=float,
178 action="store", dest="silence", default=-70,
179 help="silence threshold")
181 def parser_add_minioi(parser):
182 parser.add_argument("-M", "--minioi",
183 metavar = "<value>", type=str,
184 action="store", dest="minioi", default="12ms",
185 help="minimum Inter-Onset Interval")
187 def parser_add_pitch_unit(parser, default="Hz"):
188 help_str = "frequency unit, should be one of Hz, midi, bin, cent"
189 help_str += " [default=%s]" % default
190 parser.add_argument("-u", "--pitch-unit",
191 metavar = "<value>", type=str,
192 action="store", dest="pitch_unit", default=default,
195 def parser_add_time_format(parser):
196 helpstr = "select time values output format (samples, ms, seconds)"
197 helpstr += " [default=seconds]"
198 parser.add_argument("-T", "--time-format",
206 def samples2seconds(n_frames, samplerate):
207 return "%f\t" % (n_frames / float(samplerate))
209 def samples2milliseconds(n_frames, samplerate):
210 return "%f\t" % (1000. * n_frames / float(samplerate))
212 def samples2samples(n_frames, samplerate):
213 return "%d\t" % n_frames
216 if mode is None or mode == 'seconds' or mode == 's':
217 return samples2seconds
218 elif mode == 'ms' or mode == 'milliseconds':
219 return samples2milliseconds
220 elif mode == 'samples':
221 return samples2samples
223 raise ValueError("invalid time format '%s'" % mode)
225 # definition of processing classes
227 class default_process(object):
228 def __init__(self, args):
229 if 'time_format' in args:
230 self.time2string = timefunc(args.time_format)
231 if args.verbose > 2 and hasattr(self, 'options'):
232 name = type(self).__name__.split('_')[1]
233 optstr = ' '.join(['running', name, 'with options', repr(self.options), '\n'])
234 sys.stderr.write(optstr)
235 def flush(self, n_frames, samplerate):
236 # optionally called at the end of process
239 def parse_options(self, args, valid_opts):
240 # get any valid options found in a dictionnary of arguments
241 options = {k :v for k,v in vars(args).items() if k in valid_opts}
242 self.options = options
244 def remap_pvoc_options(self, options):
245 # FIXME: we need to remap buf_size to win_s, hop_size to hop_s
246 # adjust python/ext/py-phasevoc.c to understand buf_size/hop_size
247 if 'buf_size' in options:
248 options['win_s'] = options['buf_size']
249 del options['buf_size']
250 if 'hop_size' in options:
251 options['hop_s'] = options['hop_size']
252 del options['hop_size']
253 self.options = options
255 class process_onset(default_process):
256 valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
257 def __init__(self, args):
258 self.parse_options(args, self.valid_opts)
259 self.onset = aubio.onset(**self.options)
260 if args.threshold is not None:
261 self.onset.set_threshold(args.threshold)
263 if args.minioi.endswith('ms'):
264 self.onset.set_minioi_ms(float(args.minioi[:-2]))
265 elif args.minioi.endswith('s'):
266 self.onset.set_minioi_s(float(args.minioi[:-1]))
268 self.onset.set_minioi(int(args.minioi))
270 self.onset.set_silence(args.silence)
271 super(process_onset, self).__init__(args)
272 def __call__(self, block):
273 return self.onset(block)
274 def repr_res(self, res, frames_read, samplerate):
276 outstr = self.time2string(self.onset.get_last(), samplerate)
277 sys.stdout.write(outstr + '\n')
279 class process_pitch(default_process):
280 valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
281 def __init__(self, args):
282 self.parse_options(args, self.valid_opts)
283 self.pitch = aubio.pitch(**self.options)
284 if args.pitch_unit is not None:
285 self.pitch.set_unit(args.pitch_unit)
286 if args.threshold is not None:
287 self.pitch.set_tolerance(args.threshold)
288 if args.silence is not None:
289 self.pitch.set_silence(args.silence)
290 super(process_pitch, self).__init__(args)
291 def __call__(self, block):
292 return self.pitch(block)
293 def repr_res(self, res, frames_read, samplerate):
294 fmt_out = self.time2string(frames_read, samplerate)
295 sys.stdout.write(fmt_out + "%.6f\n" % res[0])
297 class process_beat(default_process):
298 valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
299 def __init__(self, args):
300 self.parse_options(args, self.valid_opts)
301 self.tempo = aubio.tempo(**self.options)
302 super(process_beat, self).__init__(args)
303 def __call__(self, block):
304 return self.tempo(block)
305 def repr_res(self, res, frames_read, samplerate):
307 outstr = self.time2string(self.tempo.get_last(), samplerate)
308 sys.stdout.write(outstr + '\n')
310 class process_tempo(process_beat):
311 def __init__(self, args):
312 super(process_tempo, self).__init__(args)
313 self.beat_locations = []
314 def repr_res(self, res, frames_read, samplerate):
316 self.beat_locations.append(self.tempo.get_last_s())
317 def flush(self, frames_read, samplerate):
319 if len(self.beat_locations) < 2:
320 outstr = "unknown bpm"
322 bpms = 60./ np.diff(self.beat_locations)
323 median_bpm = np.mean(bpms)
324 if len(self.beat_locations) < 10:
325 outstr = "%.2f bpm (uncertain)" % median_bpm
327 outstr = "%.2f bpm" % median_bpm
328 sys.stdout.write(outstr + '\n')
330 class process_notes(default_process):
331 valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
332 def __init__(self, args):
333 self.parse_options(args, self.valid_opts)
334 self.notes = aubio.notes(**self.options)
335 super(process_notes, self).__init__(args)
336 def __call__(self, block):
337 return self.notes(block)
338 def repr_res(self, res, frames_read, samplerate):
339 if res[2] != 0: # note off
340 fmt_out = self.time2string(frames_read, samplerate)
341 sys.stdout.write(fmt_out + '\n')
342 if res[0] != 0: # note on
344 fmt_out = "%f\t" % lastmidi
345 fmt_out += self.time2string(frames_read, samplerate)
346 sys.stdout.write(fmt_out) # + '\t')
347 def flush(self, frames_read, samplerate):
348 eof = self.time2string(frames_read, samplerate)
349 sys.stdout.write(eof + '\n')
351 class process_mfcc(default_process):
352 def __init__(self, args):
353 valid_opts1 = ['hop_size', 'buf_size']
354 self.parse_options(args, valid_opts1)
355 self.remap_pvoc_options(self.options)
356 self.pv = aubio.pvoc(**self.options)
358 valid_opts2 = ['buf_size', 'n_filters', 'n_coeffs', 'samplerate']
359 self.parse_options(args, valid_opts2)
360 self.mfcc = aubio.mfcc(**self.options)
362 # remember all options
363 self.parse_options(args, list(set(valid_opts1 + valid_opts2)))
365 super(process_mfcc, self).__init__(args)
367 def __call__(self, block):
368 fftgrain = self.pv(block)
369 return self.mfcc(fftgrain)
370 def repr_res(self, res, frames_read, samplerate):
371 fmt_out = self.time2string(frames_read, samplerate)
372 fmt_out += ' '.join(["% 9.7f" % f for f in res.tolist()])
373 sys.stdout.write(fmt_out + '\n')
375 class process_melbands(default_process):
376 def __init__(self, args):
378 valid_opts = ['hop_size', 'buf_size']
379 self.parse_options(args, valid_opts)
380 self.remap_pvoc_options(self.options)
381 self.pv = aubio.pvoc(**self.options)
383 valid_opts = ['buf_size', 'n_filters']
384 self.parse_options(args, valid_opts)
385 self.remap_pvoc_options(self.options)
386 self.filterbank = aubio.filterbank(**self.options)
387 self.filterbank.set_mel_coeffs_slaney(args.samplerate)
389 super(process_melbands, self).__init__(args)
390 def __call__(self, block):
391 fftgrain = self.pv(block)
392 return self.filterbank(fftgrain)
393 def repr_res(self, res, frames_read, samplerate):
394 fmt_out = self.time2string(frames_read, samplerate)
395 fmt_out += ' '.join(["% 9.7f" % f for f in res.tolist()])
396 sys.stdout.write(fmt_out + '\n')
398 class process_quiet(default_process):
399 def __init__(self, args):
401 valid_opts = ['hop_size', 'silence']
402 self.parse_options(args, valid_opts)
403 self.issilence = None
406 if args.silence is not None:
407 self.silence = args.silence
408 super(process_quiet, self).__init__(args)
410 def __call__(self, block):
411 if aubio.silence_detection(block, self.silence) == 1:
412 if self.wassilence == 1:
418 if self.wassilence == 0:
424 def repr_res(self, res, frames_read, samplerate):
426 if self.issilence == -1:
428 if self.issilence == 2:
430 if fmt_out is not None:
431 fmt_out += self.time2string(frames_read, samplerate)
432 sys.stdout.write(fmt_out + '\n')
435 parser = aubio_parser()
436 args = parser.parse_args()
437 if 'show_version' in args and args.show_version:
438 sys.stdout.write('aubio version ' + aubio.version + '\n')
440 elif 'verbose' in args and args.verbose > 3:
441 sys.stderr.write('aubio version ' + aubio.version + '\n')
442 if 'command' not in args or args.command is None:
443 # no command given, print help and return 1
446 elif not args.source_uri and not args.source_uri2:
447 sys.stderr.write("Error: a source is required\n")
450 elif args.source_uri2 is not None:
451 args.source_uri = args.source_uri2
454 with aubio.source(args.source_uri, hop_size=args.hop_size,
455 samplerate=args.samplerate) as a_source:
456 # always update args.samplerate to native samplerate, in case
457 # source was opened with args.samplerate=0
458 args.samplerate = a_source.samplerate
459 # create the processor for this subcommand
460 processor = args.process(args)
463 # read new block from source
464 block, read = a_source()
465 # execute processor on this block
466 res = processor(block)
467 # print results for this block
469 processor.repr_res(res, frames_read, a_source.samplerate)
470 # increment total number of frames read
472 # exit loop at end of file
473 if read < a_source.hop_size: break
474 # flush the processor if needed
475 processor.flush(frames_read, a_source.samplerate)
477 fmt_string = "read {:.2f}s"
478 fmt_string += " ({:d} samples in {:d} blocks of {:d})"
479 fmt_string += " from {:s} at {:d}Hz\n"
480 sys.stderr.write(fmt_string.format(
481 frames_read/float(a_source.samplerate),
483 frames_read // a_source.hop_size + 1,
486 a_source.samplerate))
487 except KeyboardInterrupt: