-
Notifications
You must be signed in to change notification settings - Fork 56
/
audioqueue.pyx
356 lines (349 loc) · 14 KB
/
audioqueue.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import numpy
import threading
import sys
cimport numpy as np
cdef extern from "numpy/arrayobject.h":
void *PyArray_DATA(np.ndarray arr)
class Queue_Empty(Exception):
pass
class Queue_Full(Exception):
pass
cdef class AudioQueue:
"""
This class is responsible for gathering sound sample together
and if necessary, for reemitting new audio-packet of a specified size
"""
cdef int limitsz
cdef object l
cdef unsigned long long _off # global time offset
cdef unsigned long long _totallen # len of buffer
cdef long long _newframepos # new frame starts at...
cdef int _destframesize
cdef int _destframeinterval
cdef int _destframeoverlap
cdef object _destframequeue
cdef float tps
cdef float samplerate
cdef float speedrate[2]
cdef object mutex
def __init__(self,limitsz=-1,samplerate=44100,tps=1000,destframesize=0, destframeoverlap=0,destframequeue=None):
self.limitsz=limitsz
self.l=[]
self._off=0
self._totallen=0
self._newframepos=0
self._destframesize=destframesize
self._destframeoverlap=destframeoverlap
self._destframeinterval=destframesize-destframeoverlap
#print destframesize,destframeoverlap
assert((self._destframeinterval>0) or destframesize==0)
self._destframequeue=destframequeue
self.tps=tps
self.samplerate=samplerate
self.speedrate[0]=tps/samplerate
self.speedrate[1]=1./samplerate # how much seconds does elapse per sample
self.mutex=threading.Lock()
def __len__(self):
""" return the current amount of audio in the queue"""
return self._totallen
def get_len(self):
""" return the max amount of audio in the queue """
return self.limitsz
def get(self,wait=True):
if (self.mutex.acquire(wait)):
try:
r= self.l.pop(0)
self._totallen-=r[0].shape[0]
self._newframepos-=r[0].shape[0]
self._off+=r[0].shape[0]
if (self._newframepos<0):
self._newframepos=0
if (self._totallen<0):
self._totallen=0
assert(self._newframepos>=0)
assert(self._newframepos<=self._totallen)
self.mutex.release()
return r;
except:
self.mutex.release()
raise Queue_Empty
else:
raise Queue_Empty
def _timeat(self,x,t=0):
i=0
lli=self.l[i][0].shape[0]
while (x>lli):
x-=lli
i+=1
lli=self.l[i][0].shape[0]
#print "erroneous speedrate to correct"
return self.l[i][1+t]+x*self.speedrate[t]
def _check_push_frame(self,writesz):
# we are already mutex protected here
#print "dfsz=", self._destframesize, self._totallen, self._newframepos
if (self._destframesize):
#newframes=((self._totallen-self._newframepos)//(self._destframeinterval))-((self._totallen-(writesz+self._newframepos))//(self._destframeinterval))
#newframes-=(self._destframeoverlap/self._destframeinterval)
#print "# NEWFRAMES, TL, NFP",newframes, self._totallen, self._newframepos
while ((self._totallen-self._newframepos) > self._destframesize):
# we can add frames
#print "# TL, NFP,INT", self._totallen, self._newframepos,self._destframeinterval
#print ((self._totallen+writesz-self._newframepos) , self._destframesize)
#print self._destframequeue.get_len()
#raise Exception,"Will lockx"
#sys.stderr.write( "PUSHING...\n")
#sys.stderr.write(str(self))
#sys.stderr.write(str(self._destframequeue))
# sys.stderr.write(str(self.mutex))
# sys.stderr.write(str(self._destframequeue.mutex))
self._destframequeue.putforce((self.__getslice(self._newframepos,(self._newframepos+self._destframesize)),self._timeat(self._newframepos),self._timeat(self._newframepos,t=1) ))
#print "# TL, NFP", self._totallen, self._newframepos
self._newframepos+=self._destframeinterval
#print "# TL, NFP", self._totallen, self._newframepos
#sys.stderr.write(str((self._newframepos, self._totallen)))
assert(self._newframepos>=0)
assert(self._newframepos<=self._totallen)
def put(self,it,wait=True):
if (self.mutex.acquire(wait)):
if ((self.limitsz!=-1) and (len(self.l)>=self.limitsz)):
self.mutex.release()
raise Queue_Full
self.l.append(it)
self._totallen+=it[0].shape[0]
self._check_push_frame(it[0].shape[0])
self.mutex.release()
else:
raise Queue_Full
def putforce(self,it,wait=True):
#print self._newframepos, self.l, self.limitsz
if (self.mutex.acquire(wait)):
#print (self.limitsz==-1) or ((self.limitsz!=-1) and (len(self.l)<=self.limitsz))
if ((self.limitsz!=-1) and (len(self.l)>=self.limitsz)):
#sys.stderr.write("warning : audio queue overloaded\n")
x=self.l.pop(0)
#print "$", self._totallen, self._newframepos
self._totallen-=x[0].shape[0]
self._newframepos-=x[0].shape[0]
self._off+=x[0].shape[0]
#print "$", self._totallen, self._newframepos
if (self._newframepos<0):
self._newframepos=0
if (self._totallen<0):
self._totallen=0
assert(self._newframepos>=0)
assert(self._newframepos<=self._totallen)
self.l.append(it)
self._totallen+=it[0].shape[0]
self._check_push_frame(it[0].shape[0])
self.mutex.release()
def get_nowait(self):
return self.get(wait=False)
def put_nowait(self,it):
return self.put(it,wait=False)
def putforce_nowait(self,it):
return self.putforce(it,wait=False)
def __getitem__(self,x):
# 0 is the fist element in the non popped array so we start from last buf
assert(x>=0)
self.mutex.acquire()
if (x>=self._totallen):
self.mutex.release()
assert(x<self._totallen)
assert(False)
i=0#i=-1
try:
lli=self.l[i][0].shape[0]
except:
self.mutex.release()
raise IndexError
while (x>lli):
x-=lli
i+=1#i-=1
try:
lli=self.l[i][0].shape[0]
except:
self.mutex.release()
raise IndexError
r=self.l[i][0][x]
self.mutex.release()
return r
def __getslice__(self,x,y):
# 0 is the fist element in the non popped array so we start from last buf
assert(y>=x)
assert(x>=0)
self.mutex.acquire()
if (y>self._totallen):
self.mutex.release()
assert(y<=self._totallen)
assert(False)
if (y==x):
self.mutex.release()
return []
i=0#i=-1
try:
lli=self.l[i][0].shape[0]
except:
self.mutex.release()
raise IndexError
while (x>=lli):
x-=lli
y-=lli
#i-=1
i+=1
try:
lli=self.l[i][0].shape[0]
except:
self.mutex.release()
raise IndexError
j=i
llj=lli
while (y>llj):
y-=llj
#j-=1
j+=1
try:
llj=self.l[j][0].shape[0]
except:
self.mutex.release()
raise IndexError
if (i==j):
try:
r=self.l[i][0][x:y]
except:
self.mutex.release()
raise IndexError
self.mutex.release()
return r
else:
#range (i-1,j,-1)
try:
r=numpy.vstack( [ self.l[i][0][x:,:] ] + [ self.l[k][0] for k in range (i+1,j) ] + [ self.l[j][0][:y,:] ])
except:
self.mutex.release()
raise IndexError
self.mutex.release()
return r
def __getitem(self,x):
# 0 is the fist element in the non popped array so we start from last buf
i=0#i=-1
lli=self.l[i][0].shape[0]
while (x>lli):
x-=lli
i+=1#i-=1
lli=self.l[i][0].shape[0]
r=self.l[i][x]
return r
def __getslice(self,x,y):
# 0 is the fist element in the non popped array so we start from last buf
if (y==x):
return []
i=0#i=-1
lli=self.l[i][0].shape[0]
while (x>=lli):
x-=lli
y-=lli
#i-=1
i+=1
lli=self.l[i][0].shape[0]
j=i
llj=lli
while (y>llj):
y-=llj
#j-=1
j+=1
if (j==len(self.l)):
j=j-1
y=self.l[j][0].shape[0]
llj=self.l[j][0].shape[0]
if (i==j):
r=self.l[i][0][x:y]
return r
else:
#range (i-1,j,-1)
r=numpy.vstack( [ self.l[i][0][x:,:] ] + [ self.l[k][0] for k in range (i+1,j) ] + [ self.l[j][0][:y,:] ])
return r
def get_time_bounds(self,wait=True):
if (self.mutex.acquire(wait)):
ttimefrom=self.l[0][2] ## mintime
ttimeto=self.l[-1][2]+(self.l[-1][0].shape[0]*self.speedrate[1]) ## maxtime
self.mutex.release()
return ttimefrom,ttimeto
def get_time_slice(self,timefrom,timeto,wait=True):
## we assume this timeslice is in our queue
""" get the slice of audio buffers contained in-between the two specified instants,
these instants must be specified in seconds since the audio started
(this function suffers from a little bit from approximations (apparently))
"""
assert(timefrom<=timeto)
if (self.mutex.acquire(wait)):
ttimefrom=self.l[0][2] ## mintime
ttimeto=self.l[-1][2]+(self.l[-1][0].shape[0]*self.speedrate[1]) ## maxtime
if (ttimeto<ttimefrom):
print("warning ttimeto < ttimefrom : insonsistent audio queue think to reset audio queues when seeking")
if (timefrom<ttimefrom):
print("warning time from slice is before audioqueue memory capacity : fixing !")
timefrom=ttimefrom
if (timeto<ttimefrom):
print("warning timeto slice is before audioqueue memory capacity : fixing !")
timeto=ttimefrom
if (timeto>ttimeto):
print("warning timeto slice is after audioqueue memory capacity : fixing !")
timeto=ttimeto
if (timefrom>ttimeto):
print("warning timefrom slice is after audioqueue memory capacity : fixing !")
timefrom=ttimeto
deltafrom=int((timefrom-ttimefrom)*self.samplerate)
deltato=int((timeto-ttimefrom)*self.samplerate)
try:
sl=self.__getslice(deltafrom,deltato)
except:
self.mutex.release()
raise Exception,("error retrieving slice %d:%d"%(deltafrom,deltato))
# print (self._off+deltafrom,self._off+deltato)
self.mutex.release()
return sl
def get_sampletime_bounds(self,wait=True):
if (self.mutex.acquire(wait)):
ttimefrom=self._off ## mintime
ttimeto=self._off+self._totallen ## maxtime
self.mutex.release()
return ttimefrom,ttimeto
def get_sampletime_slice(self,timefrom,timeto,wait=True):
## we assume this timeslice is in our queue
""" get the slice of audio buffers contained in-between the two specified instants,
these instants must be specified in seconds since the audio started """
assert(timefrom<=timeto)
if (self.mutex.acquire(wait)):
ttimefrom=self._off ## mintime
ttimeto=self._off+self._totallen ## maxtime
if (ttimeto<ttimefrom):
print("warning ttimeto < ttimefrom : insonsistent audio queue think to reset audio queues when seeking")
if (timefrom<ttimefrom):
print("warning time from slice is before audioqueue memory capacity : fixing !")
timefrom=ttimefrom
if (timeto<ttimefrom):
print("warning timeto slice is before audioqueue memory capacity : fixing !")
timeto=ttimefrom
if (timeto>ttimeto):
print("warning timeto slice is after audioqueue memory capacity : fixing !")
timeto=ttimeto
if (timefrom>ttimeto):
print("warning timefrom slice is after audioqueue memory capacity : fixing !")
timefrom=ttimeto
deltafrom=(timefrom-ttimefrom)
deltato=(timeto-ttimefrom)
try:
sl=self.__getslice(deltafrom,deltato)
except:
self.mutex.release()
raise Exception,("error retrieving slice %d:%d"%(deltafrom,deltato))
# print (self._off+deltafrom,self._off+deltato)
self.mutex.release()
return sl
def print_buffer_stats(self,prefix=""):
sys.stderr.write( prefix+" limitsz"+ str(self.limitsz)+"\n")
sys.stderr.write( prefix+" offset (mintime)"+str( self._off)+"\n")
sys.stderr.write( prefix+" offset (maxtime)"+str( self._off+ self._totallen)+"\n")
sys.stderr.write( prefix+" length"+str( self._totallen)+"\n")
sys.stderr.write( prefix+" time bounds : "+str( self.get_time_bounds())+"\n")
sys.stderr.write( prefix+" sampletime bounds : "+str( self.get_sampletime_bounds())+"\n")