source: python/aubio/tasks.py @ 0fe9aab

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5pitchshiftsamplertimestretchyinfft+
Last change on this file since 0fe9aab was 300adc3, checked in by Paul Brossier <piem@altern.org>, 19 years ago

update taskpitch, use oplots instead of gnuplot
update taskpitch, use oplots instead of gnuplot

  • Property mode set to 100644
File size: 22.1 KB
RevLine 
[5e491b3b]1from aubioclass import * 
2
[7473074]3def get_onset_mode(nvalue):
[5e491b3b]4        """ utility function to convert a string to aubio_onsetdetection_type """
[7473074]5        if   nvalue == 'complexdomain' or nvalue == 'complex' :
6                 return aubio_onset_complex
7        elif nvalue == 'hfc'           :
8                 return aubio_onset_hfc
9        elif nvalue == 'phase'         :
10                 return aubio_onset_phase
11        elif nvalue == 'specdiff'      :
12                 return aubio_onset_specdiff
13        elif nvalue == 'energy'        :
14                 return aubio_onset_energy
15        elif nvalue == 'kl'            :
16                 return aubio_onset_kl
17        elif nvalue == 'mkl'           :
18                 return aubio_onset_mkl
19        elif nvalue == 'dual'          :
20                 return 'dual'
21        else:
22                 import sys
23                 print "unknown onset detection function selected"
24                 sys.exit(1)
25
[0029638]26def get_pitch_mode(nvalue):
27        """ utility function to convert a string to aubio_pitchdetection_type """
28        if   nvalue == 'mcomb'  :
29                 return aubio_pitch_mcomb
30        elif nvalue == 'yin'    :
31                 return aubio_pitch_yin
32        elif nvalue == 'fcomb'  :
33                 return aubio_pitch_fcomb
34        elif nvalue == 'schmitt':
35                 return aubio_pitch_schmitt
36        else:
37                 import sys
38                 print "error: unknown pitch detection function selected"
39                 sys.exit(1)
40
[7473074]41def check_onset_mode(option, opt, value, parser):
42        """ wrapper function to convert a list of modes to
43                aubio_onsetdetection_type """
[5e491b3b]44        nvalues = parser.rargs[0].split(',')
45        val =  []
46        for nvalue in nvalues:
[7473074]47                val.append(get_onset_mode(nvalue))
[5e491b3b]48                setattr(parser.values, option.dest, val)
49
50def check_pitch_mode(option, opt, value, parser):
51        """ utility function to convert a string to aubio_pitchdetection_type"""
52        nvalues = parser.rargs[0].split(',')
53        val = []
54        for nvalue in nvalues:
[0029638]55                val.append(get_pitch_mode(nvalue))
[5e491b3b]56                setattr(parser.values, option.dest, val)
57
58def check_pitchm_mode(option, opt, value, parser):
59        """ utility function to convert a string to aubio_pitchdetection_mode """
60        nvalue = parser.rargs[0]
61        if   nvalue == 'freq'  :
62                 setattr(parser.values, option.dest, aubio_pitchm_freq)
63        elif nvalue == 'midi'  :
64                 setattr(parser.values, option.dest, aubio_pitchm_midi)
65        elif nvalue == 'cent'  :
66                 setattr(parser.values, option.dest, aubio_pitchm_cent)
67        elif nvalue == 'bin'   :
68                 setattr(parser.values, option.dest, aubio_pitchm_bin)
69        else:
70                 import sys
71                 print "error: unknown pitch detection output selected"
72                 sys.exit(1)
73
74
[d9101a5]75#def getonsets(filein,threshold=0.2,silence=-70.,bufsize=1024,hopsize=512,
76#                mode='dual',localmin=False,storefunc=False,derivate=False):
77#        frameread = 0
78#        filei     = sndfile(filein)
79#        channels  = filei.channels()
80#        myvec     = fvec(hopsize,channels)
81#        readsize  = filei.read(hopsize,myvec)
82#        opick     = onsetpick(bufsize,hopsize,channels,myvec,threshold,
83#                         mode=mode,derivate=derivate)
84#        mylist    = list()
85#        if localmin:
86#                ovalist   = [0., 0., 0., 0., 0.]
87#        ofunclist = []
88#        while(readsize):
89#                readsize = filei.read(hopsize,myvec)
90#                isonset,val = opick.do(myvec)
91#                if (aubio_silence_detection(myvec(),silence)):
92#                        isonset=0
93#                if localmin:
94#                        if val > 0: ovalist.append(val)
95#                        else: ovalist.append(0)
96#                        ovalist.pop(0)
97#                if storefunc:
98#                        ofunclist.append(val)
99#                if (isonset == 1):
100#                        if localmin:
101#                                i=len(ovalist)-1
102#                                # find local minima before peak
103#                                while ovalist[i-1] < ovalist[i] and i > 0:
104#                                        i -= 1
105#                                now = (frameread+1-i)
106#                        else:
107#                                now = frameread
108#                        if now > 0 :
109#                                mylist.append(now)
110#                        else:
111#                                now = 0
112#                                mylist.append(now)
113#                frameread += 1
114#        return mylist, ofunclist
115#
116#def cutfile(filein,slicetimes,zerothres=0.008,bufsize=1024,hopsize=512):
117#    frameread = 0
118#    readsize  = hopsize
119#    filei     = sndfile(filein)
120#    framestep = hopsize/(filei.samplerate()+0.)
121#    channels  = filei.channels()
122#    newname   = "%s%s%09.5f%s%s" % (filein.split(".")[0].split("/")[-1],".",
123#                frameread*framestep,".",filein.split(".")[-1])
124#    fileo     = sndfile(newname,model=filei)
125#    myvec     = fvec(hopsize,channels)
126#    mycopy    = fvec(hopsize,channels)
127#    while(readsize==hopsize):
128#        readsize = filei.read(hopsize,myvec)
129#        # write to current file
130#        if len(slicetimes) and frameread >= slicetimes[0]:
131#            slicetimes.pop(0)
132#            # write up to 1st zero crossing
133#            zerocross = 0
134#            while ( abs( myvec.get(zerocross,0) ) > zerothres ):
135#                zerocross += 1
136#            writesize = fileo.write(zerocross,myvec)
137#            fromcross = 0
138#            while (zerocross < readsize):
139#                for i in range(channels):
140#                    mycopy.set(myvec.get(zerocross,i),fromcross,i)
141#                    fromcross += 1
142#                    zerocross += 1
143#            del fileo
144#            fileo = sndfile("%s%s%09.5f%s%s" %
145#                (filein.split(".")[0].split("/")[-1],".",
146#                frameread*framestep,".",filein.split(".")[-1]),model=filei)
147#            writesize = fileo.write(fromcross,mycopy)
148#        else:
149#            writesize = fileo.write(readsize,myvec)
150#        frameread += 1
151#    del fileo
152#
153#
154#def getsilences(filein,hopsize=512,silence=-70):
155#    frameread = 0
156#    filei     = sndfile(filein)
157#    srate     = filei.samplerate()
158#    channels  = filei.channels()
159#    myvec     = fvec(hopsize,channels)
160#    readsize  = filei.read(hopsize,myvec)
161#    mylist    = []
162#    wassilence = 0
163#    while(readsize==hopsize):
164#        readsize = filei.read(hopsize,myvec)
165#        if (aubio_silence_detection(myvec(),silence)==1):
166#            if wassilence == 0:
167#                mylist.append(frameread)
168#                wassilence == 1
169#        else: wassilence = 0
170#        frameread += 1
171#    return mylist
172#
173#
174#def getpitch(filein,mode=aubio_pitch_mcomb,bufsize=1024,hopsize=512,omode=aubio_pitchm_freq,
175#        samplerate=44100.,silence=-70):
176#    frameread = 0
177#    filei     = sndfile(filein)
178#    srate     = filei.samplerate()
179#    channels  = filei.channels()
180#    myvec     = fvec(hopsize,channels)
181#    readsize  = filei.read(hopsize,myvec)
182#    pitchdet  = pitchdetection(mode=mode,bufsize=bufsize,hopsize=hopsize,
183#                         channels=channels,samplerate=srate,omode=omode)
184#    mylist    = []
185#    while(readsize==hopsize):
186#        readsize = filei.read(hopsize,myvec)
187#        freq = pitchdet(myvec)
188#        #print "%.3f     %.2f" % (now,freq)
189#        if (aubio_silence_detection(myvec(),silence)!=1):
190#                mylist.append(freq)
191#        else:
192#                mylist.append(-1.)
193#        frameread += 1
194#    return mylist
[5e491b3b]195
[0029638]196
[c32976a5]197class taskparams(object):
[0029638]198        """ default parameters for task classes """
199        def __init__(self,input=None,output=None):
200                self.silence = -70
201                self.derivate = False
202                self.localmin = False
[84e80a1]203                self.delay = 4.
[7c9ad74]204                self.storefunc = False
[0029638]205                self.bufsize = 512
206                self.hopsize = 256
207                self.samplerate = 44100
208                self.tol = 0.05
[37f0352]209                self.mintol = 0.0
[0029638]210                self.step = float(self.hopsize)/float(self.samplerate)
211                self.threshold = 0.1
[7c9ad74]212                self.onsetmode = 'dual'
213                self.pitchmode = 'yin'
[300adc3]214                self.pitchsmooth = 20
215                self.pitchmin=100.
216                self.pitchmax=1500.
[84e80a1]217                self.dcthreshold = -1.
[0029638]218                self.omode = aubio_pitchm_freq
[84e80a1]219                self.verbose   = False
[0029638]220
221class task(taskparams):
[7c9ad74]222        """ default template class to apply tasks on a stream """
[0029638]223        def __init__(self,input,output=None,params=None):
[7c9ad74]224                """ open the input file and initialize default argument
225                parameters should be set *before* calling this method.
226                """
[d9101a5]227                import time
228                self.tic = time.time()
[0029638]229                if params == None: self.params = taskparams()
230                else: self.params = params
[7c9ad74]231                self.frameread = 0
232                self.readsize  = self.params.hopsize
[0029638]233                self.input     = input
234                self.filei     = sndfile(self.input)
235                self.srate     = self.filei.samplerate()
236                self.channels  = self.filei.channels()
[84e80a1]237                self.params.step = float(self.params.hopsize)/float(self.srate)
[7c9ad74]238                self.myvec     = fvec(self.params.hopsize,self.channels)
[0029638]239                self.output    = output
[d9101a5]240
[7c9ad74]241        def __call__(self):
242                self.readsize = self.filei.read(self.params.hopsize,self.myvec)
243                self.frameread += 1
244               
[0029638]245        def compute_all(self):
246                """ Compute data """
247                mylist    = []
248                while(self.readsize==self.params.hopsize):
[7c9ad74]249                        tmp = self()
[84e80a1]250                        if tmp: 
251                                mylist.append(tmp)
252                                if self.params.verbose:
253                                        self.fprint(tmp)
[0029638]254                return mylist
[84e80a1]255       
256        def fprint(self,foo):
257                print foo
[0029638]258
259        def eval(self,results):
260                """ Eval data """
261                pass
262
263        def plot(self):
264                """ Plot data """
265                pass
266
[d9101a5]267        def time(self):
268                import time
269                print "CPU time is now %f seconds," % time.clock(),
270                print "task execution took %f seconds" % (time.time() - self.tic)
271
[7c9ad74]272class tasksilence(task):
273        wassilence = 1
274        issilence  = 1
275        def __call__(self):
276                task.__call__(self)
277                if (aubio_silence_detection(self.myvec(),self.params.silence)==1):
278                        if self.wassilence == 1: self.issilence = 1
279                        else: self.issilence = 2
280                        self.wassilence = 1
281                else: 
282                        if self.wassilence <= 0: self.issilence = 0
283                        else: self.issilence = -1 
284                        self.wassilence = 0
285                if self.issilence == -1:
[84e80a1]286                        return max(self.frameread-self.params.delay,0.), -1
[7c9ad74]287                elif self.issilence == 2:
[84e80a1]288                        return max(self.frameread+self.params.delay,0.), 2 
289
290        def fprint(self,foo):
291                print self.params.step*foo[0],
292                if foo[1] == 2: print "OFF"
293                else: print "ON"
[7c9ad74]294
[0029638]295class taskpitch(task):
296        def __init__(self,input,params=None):
297                task.__init__(self,input,params=params)
[300adc3]298                self.shortlist = [0. for i in range(self.params.pitchsmooth)]
[7c9ad74]299                self.pitchdet  = pitchdetection(mode=get_pitch_mode(self.params.pitchmode),
[0029638]300                        bufsize=self.params.bufsize,
301                        hopsize=self.params.hopsize,
302                        channels=self.channels,
303                        samplerate=self.srate,
304                        omode=self.params.omode)
305
306        def __call__(self):
[300adc3]307                from median import short_find
[7c9ad74]308                task.__call__(self)
[300adc3]309                if (aubio_silence_detection(self.myvec(),self.params.silence)==1):
310                        freq = -1.
311                else:
312                        freq = self.pitchdet(self.myvec)
313                minpitch = self.params.pitchmin
314                maxpitch = self.params.pitchmax
315                if maxpitch and freq > maxpitch : 
316                        freq = -1.
317                elif minpitch and freq < minpitch :
318                        freq = -1.
319                if self.params.pitchsmooth:
320                        self.shortlist.append(freq)
321                        self.shortlist.pop(0)
322                        smoothfreq = short_find(self.shortlist,
323                                len(self.shortlist)/2)
324                        return smoothfreq
325                else:
[0029638]326                        return freq
[300adc3]327
328        def compute_all(self):
329                """ Compute data """
330                mylist    = []
331                while(self.readsize==self.params.hopsize):
332                        freq = self()
333                        mylist.append(freq)
334                        if self.params.verbose:
335                                self.fprint("%s\t%s" % (self.frameread*self.params.step,freq))
336                return mylist
[0029638]337
338        def gettruth(self):
[7c9ad74]339                """ big hack to extract midi note from /path/to/file.<midinote>.wav """
[c32976a5]340                floatpit = self.input.split('.')[-2]
341                try:
[37f0352]342                        return aubio_miditofreq(float(floatpit))
[c32976a5]343                except ValueError:
344                        print "ERR: no truth file found"
345                        return 0
[0029638]346
347        def eval(self,results):
[37f0352]348                def mmean(l):
349                        return sum(l)/max(float(len(l)),1)
350
[300adc3]351                from median import percental
[0029638]352                self.truth = self.gettruth()
353                res = []
354                for i in results:
[300adc3]355                        if i <= 0: pass
356                        else: res.append(self.truth-i)
[37f0352]357                if not res: 
358                        avg = self.truth; med = self.truth
[7c9ad74]359                else:
[37f0352]360                        avg = mmean(res) 
[300adc3]361                        med = percental(res,len(res)/2) 
[37f0352]362                return self.truth, self.truth-med, self.truth-avg
[0029638]363
[300adc3]364        def plot(self,pitch,wplot,oplots,outplot=None):
365                from aubio.txtfile import read_datafile
366                import os.path
367                import numarray
368                import Gnuplot
369
370                downtime = self.params.step*numarray.arange(len(pitch))
371                oplots.append(Gnuplot.Data(downtime,pitch,with='lines',
372                        title=self.params.pitchmode))
373
374                # check if ground truth exists
375                datafile = self.input.replace('.wav','.txt')
376                if datafile == self.input: datafile = ""
377                if not os.path.isfile(datafile):
378                        self.title = "" #"truth file not found"
379                        t = Gnuplot.Data(0,0,with='impulses') 
380                else:
381                        self.title = "" #"truth file plotting not implemented yet"
382                        values = read_datafile(datafile)
383                        if (len(datafile[0])) > 1:
384                                time, pitch = [], []
385                                for i in range(len(values)):
386                                        time.append(values[i][0])
387                                        pitch.append(values[i][1])
388                                oplots.append(Gnuplot.Data(time,pitch,with='lines',
389                                        title='ground truth'))
390                       
391        def plotplot(self,wplot,oplots,outplot=None):
392                from aubio.gnuplot import gnuplot_init, audio_to_array, make_audio_plot
393                import re
394                # audio data
395                time,data = audio_to_array(self.input)
396                f = make_audio_plot(time,data)
397
398                g = gnuplot_init(outplot)
399                g('set title \'%s %s\'' % (re.sub('.*/','',self.input),self.title))
400                g('set multiplot')
401                # hack to align left axis
402                g('set lmargin 15')
403                # plot waveform and onsets
404                g('set size 1,0.3')
405                g('set origin 0,0.7')
406                g('set xrange [0:%f]' % max(time)) 
407                g('set yrange [-1:1]') 
408                g.ylabel('amplitude')
409                g.plot(f)
410                g('unset title')
411                # plot onset detection function
412
413
414                g('set size 1,0.7')
415                g('set origin 0,0')
416                g('set xrange [0:%f]' % max(time))
417                g('set yrange [40:%f]' % self.params.pitchmax) 
418                g('set key right top')
419                g('set noclip one') 
420                g('set format x ""')
421                #g.xlabel('time (s)')
422                g.ylabel('frequency (Hz)')
423                multiplot = 1
424                if multiplot:
425                        for i in range(len(oplots)):
426                                # plot onset detection functions
427                                g('set size 1,%f' % (0.7/(len(oplots))))
428                                g('set origin 0,%f' % (float(i)*0.7/(len(oplots))))
429                                g('set xrange [0:%f]' % max(time))
430                                g.plot(oplots[i])
431                else:
432                        g.plot(*oplots)
433                g('unset multiplot')
[0029638]434
435
[7c9ad74]436class taskonset(task):
437        def __init__(self,input,output=None,params=None):
438                """ open the input file and initialize arguments
439                parameters should be set *before* calling this method.
440                """
441                task.__init__(self,input,params=params)
442                self.opick = onsetpick(self.params.bufsize,
443                        self.params.hopsize,
444                        self.channels,
445                        self.myvec,
446                        self.params.threshold,
447                        mode=get_onset_mode(self.params.onsetmode),
[84e80a1]448                        dcthreshold=self.params.dcthreshold,
[7c9ad74]449                        derivate=self.params.derivate)
450                self.olist = [] 
451                self.ofunc = []
452                self.maxofunc = 0
[37f0352]453                self.last = 0
[7c9ad74]454                if self.params.localmin:
[c32976a5]455                        self.ovalist   = [0., 0., 0., 0., 0.]
[7c9ad74]456
457        def __call__(self):
458                task.__call__(self)
459                isonset,val = self.opick.do(self.myvec)
460                if (aubio_silence_detection(self.myvec(),self.params.silence)):
461                        isonset=0
462                if self.params.storefunc:
463                        self.ofunc.append(val)
464                if self.params.localmin:
[c32976a5]465                        if val > 0: self.ovalist.append(val)
466                        else: self.ovalist.append(0)
467                        self.ovalist.pop(0)
[7c9ad74]468                if (isonset == 1):
469                        if self.params.localmin:
470                                # find local minima before peak
[84e80a1]471                                i=len(self.ovalist)-1
[7c9ad74]472                                while self.ovalist[i-1] < self.ovalist[i] and i > 0:
473                                        i -= 1
474                                now = (self.frameread+1-i)
475                        else:
476                                now = self.frameread
[84e80a1]477                        # take back delay
[8d29cfe]478                        if self.params.delay != 0.: now -= self.params.delay
[7c9ad74]479                        if now < 0 :
480                                now = 0
[37f0352]481                        if self.params.mintol:
[84e80a1]482                                # prune doubled
[37f0352]483                                if (now - self.last) > self.params.mintol:
484                                        self.last = now
485                                        return now, val
486                        else:
487                                return now, val
[7c9ad74]488
[c32976a5]489
[84e80a1]490        def fprint(self,foo):
491                print self.params.step*foo[0]
492
[4045ba4]493        def eval(self,inputdata,ftru,mode='roc',vmode=''):
[7c9ad74]494                from txtfile import read_datafile
[4045ba4]495                from onsetcompare import onset_roc, onset_diffs, onset_rocloc
[c32976a5]496                ltru = read_datafile(ftru,depth=0)
[4045ba4]497                lres = []
498                for i in range(len(inputdata)): lres.append(inputdata[i][0]*self.params.step)
[7c9ad74]499                if vmode=='verbose':
[4045ba4]500                        print "Running with mode %s" % self.params.onsetmode, 
[7c9ad74]501                        print " and threshold %f" % self.params.threshold, 
[4045ba4]502                        print " on file", self.input
[7c9ad74]503                #print ltru; print lres
[4045ba4]504                if mode == 'local':
[7c9ad74]505                        l = onset_diffs(ltru,lres,self.params.tol)
506                        mean = 0
507                        for i in l: mean += i
[4045ba4]508                        if len(l): mean = "%.3f" % (mean/len(l))
509                        else: mean = "?0"
510                        return l, mean
511                elif mode == 'roc':
[7c9ad74]512                        self.orig, self.missed, self.merged, \
513                                self.expc, self.bad, self.doubled = \
514                                onset_roc(ltru,lres,self.params.tol)
[4045ba4]515                elif mode == 'rocloc':
[dbc0351]516                        self.v = {}
517                        self.v['orig'], self.v['missed'], self.v['Tm'], \
518                                self.v['expc'], self.v['bad'], self.v['Td'], \
519                                self.v['l'], self.v['labs'] = \
[4045ba4]520                                onset_rocloc(ltru,lres,self.params.tol)
[7c9ad74]521
[84e80a1]522        def plot(self,onsets,ofunc,wplot,oplots,nplot=False):
[7c9ad74]523                import Gnuplot, Gnuplot.funcutils
524                import aubio.txtfile
525                import os.path
526                import numarray
527                from aubio.onsetcompare import onset_roc
528
[84e80a1]529                x1,y1,y1p = [],[],[]
530                oplot = []
[300adc3]531                if self.params.onsetmode in ('mkl','kl'): ofunc[0:10] = [0] * 10
[84e80a1]532
[7c9ad74]533                self.lenofunc = len(ofunc) 
[84e80a1]534                self.maxofunc = max(ofunc)
[7c9ad74]535                # onset detection function
[84e80a1]536                downtime = numarray.arange(len(ofunc))*self.params.step
537                oplot.append(Gnuplot.Data(downtime,ofunc,with='lines',title=self.params.onsetmode))
[7c9ad74]538
539                # detected onsets
[84e80a1]540                if not nplot:
541                        for i in onsets:
542                                x1.append(i[0]*self.params.step)
543                                y1.append(self.maxofunc)
544                                y1p.append(-self.maxofunc)
545                        #x1 = numarray.array(onsets)*self.params.step
546                        #y1 = self.maxofunc*numarray.ones(len(onsets))
547                        if x1:
548                                oplot.append(Gnuplot.Data(x1,y1,with='impulses'))
549                                wplot.append(Gnuplot.Data(x1,y1p,with='impulses'))
550
551                oplots.append(oplot)
[7c9ad74]552
553                # check if datafile exists truth
554                datafile = self.input.replace('.wav','.txt')
555                if datafile == self.input: datafile = ""
556                if not os.path.isfile(datafile):
[84e80a1]557                        self.title = "" #"(no ground truth)"
[7c9ad74]558                        t = Gnuplot.Data(0,0,with='impulses') 
559                else:
560                        t_onsets = aubio.txtfile.read_datafile(datafile)
561                        x2 = numarray.array(t_onsets).resize(len(t_onsets))
[84e80a1]562                        y2 = self.maxofunc*numarray.ones(len(t_onsets))
563                        wplot.append(Gnuplot.Data(x2,y2,with='impulses'))
[7c9ad74]564                       
565                        tol = 0.050 
[0029638]566
[7c9ad74]567                        orig, missed, merged, expc, bad, doubled = \
568                                onset_roc(x2,x1,tol)
569                        self.title = "GD %2.3f%% FP %2.3f%%" % \
570                                ((100*float(orig-missed-merged)/(orig)),
571                                 (100*float(bad+doubled)/(orig)))
572
573
[300adc3]574        def plotplot(self,wplot,oplots,outplot=None):
[7c9ad74]575                from aubio.gnuplot import gnuplot_init, audio_to_array, make_audio_plot
576                import re
577                # audio data
578                time,data = audio_to_array(self.input)
[84e80a1]579                wplot = [make_audio_plot(time,data)] + wplot
[7c9ad74]580                # prepare the plot
581                g = gnuplot_init(outplot)
582
583                g('set multiplot')
584
585                # hack to align left axis
[84e80a1]586                g('set lmargin 6')
587                g('set tmargin 0')
588                g('set format x ""')
589                g('set format y ""')
590                g('set noytics')
591
[300adc3]592                for i in range(len(oplots)):
[84e80a1]593                        # plot onset detection functions
[300adc3]594                        g('set size 1,%f' % (0.7/(len(oplots))))
595                        g('set origin 0,%f' % (float(i)*0.7/(len(oplots))))
[84e80a1]596                        g('set xrange [0:%f]' % (self.lenofunc*self.params.step))
[300adc3]597                        g.plot(*oplots[i])
[84e80a1]598
[300adc3]599                g('set tmargin 3.0')
600                g('set xlabel "time (s)" 1,0')
601                g('set format x "%1.1f"')
[84e80a1]602
603                g('set title \'%s %s\'' % (re.sub('.*/','',self.input),self.title))
[7c9ad74]604
605                # plot waveform and onsets
606                g('set size 1,0.3')
607                g('set origin 0,0.7')
608                g('set xrange [0:%f]' % max(time)) 
609                g('set yrange [-1:1]') 
610                g.ylabel('amplitude')
[84e80a1]611                g.plot(*wplot)
[7c9ad74]612               
613                g('unset multiplot')
614
615class taskcut(task):
616        def __init__(self,input,slicetimes,params=None,output=None):
617                """ open the input file and initialize arguments
618                parameters should be set *before* calling this method.
619                """
620                task.__init__(self,input,output=None,params=params)
621                self.newname   = "%s%s%09.5f%s%s" % (self.input.split(".")[0].split("/")[-1],".",
[84e80a1]622                                        self.frameread*self.params.step,".",self.input.split(".")[-1])
623                self.fileo      = sndfile(self.newname,model=self.filei)
624                self.myvec      = fvec(self.params.hopsize,self.channels)
[7c9ad74]625                self.mycopy     = fvec(self.params.hopsize,self.channels)
626                self.slicetimes = slicetimes
627
628        def __call__(self):
629                task.__call__(self)
630                # write to current file
[84e80a1]631                if len(self.slicetimes) and self.frameread >= self.slicetimes[0][0]:
[7c9ad74]632                        self.slicetimes.pop(0)
633                        # write up to 1st zero crossing
634                        zerocross = 0
635                        while ( abs( self.myvec.get(zerocross,0) ) > self.params.zerothres ):
636                                zerocross += 1
637                        writesize = self.fileo.write(zerocross,self.myvec)
638                        fromcross = 0
639                        while (zerocross < self.readsize):
640                                for i in range(self.channels):
641                                        self.mycopy.set(self.myvec.get(zerocross,i),fromcross,i)
642                                        fromcross += 1
643                                        zerocross += 1
644                        del self.fileo
645                        self.fileo = sndfile("%s%s%09.5f%s%s" % 
646                                (self.input.split(".")[0].split("/")[-1],".",
[84e80a1]647                                self.frameread*self.params.step,".",self.input.split(".")[-1]),model=self.filei)
[7c9ad74]648                        writesize = self.fileo.write(fromcross,self.mycopy)
649                else:
650                        writesize = self.fileo.write(self.readsize,self.myvec)
[c32976a5]651
652class taskbeat(taskonset):
653        def __init__(self,input,params=None,output=None):
654                """ open the input file and initialize arguments
655                parameters should be set *before* calling this method.
656                """
657                taskonset.__init__(self,input,output=None,params=params)
658                self.btwinlen  = 512**2/self.params.hopsize
659                self.btstep    = self.btwinlen/4
660                self.btoutput  = fvec(self.btstep,self.channels)
661                self.dfframe   = fvec(self.btwinlen,self.channels)
662                self.bt        = beattracking(self.btwinlen,self.channels)
663                self.pos2      = 0
664
665        def __call__(self):
666                taskonset.__call__(self)
667                # write to current file
668                if self.pos2 == self.btstep - 1 : 
669                        self.bt.do(self.dfframe,self.btoutput)
670                        for i in range (self.btwinlen - self.btstep):
671                                self.dfframe.set(self.dfframe.get(i+self.btstep,0),i,0) 
672                        for i in range(self.btwinlen - self.btstep, self.btwinlen): 
673                                self.dfframe.set(0,i,0)
674                        self.pos2 = -1;
675                self.pos2 += 1
676                val = self.opick.pp.getval()
677                self.dfframe.set(val,self.btwinlen - self.btstep + self.pos2,0)
678                i=0
679                for i in range(1,int( self.btoutput.get(0,0) ) ):
680                        if self.pos2 == self.btoutput.get(i,0) and \
681                                aubio_silence_detection(self.myvec(),
682                                        self.params.silence)!=1: 
683                                return self.frameread, 0 
684       
685        def eval(self,results):
686                pass
Note: See TracBrowser for help on using the repository browser.