python/lib/aubio/cut.py: clean-up, split in functions
[aubio.git] / python / lib / aubio / cut.py
1 #! /usr/bin/env python
2
3 """ this file was written by Paul Brossier
4   it is released under the GNU/GPL license.
5 """
6
7 import sys
8 import argparse
9
10 def aubio_cut_parser():
11     usage = "usage: %s [options] -i soundfile" % sys.argv[0]
12     usage += "\n help: %s -h" % sys.argv[0]
13     parser = argparse.ArgumentParser()
14     parser.add_argument("source_file", default=None, nargs='?',
15             help="input sound file to analyse", metavar = "<source_file>")
16     parser.add_argument("-i", "--input", action = "store", dest = "source_file2",
17             help="input sound file to analyse", metavar = "<source_file>")
18     parser.add_argument("-O","--onset-method",
19             action="store", dest="onset_method", default='default',
20             metavar = "<onset_method>",
21             help="onset detection method [default=default] \
22                     complexdomain|hfc|phase|specdiff|energy|kl|mkl")
23     # cutting methods
24     parser.add_argument("-b","--beat",
25             action="store_true", dest="beat", default=False,
26             help="use beat locations")
27     """
28     parser.add_argument("-S","--silencecut",
29             action="store_true", dest="silencecut", default=False,
30             help="use silence locations")
31     parser.add_argument("-s","--silence",
32             metavar = "<value>",
33             action="store", dest="silence", default=-70,
34             help="silence threshold [default=-70]")
35             """
36     # algorithm parameters
37     parser.add_argument("-r", "--samplerate",
38             metavar = "<freq>", type=int,
39             action="store", dest="samplerate", default=0,
40             help="samplerate at which the file should be represented")
41     parser.add_argument("-B","--bufsize",
42             action="store", dest="bufsize", default=512,
43             metavar = "<size>", type=int,
44             help="buffer size [default=512]")
45     parser.add_argument("-H","--hopsize",
46             metavar = "<size>", type=int,
47             action="store", dest="hopsize", default=256,
48             help="overlap size [default=256]")
49     parser.add_argument("-t","--onset-threshold",
50             metavar = "<value>", type=float,
51             action="store", dest="threshold", default=0.3,
52             help="onset peak picking threshold [default=0.3]")
53     parser.add_argument("-c","--cut",
54             action="store_true", dest="cut", default=False,
55             help="cut input sound file at detected labels \
56                     best used with option -L")
57
58     # minioi
59     parser.add_argument("-M","--minioi",
60             metavar = "<value>", type=str,
61             action="store", dest="minioi", default="12ms",
62             help="minimum inter onset interval [default=12ms]")
63
64     """
65     parser.add_argument("-D","--delay",
66             action = "store", dest = "delay", type = float,
67             metavar = "<seconds>", default=0,
68             help="number of seconds to take back [default=system]\
69                     default system delay is 3*hopsize/samplerate")
70     parser.add_argument("-C","--dcthreshold",
71             metavar = "<value>",
72             action="store", dest="dcthreshold", default=1.,
73             help="onset peak picking DC component [default=1.]")
74     parser.add_argument("-L","--localmin",
75             action="store_true", dest="localmin", default=False,
76             help="use local minima after peak detection")
77     parser.add_argument("-d","--derivate",
78             action="store_true", dest="derivate", default=False,
79             help="derivate onset detection function")
80     parser.add_argument("-z","--zerocross",
81             metavar = "<value>",
82             action="store", dest="zerothres", default=0.008,
83             help="zero-crossing threshold for slicing [default=0.00008]")
84             """
85     # plotting functions
86     """
87     parser.add_argument("-p","--plot",
88             action="store_true", dest="plot", default=False,
89             help="draw plot")
90     parser.add_argument("-x","--xsize",
91             metavar = "<size>",
92             action="store", dest="xsize", default=1.,
93             type=float, help="define xsize for plot")
94     parser.add_argument("-y","--ysize",
95             metavar = "<size>",
96             action="store", dest="ysize", default=1.,
97             type=float, help="define ysize for plot")
98     parser.add_argument("-f","--function",
99             action="store_true", dest="func", default=False,
100             help="print detection function")
101     parser.add_argument("-n","--no-onsets",
102             action="store_true", dest="nplot", default=False,
103             help="do not plot detected onsets")
104     parser.add_argument("-O","--outplot",
105             metavar = "<output_image>",
106             action="store", dest="outplot", default=None,
107             help="save plot to output.{ps,png}")
108     parser.add_argument("-F","--spectrogram",
109             action="store_true", dest="spectro", default=False,
110             help="add spectrogram to the plot")
111     """
112     parser.add_argument("-o","--output", type = str,
113             metavar = "<outputdir>",
114             action="store", dest="output_directory", default=None,
115             help="specify path where slices of the original file should be created")
116     parser.add_argument("--cut-until-nsamples", type = int,
117             metavar = "<samples>",
118             action = "store", dest = "cut_until_nsamples", default = None,
119             help="how many extra samples should be added at the end of each slice")
120     parser.add_argument("--cut-every-nslices", type = int,
121             metavar = "<samples>",
122             action = "store", dest = "cut_every_nslices", default = None,
123             help="how many slices should be groupped together at each cut")
124     parser.add_argument("--cut-until-nslices", type = int,
125             metavar = "<slices>",
126             action = "store", dest = "cut_until_nslices", default = None,
127             help="how many extra slices should be added at the end of each slice")
128
129     parser.add_argument("-v","--verbose",
130             action="store_true", dest="verbose", default=True,
131             help="make lots of noise [default]")
132     parser.add_argument("-q","--quiet",
133             action="store_false", dest="verbose", default=True,
134             help="be quiet")
135     return parser
136
137
138 def _cut_analyze(options):
139     source_file = options.source_file
140     hopsize = options.hopsize
141     bufsize = options.bufsize
142     samplerate = options.samplerate
143     source_file = options.source_file
144
145     # analyze pass
146     from aubio import onset, tempo, source
147
148     s = source(source_file, samplerate, hopsize)
149     if samplerate == 0:
150         samplerate = s.get_samplerate()
151         options.samplerate = samplerate
152
153     if options.beat:
154         o = tempo(options.onset_method, bufsize, hopsize, samplerate=samplerate)
155     else:
156         o = onset(options.onset_method, bufsize, hopsize, samplerate=samplerate)
157         if options.minioi:
158             if options.minioi.endswith('ms'):
159                 o.set_minioi_ms(int(options.minioi[:-2]))
160             elif options.minioi.endswith('s'):
161                 o.set_minioi_s(int(options.minioi[:-1]))
162             else:
163                 o.set_minioi(int(options.minioi))
164     o.set_threshold(options.threshold)
165
166     timestamps = []
167     total_frames = 0
168     while True:
169         samples, read = s()
170         if o(samples):
171             timestamps.append (o.get_last())
172             if options.verbose: print ("%.4f" % o.get_last_s())
173         total_frames += read
174         if read < hopsize: break
175     del s
176     return timestamps, total_frames
177
178 def _cut_slice(options, timestamps):
179     # cutting pass
180     nstamps = len(timestamps)
181     if nstamps > 0:
182         # generate output files
183         from aubio.slicing import slice_source_at_stamps
184         timestamps_end = None
185         if options.cut_every_nslices:
186             timestamps = timestamps[::options.cut_every_nslices]
187             nstamps = len(timestamps)
188         if options.cut_until_nslices and options.cut_until_nsamples:
189             print ("warning: using cut_until_nslices, but cut_until_nsamples is set")
190         if options.cut_until_nsamples:
191             timestamps_end = [t + options.cut_until_nsamples for t in timestamps[1:]]
192             timestamps_end += [ 1e120 ]
193         if options.cut_until_nslices:
194             timestamps_end = [t for t in timestamps[1 + options.cut_until_nslices:]]
195             timestamps_end += [ 1e120 ] * (options.cut_until_nslices + 1)
196         slice_source_at_stamps(options.source_file,
197                 timestamps, timestamps_end = timestamps_end,
198                 output_dir = options.output_directory,
199                 samplerate = options.samplerate)
200
201 def main():
202     parser = aubio_cut_parser()
203     options = parser.parse_args()
204     if not options.source_file and not options.source_file2:
205         sys.stderr.write("Error: no file name given\n")
206         parser.print_help()
207         sys.exit(1)
208     elif options.source_file2 is not None:
209         options.source_file = options.source_file2
210
211     # analysis
212     timestamps, total_frames = _cut_analyze(options)
213
214     # print some info
215     duration = float (total_frames) / float(options.samplerate)
216     base_info = '%(source_file)s' % {'source_file': options.source_file}
217     base_info += ' (total %(duration).2fs at %(samplerate)dHz)\n' % \
218             {'duration': duration, 'samplerate': options.samplerate}
219
220     info = "found %d timestamps in " % len(timestamps)
221     info += base_info
222     sys.stderr.write(info)
223
224     if options.cut:
225         _cut_slice(options, timestamps)
226         info = "created %d slices from " % len(timestamps)
227         info += base_info
228         sys.stderr.write(info)