-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayer.py
342 lines (263 loc) · 10.9 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
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
import os
import asyncio
import audioop
import traceback
from enum import Enum
from array import array
from collections import deque
from shutil import get_terminal_size
from .lib.event_emitter import EventEmitter
class PatchedBuff:
"""
PatchedBuff monkey patches a readable object, allowing you to vary what the volume is as the song is playing.
"""
def __init__(self, buff, *, draw=False):
self.buff = buff
self.frame_count = 0
self.volume = 1.0
self.draw = draw
self.use_audioop = True
self.frame_skip = 2
self.rmss = deque([2048], maxlen=90)
def __del__(self):
if self.draw:
print(' ' * (get_terminal_size().columns-1), end='\r')
def read(self, frame_size):
self.frame_count += 1
frame = self.buff.read(frame_size)
if self.volume != 1:
frame = self._frame_vol(frame, self.volume, maxv=2)
if self.draw and not self.frame_count % self.frame_skip:
# these should be processed for every frame, but "overhead"
rms = audioop.rms(frame, 2)
self.rmss.append(rms)
max_rms = sorted(self.rmss)[-1]
meter_text = 'avg rms: {:.2f}, max rms: {:.2f} '.format(self._avg(self.rmss), max_rms)
self._pprint_meter(rms / max(1, max_rms), text=meter_text, shift=True)
return frame
def _frame_vol(self, frame, mult, *, maxv=2, use_audioop=True):
if use_audioop:
return audioop.mul(frame, 2, min(mult, maxv))
else:
# ffmpeg returns s16le pcm frames.
frame_array = array('h', frame)
for i in range(len(frame_array)):
frame_array[i] = int(frame_array[i] * min(mult, min(1, maxv)))
return frame_array.tobytes()
def _avg(self, i):
return sum(i) / len(i)
def _pprint_meter(self, perc, *, char='#', text='', shift=True):
tx, ty = get_terminal_size()
if shift:
outstr = text + "{}".format(char * (int((tx - len(text)) * perc) - 1))
else:
outstr = text + "{}".format(char * (int(tx * perc) - 1))[len(text):]
print(outstr.ljust(tx - 1), end='\r')
class MusicPlayerState(Enum):
STOPPED = 0 # When the player isn't playing anything
PLAYING = 1 # The player is actively playing music.
PAUSED = 2 # The player is paused on a song.
WAITING = 3 # The player has finished its song but is still downloading the next one
DEAD = 4 # The player has been killed.
def __str__(self):
return self.name
class MusicPlayer(EventEmitter):
def __init__(self, bot, voice_client, playlist):
super().__init__()
self.bot = bot
self.loop = bot.loop
self.voice_client = voice_client
self.playlist = playlist
self.playlist.on('entry-added', self.on_entry_added)
self._volume = bot.config.default_volume
self._play_lock = asyncio.Lock()
self._current_player = None
self._current_entry = None
self.state = MusicPlayerState.STOPPED
self.loop.create_task(self.websocket_check())
@property
def volume(self):
return self._volume
@volume.setter
def volume(self, value):
self._volume = value
if self._current_player:
self._current_player.buff.volume = value
def on_entry_added(self, playlist, entry):
if self.is_stopped:
self.loop.call_later(2, self.play)
def skip(self):
self._kill_current_player()
def stop(self):
self.state = MusicPlayerState.STOPPED
self._kill_current_player()
self.emit('stop', player=self)
def resume(self):
if self.is_paused and self._current_player:
self._current_player.resume()
self.state = MusicPlayerState.PLAYING
self.emit('resume', player=self, entry=self.current_entry)
return
if self.is_paused and not self._current_player:
self.state = MusicPlayerState.PLAYING
self._kill_current_player()
return
raise ValueError('Cannot resume playback from state %s' % self.state)
def pause(self):
if self.is_playing:
self.state = MusicPlayerState.PAUSED
if self._current_player:
self._current_player.pause()
self.emit('pause', player=self, entry=self.current_entry)
return
elif self.is_paused:
return
raise ValueError('Cannot pause a MusicPlayer in state %s' % self.state)
def kill(self):
self.state = MusicPlayerState.DEAD
self.playlist.clear()
self._events.clear()
self._kill_current_player()
def _playback_finished(self):
entry = self._current_entry
if self._current_player:
self._current_player.after = None
self._kill_current_player()
self._current_entry = None
if not self.is_stopped and not self.is_dead:
self.play(_continue=True)
if not self.bot.config.save_videos and entry:
if any([entry.filename == e.filename for e in self.playlist.entries]):
print("[Config:SaveVideos] Skipping deletion, found song in queue")
else:
# print("[Config:SaveVideos] Deleting file: %s" % os.path.relpath(entry.filename))
asyncio.ensure_future(self._delete_file(entry.filename))
self.emit('finished-playing', player=self, entry=entry)
def _kill_current_player(self):
if self._current_player:
if self.is_paused:
self.resume()
try:
self._current_player.stop()
except OSError:
pass
self._current_player = None
return True
return False
async def _delete_file(self, filename):
for x in range(30):
try:
os.unlink(filename)
break
except PermissionError as e:
if e.winerror == 32: # File is in use
await asyncio.sleep(0.25)
except Exception as e:
traceback.print_exc()
print("Error trying to delete " + filename)
break
else:
print("[Config:SaveVideos] Could not delete file {}, giving up and moving on".format(
os.path.relpath(filename)))
def play(self, _continue=False):
self.loop.create_task(self._play(_continue=_continue))
async def _play(self, _continue=False):
"""
Plays the next entry from the playlist, or resumes playback of the current entry if paused.
"""
if self.is_paused:
return self.resume()
if self.is_dead:
return
with await self._play_lock:
if self.is_stopped or _continue:
try:
entry = await self.playlist.get_next_entry()
except Exception as e:
print("Failed to get entry.")
traceback.print_exc()
# Retry playing the next entry in a sec.
self.loop.call_later(0.1, self.play)
return
# If nothing left to play, transition to the stopped state.
if not entry:
self.stop()
return
# In-case there was a player, kill it. RIP.
self._kill_current_player()
self._current_player = self._monkeypatch_player(self.voice_client.create_ffmpeg_player(
entry.filename,
before_options="-nostdin",
options="-vn -b:a 128k",
# Threadsafe call soon, b/c after will be called from the voice playback thread.
after=lambda: self.loop.call_soon_threadsafe(self._playback_finished)
))
self._current_player.setDaemon(True)
self._current_player.buff.volume = self.volume
# I need to add ytdl hooks
self.state = MusicPlayerState.PLAYING
self._current_entry = entry
self._current_player.start()
self.emit('play', player=self, entry=entry)
def _monkeypatch_player(self, player):
original_buff = player.buff
player.buff = PatchedBuff(original_buff)
return player
def reload_voice(self, voice_client):
self.voice_client = voice_client
if self._current_player:
self._current_player.player = voice_client.play_audio
self._current_player._resumed.clear()
self._current_player._connected.set()
async def websocket_check(self):
if self.bot.config.debug_mode:
print("[Debug] Creating websocket check loop")
while not self.is_dead:
try:
self.voice_client.ws.ensure_open()
assert self.voice_client.ws.open
except:
if self.bot.config.debug_mode:
print("[Debug] Voice websocket is %s, reconnecting" % self.voice_client.ws.state_name)
await self.bot.reconnect_voice_client(self.voice_client.channel.server)
await asyncio.sleep(4)
finally:
await asyncio.sleep(1)
@property
def current_entry(self):
return self._current_entry
@property
def is_playing(self):
return self.state == MusicPlayerState.PLAYING
@property
def is_paused(self):
return self.state == MusicPlayerState.PAUSED
@property
def is_stopped(self):
return self.state == MusicPlayerState.STOPPED
@property
def is_dead(self):
return self.state == MusicPlayerState.DEAD
@property
def progress(self):
return round(self._current_player.buff.frame_count * 0.02)
# TODO: Properly implement this
# Correct calculation should be bytes_read/192k
# 192k AKA sampleRate * (bitDepth / 8) * channelCount
# Change frame_count to bytes_read in the PatchedBuff
# if redistributing ffmpeg is an issue, it can be downloaded from here:
# - http://ffmpeg.zeranoe.com/builds/win32/static/ffmpeg-latest-win32-static.7z
# - http://ffmpeg.zeranoe.com/builds/win64/static/ffmpeg-latest-win64-static.7z
#
# Extracting bin/ffmpeg.exe, bin/ffplay.exe, and bin/ffprobe.exe should be fine
# However, the files are in 7z format so meh
# I don't know if we can even do this for the user, at most we open it in the browser
# I can't imagine the user is so incompetent that they can't pull 3 files out of it...
# ...
# ...right?
# Get duration with ffprobe
# ffprobe.exe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 -sexagesimal filename.mp3
# This is also how I fix the format checking issue for now
# ffprobe -v quiet -print_format json -show_format stream
# Normalization filter
# -af dynaudnorm