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