source: python/lib/aubio/cmd.py @ 67ee29f

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5
Last change on this file since 67ee29f was 67ee29f, checked in by Paul Brossier <piem@piem.org>, 7 years ago

python/lib/aubio/cmd.py: split buffer and hop sizes

  • Property mode set to 100644
File size: 16.5 KB
Line 
1#! /usr/bin/env python
2# -*- coding: utf-8 -*-
3
4"""aubio command line tool
5
6This file was written by Paul Brossier <piem@aubio.org> and is released under
7the GNU/GPL v3.
8
9Note: this script is mostly about parsing command line arguments. For more
10readable code examples, check out the `python/demos` folder."""
11
12import sys
13import argparse
14import aubio
15
16def aubio_parser():
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")
21
22    subparsers = parser.add_subparsers(title='commands', dest='command',
23            metavar="")
24
25    # onset subcommand
26    subparser = subparsers.add_parser('onset',
27            help='estimate time of onsets (beginning of sound event)',
28            formatter_class = argparse.ArgumentDefaultsHelpFormatter)
29    parser_add_input(subparser)
30    parser_add_buf_hop_size(subparser)
31    helpstr = "onset novelty function"
32    helpstr += " <default|energy|hfc|complex|phase|specdiff|kl|mkl|specflux>"
33    parser_add_method(subparser, helpstr=helpstr)
34    parser_add_threshold(subparser)
35    parser_add_silence(subparser)
36    parser_add_minioi(subparser)
37    parser_add_time_format(subparser)
38    parser_add_verbose_help(subparser)
39    subparser.set_defaults(process=process_onset)
40
41    # pitch subcommand
42    subparser = subparsers.add_parser('pitch',
43            help='estimate fundamental frequency (monophonic)')
44    parser_add_input(subparser)
45    parser_add_buf_hop_size(subparser, buf_size=2048)
46    helpstr = "pitch detection method <default|yinfft|yin|mcomb|fcomb|schmitt>"
47    parser_add_method(subparser, helpstr=helpstr)
48    parser_add_threshold(subparser)
49    parser_add_pitch_unit(subparser)
50    parser_add_silence(subparser)
51    parser_add_time_format(subparser)
52    parser_add_verbose_help(subparser)
53    subparser.set_defaults(process=process_pitch)
54
55    # beat subcommand
56    subparser = subparsers.add_parser('beat',
57            help='estimate location of beats')
58    parser_add_input(subparser)
59    parser_add_buf_hop_size(subparser, buf_size=1024, hop_size=512)
60    parser_add_time_format(subparser)
61    parser_add_verbose_help(subparser)
62    subparser.set_defaults(process=process_beat)
63
64    # tempo subcommand
65    subparser = subparsers.add_parser('tempo',
66            help='estimate overall tempo in bpm')
67    parser_add_input(subparser)
68    parser_add_buf_hop_size(subparser, buf_size=1024, hop_size=512)
69    parser_add_time_format(subparser)
70    parser_add_verbose_help(subparser)
71    subparser.set_defaults(process=process_tempo)
72
73    # notes subcommand
74    subparser = subparsers.add_parser('notes',
75            help='estimate midi-like notes (monophonic)')
76    parser_add_input(subparser)
77    parser_add_buf_hop_size(subparser)
78    parser_add_time_format(subparser)
79    parser_add_verbose_help(subparser)
80    subparser.set_defaults(process=process_notes)
81
82    # mfcc subcommand
83    subparser = subparsers.add_parser('mfcc',
84            help='extract Mel-Frequency Cepstrum Coefficients')
85    parser_add_input(subparser)
86    parser_add_buf_hop_size(subparser)
87    parser_add_time_format(subparser)
88    parser_add_verbose_help(subparser)
89    subparser.set_defaults(process=process_mfcc)
90
91    # melbands subcommand
92    subparser = subparsers.add_parser('melbands',
93            help='extract energies in Mel-frequency bands')
94    parser_add_input(subparser)
95    parser_add_buf_hop_size(subparser)
96    parser_add_time_format(subparser)
97    parser_add_verbose_help(subparser)
98    subparser.set_defaults(process=process_melbands)
99
100    return parser
101
102def parser_add_input(parser):
103    parser.add_argument("source_uri", default=None, nargs='?',
104            help="input sound file to analyse", metavar = "<source_uri>")
105    parser.add_argument("-i", "--input", dest = "source_uri2",
106            help="input sound file to analyse", metavar = "<source_uri>")
107    parser.add_argument("-r", "--samplerate",
108            metavar = "<freq>", type=int,
109            action="store", dest="samplerate", default=0,
110            help="samplerate at which the file should be represented")
111
112def parser_add_verbose_help(parser):
113    parser.add_argument("-v","--verbose",
114            action="count", dest="verbose", default=1,
115            help="make lots of noise [default]")
116    parser.add_argument("-q","--quiet",
117            action="store_const", dest="verbose", const=0,
118            help="be quiet")
119
120def parser_add_buf_hop_size(parser, buf_size=512, hop_size=256):
121    parser_add_buf_size(parser, buf_size=buf_size)
122    parser_add_hop_size(parser, hop_size=hop_size)
123
124def parser_add_buf_size(parser, buf_size=512):
125    parser.add_argument("-B","--bufsize",
126            action="store", dest="buf_size", default=buf_size,
127            metavar = "<size>", type=int,
128            help="buffer size [default=%d]" % buf_size)
129
130def parser_add_hop_size(parser, hop_size=256):
131    parser.add_argument("-H","--hopsize",
132            metavar = "<size>", type=int,
133            action="store", dest="hop_size", default=hop_size,
134            help="overlap size [default=%d]" % hop_size)
135
136def parser_add_method(parser, method='default', helpstr='method'):
137    parser.add_argument("-m","--method",
138            metavar = "<method>", type=str,
139            action="store", dest="method", default=method,
140            help="%s [default=%s]" % (helpstr, method))
141
142def parser_add_threshold(parser, default=None):
143    parser.add_argument("-t","--threshold",
144            metavar = "<threshold>", type=float,
145            action="store", dest="threshold", default=default,
146            help="threshold [default=%s]" % default)
147
148def parser_add_silence(parser):
149    parser.add_argument("-s", "--silence",
150            metavar = "<value>", type=float,
151            action="store", dest="silence", default=-70,
152            help="silence threshold")
153
154def parser_add_minioi(parser):
155    parser.add_argument("-M", "--minioi",
156            metavar = "<value>", type=str,
157            action="store", dest="minioi", default="12ms",
158            help="minimum Inter-Onset Interval")
159
160def parser_add_pitch_unit(parser, default="Hz"):
161    help_str = "frequency unit, should be one of Hz, midi, bin, cent"
162    help_str += " [default=%s]" % default
163    parser.add_argument("-u", "--pitch-unit",
164            metavar = "<value>", type=str,
165            action="store", dest="pitch_unit", default=default,
166            help=help_str)
167
168def parser_add_time_format(parser):
169    helpstr = "select time values output format (samples, ms, seconds)"
170    helpstr += " [default=seconds]"
171    parser.add_argument("-T", "--time-format",
172             metavar='format',
173             dest="time_format",
174             default=None,
175             help=helpstr)
176
177# some utilities
178
179def samples2seconds(n_frames, samplerate):
180    return "%f\t" % (n_frames / float(samplerate))
181
182def samples2milliseconds(n_frames, samplerate):
183    return "%f\t" % (1000. * n_frames / float(samplerate))
184
185def samples2samples(n_frames, samplerate):
186    return "%d\t" % n_frames
187
188def timefunc(mode):
189    if mode is None or mode == 'seconds' or mode == 's':
190        return samples2seconds
191    elif mode == 'ms' or mode == 'milliseconds':
192        return samples2milliseconds
193    elif mode == 'samples':
194        return samples2samples
195    else:
196        raise ValueError("invalid time format '%s'" % mode)
197
198# definition of processing classes
199
200class default_process(object):
201    def __init__(self, args):
202        if 'time_format' in args:
203            self.time2string = timefunc(args.time_format)
204        if args.verbose > 2 and hasattr(self, 'options'):
205            name = type(self).__name__.split('_')[1]
206            optstr = ' '.join(['running', name, 'with options', repr(self.options), '\n'])
207            sys.stderr.write(optstr)
208    def flush(self, n_frames, samplerate):
209        # optionally called at the end of process
210        pass
211
212    def parse_options(self, args, valid_opts):
213        # get any valid options found in a dictionnary of arguments
214        options = {k :v for k,v in vars(args).items() if k in valid_opts}
215        self.options = options
216
217    def remap_pvoc_options(self, options):
218        # FIXME: we need to remap buf_size to win_s, hop_size to hop_s
219        # adjust python/ext/py-phasevoc.c to understand buf_size/hop_size
220        if 'buf_size' in options:
221            options['win_s'] = options['buf_size']
222            del options['buf_size']
223        if 'hop_size' in options:
224            options['hop_s'] = options['hop_size']
225            del options['hop_size']
226        self.options = options
227
228class process_onset(default_process):
229    valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
230    def __init__(self, args):
231        self.parse_options(args, self.valid_opts)
232        self.onset = aubio.onset(**self.options)
233        if args.threshold is not None:
234            self.onset.set_threshold(args.threshold)
235        if args.minioi:
236            if args.minioi.endswith('ms'):
237                self.onset.set_minioi_ms(float(args.minioi[:-2]))
238            elif args.minioi.endswith('s'):
239                self.onset.set_minioi_s(float(args.minioi[:-1]))
240            else:
241                self.onset.set_minioi(int(args.minioi))
242        if args.silence:
243            self.onset.set_silence(args.silence)
244        super(process_onset, self).__init__(args)
245    def __call__(self, block):
246        return self.onset(block)
247    def repr_res(self, res, frames_read, samplerate):
248        if res[0] != 0:
249            outstr = self.time2string(self.onset.get_last(), samplerate)
250            sys.stdout.write(outstr + '\n')
251
252class process_pitch(default_process):
253    valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
254    def __init__(self, args):
255        self.parse_options(args, self.valid_opts)
256        self.pitch = aubio.pitch(**self.options)
257        if args.pitch_unit is not None:
258            self.pitch.set_unit(args.pitch_unit)
259        if args.threshold is not None:
260            self.pitch.set_tolerance(args.threshold)
261        if args.silence is not None:
262            self.pitch.set_silence(args.silence)
263        super(process_pitch, self).__init__(args)
264    def __call__(self, block):
265        return self.pitch(block)
266    def repr_res(self, res, frames_read, samplerate):
267        fmt_out = self.time2string(frames_read, samplerate)
268        sys.stdout.write(fmt_out + "%.6f\n" % res[0])
269
270class process_beat(default_process):
271    valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
272    def __init__(self, args):
273        self.parse_options(args, self.valid_opts)
274        self.tempo = aubio.tempo(**self.options)
275        super(process_beat, self).__init__(args)
276    def __call__(self, block):
277        return self.tempo(block)
278    def repr_res(self, res, frames_read, samplerate):
279        if res[0] != 0:
280            outstr = self.time2string(self.tempo.get_last(), samplerate)
281            sys.stdout.write(outstr + '\n')
282
283class process_tempo(process_beat):
284    def __init__(self, args):
285        super(process_tempo, self).__init__(args)
286        self.beat_locations = []
287    def repr_res(self, res, frames_read, samplerate):
288        if res[0] != 0:
289            self.beat_locations.append(self.tempo.get_last_s())
290    def flush(self, frames_read, samplerate):
291        import numpy as np
292        if len(self.beat_locations) < 2:
293            outstr = "unknown bpm"
294        else:
295            bpms = 60./ np.diff(self.beat_locations)
296            median_bpm = np.mean(bpms)
297            if len(self.beat_locations) < 10:
298                outstr = "%.2f bpm (uncertain)" % median_bpm
299            else:
300                outstr = "%.2f bpm" % median_bpm
301        sys.stdout.write(outstr + '\n')
302
303class process_notes(default_process):
304    valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
305    def __init__(self, args):
306        self.parse_options(args, self.valid_opts)
307        self.notes = aubio.notes(**self.options)
308        super(process_notes, self).__init__(args)
309    def __call__(self, block):
310        return self.notes(block)
311    def repr_res(self, res, frames_read, samplerate):
312        if res[2] != 0: # note off
313            fmt_out = self.time2string(frames_read, samplerate)
314            sys.stdout.write(fmt_out + '\n')
315        if res[0] != 0: # note on
316            lastmidi = res[0]
317            fmt_out = "%f\t" % lastmidi
318            fmt_out += self.time2string(frames_read, samplerate)
319            sys.stdout.write(fmt_out) # + '\t')
320    def flush(self, frames_read, samplerate):
321        eof = self.time2string(frames_read, samplerate)
322        sys.stdout.write(eof + '\n')
323
324class process_mfcc(default_process):
325    def __init__(self, args):
326        valid_opts1 = ['hop_size', 'buf_size']
327        self.parse_options(args, valid_opts1)
328        self.remap_pvoc_options(self.options)
329        self.pv = aubio.pvoc(**self.options)
330
331        valid_opts2 = ['buf_size', 'n_filters', 'n_coeffs', 'samplerate']
332        self.parse_options(args, valid_opts2)
333        self.mfcc = aubio.mfcc(**self.options)
334
335        # remember all options
336        self.parse_options(args, list(set(valid_opts1 + valid_opts2)))
337
338        super(process_mfcc, self).__init__(args)
339
340    def __call__(self, block):
341        fftgrain = self.pv(block)
342        return self.mfcc(fftgrain)
343    def repr_res(self, res, frames_read, samplerate):
344        fmt_out = self.time2string(frames_read, samplerate)
345        fmt_out += ' '.join(["% 9.7f" % f for f in res.tolist()])
346        sys.stdout.write(fmt_out + '\n')
347
348class process_melbands(default_process):
349    def __init__(self, args):
350        self.args = args
351        valid_opts = ['hop_size', 'buf_size']
352        self.parse_options(args, valid_opts)
353        self.remap_pvoc_options(self.options)
354        self.pv = aubio.pvoc(**self.options)
355
356        valid_opts = ['buf_size', 'n_filters']
357        self.parse_options(args, valid_opts)
358        self.remap_pvoc_options(self.options)
359        self.filterbank = aubio.filterbank(**self.options)
360        self.filterbank.set_mel_coeffs_slaney(args.samplerate)
361
362        super(process_melbands, self).__init__(args)
363    def __call__(self, block):
364        fftgrain = self.pv(block)
365        return self.filterbank(fftgrain)
366    def repr_res(self, res, frames_read, samplerate):
367        fmt_out = self.time2string(frames_read, samplerate)
368        fmt_out += ' '.join(["% 9.7f" % f for f in res.tolist()])
369        sys.stdout.write(fmt_out + '\n')
370
371def main():
372    parser = aubio_parser()
373    args = parser.parse_args()
374    if 'show_version' in args and args.show_version:
375        sys.stdout.write('aubio version ' + aubio.version + '\n')
376        sys.exit(0)
377    elif 'verbose' in args and args.verbose > 3:
378        sys.stderr.write('aubio version ' + aubio.version + '\n')
379    if 'command' not in args or args.command is None:
380        # no command given, print help and return 1
381        parser.print_help()
382        sys.exit(1)
383    elif not args.source_uri and not args.source_uri2:
384        sys.stderr.write("Error: a source is required\n")
385        parser.print_help()
386        sys.exit(1)
387    elif args.source_uri2 is not None:
388        args.source_uri = args.source_uri2
389    try:
390        # open source_uri
391        with aubio.source(args.source_uri, hop_size=args.hop_size,
392                samplerate=args.samplerate) as a_source:
393            # always update args.samplerate to native samplerate, in case
394            # source was opened with args.samplerate=0
395            args.samplerate = a_source.samplerate
396            # create the processor for this subcommand
397            processor = args.process(args)
398            frames_read = 0
399            while True:
400                # read new block from source
401                block, read = a_source()
402                # execute processor on this block
403                res = processor(block)
404                # print results for this block
405                if args.verbose > 0:
406                    processor.repr_res(res, frames_read, a_source.samplerate)
407                # increment total number of frames read
408                frames_read += read
409                # exit loop at end of file
410                if read < a_source.hop_size: break
411            # flush the processor if needed
412            processor.flush(frames_read, a_source.samplerate)
413            if args.verbose > 1:
414                fmt_string = "read {:.2f}s"
415                fmt_string += " ({:d} samples in {:d} blocks of {:d})"
416                fmt_string += " from {:s} at {:d}Hz\n"
417                sys.stderr.write(fmt_string.format(
418                        frames_read/float(a_source.samplerate),
419                        frames_read,
420                        frames_read // a_source.hop_size + 1,
421                        a_source.hop_size,
422                        a_source.uri,
423                        a_source.samplerate))
424    except KeyboardInterrupt:
425        sys.exit(1)
Note: See TracBrowser for help on using the repository browser.