-
Notifications
You must be signed in to change notification settings - Fork 0
/
player.py
215 lines (195 loc) · 7.01 KB
/
player.py
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
import collections
import heapq
import logging
import threading
import time
import numpy
import opuslib
import pyaudio
import audio
import stats
import util
class Player:
def __init__(self):
self.channels = {}
def start(self):
self.stream = audio.get_audio().open(
format=pyaudio.paInt16,
channels=1,
rate=24000,
output=True,
frames_per_buffer=120,
stream_callback=self.callback,
)
def stop(self, block=True):
self.stream.stop_stream()
self.stream.close()
def put_payloads(self, payloads, peer_name):
channel = self.channels.get(peer_name)
if not channel:
# in lieu of a lock, use attribute assignment to synchronize
channels = dict(self.channels)
channels[peer_name] = channel = Channel()
self.channels = channels
for (seq, data) in payloads:
channel.enqueue(seq, data)
def callback(self, in_data, frame_count, time_info, status):
now = time.time()
frames = [
channel.get_audio()
for channel in self.channels.values()
if channel.last_packet_time and now - channel.last_packet_time < 5
]
frame = audio.mix(frames)
if isinstance(frame, numpy.ndarray) and frame.dtype != numpy.int16:
frame = frame.astype(numpy.int16)
return (frame, pyaudio.paContinue)
Packet = collections.namedtuple('Packet', ['seq', 'data'])
class Channel:
__slots__ = (
'accept_rate',
'decoded',
'decoder',
'decoder_lock',
'decoder_thread',
'dupe_check',
'heap',
'heap_lock',
'last_missing',
'last_packet_time',
'last_played',
'ready_next_rate',
'ready_rate',
'wake_event',
'wake_lock',
)
def __init__(self):
self.accept_rate = 1.0
self.ready_rate = 1.0
self.ready_next_rate = 0.0
self.decoded = None
self.decoder = opuslib.Decoder(24000, 1)
self.decoder_lock = threading.Lock()
self.dupe_check = util.DupeCheck()
self.heap = []
self.heap_lock = threading.Lock()
self.last_packet_time = None
self.wake_event = threading.Event()
self.wake_lock = threading.Lock()
self.decoder_thread = util.start_daemon(self.run_decoder)
self.last_missing = False
self.last_played = None
def enqueue(self, seq, data):
"""Enqueue a packet with its sequence number, and wake the decoder."""
self.last_packet_time = time.time()
if not self.dupe_check.receive(seq):
return
#stats.METER('recv %', self.dupe_check.receive_rate * 100)
self.accept_rate *= 0.995
if not self.last_played or seq > self.last_played:
with self.heap_lock:
heapq.heappush(self.heap, Packet(seq, data))
self.accept_rate += 0.005
self.wake_event.set()
#stats.METER('accept', self.accept_rate)
def dequeue(self):
packet = None
self.ready_next_rate *= 0.995
try:
stats.METER('buffer', len(self.heap)*5)
if self.last_played:
with self.heap_lock:
while self.heap[0].seq <= self.last_played:
heapq.heappop(self.heap)
if self.heap[0].seq == self.last_played + 1:
packet = heapq.heappop(self.heap)
if self.heap[0].seq == packet.seq + 1:
self.ready_next_rate += 0.005
else:
with self.heap_lock:
packet = heapq.heappop(self.heap)
except IndexError:
pass
stats.METER('readynext', self.ready_next_rate)
return packet
def run_decoder(self):
while True:
self.wake_event.wait()
self.wake_event.clear()
if self.decoded:
continue
packet = self.dequeue()
if not packet:
continue # out of luck! sleep until more data comes
self.decoder_lock.acquire()
if self.last_played and packet.seq <= self.last_played:
# too late; missed the callback window
with self.wake_lock:
self.decoder_lock.release()
self.wake_event.clear()
continue
if self.last_missing:
one = self.decoder.decode(b'', 120)
two = self.decoder.decode(packet.data, 120)
data = audio.crossfade(one, two)
self.last_missing = False
else:
data = self.decoder.decode(packet.data, 120)
self.wake_lock.acquire()
self.decoded = Packet(packet.seq, data)
self.decoder_lock.release()
self.wake_event.clear()
self.wake_lock.release()
def read_decoded(self):
"""Return whatever is in the decoded buffer (possibly None) and wake
the decoder thread to let it know the buffer is empty."""
packet = self.decoded
with self.wake_lock:
self.decoded = None
self.wake_event.set()
return packet
def get_audio(self):
"""Return a valid chunk of usable audio, regardless of whether the
decoder has real packets queued up."""
stats.METER('ready', self.ready_rate)
self.ready_rate *= 0.995
packet = self.read_decoded() # wakes decoder
if self.should_play(packet):
self.ready_rate += 0.005
self.adjust_buffer()
return packet.data
# Prepare to decode a dropped frame, so acquire the lock first.
self.decoder_lock.acquire()
# If decoder was busy, it should already have provided fresh audio.
if self.should_play(self.decoded):
self.decoder_lock.release()
packet = self.read_decoded() # remember to wake decoder
self.ready_rate += 0.005
self.adjust_buffer()
return packet.data
if self.last_played:
data = self.decoder.decode(b'', 120)
self.last_missing = True
self.decoder_lock.release()
stats.COUNT('missing')
self.last_played += 1
self.adjust_buffer()
return data
else:
return audio.SILENCE
def should_play(self, packet):
if not packet or (self.last_played and packet.seq != self.last_played + 1):
return False
self.last_played = packet.seq
return True
def adjust_buffer(self):
if self.ready_rate < 0.9:
self.last_played -= 1
self.ready_next_rate = self.ready_rate
self.ready_rate = 1.0
stats.COUNT("<<=")
elif self.ready_next_rate > 0.95:
self.last_played += 1
self.ready_rate = self.ready_next_rate
self.ready_next_rate = 0.0
stats.COUNT("=>>")