]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blame - helpers/music_file.py
Add possibility to reload YML config file
[perso/Immae/Projets/Python/MusicSampler.git] / helpers / music_file.py
CommitLineData
be27763f
IB
1import threading
2import pydub
98ff4305 3import time
60979de4 4from transitions.extensions import HierarchicalMachine as Machine
be27763f 5
29597680
IB
6import os.path
7
ccda4cb9
IB
8import audioop
9
29597680 10from .lock import Lock
a24c34bc 11from . import Config, gain, debug_print, error_print
af27d782 12from .mixer import Mixer
aee1334c 13from .music_effect import GainEffect
1b4b78f5 14
29597680
IB
15file_lock = Lock("file")
16
108f858f 17class MusicFile:
20586193
IB
18 STATES = [
19 'initial',
20 'loading',
21 'failed',
22 {
23 'name': 'loaded',
24 'children': [
25 'playing',
26 'paused',
27 'stopping'
28 ]
29 }
30 ]
31 TRANSITIONS = [
32 {
33 'trigger': 'load',
34 'source': 'initial',
b7ca3fc2
IB
35 'dest': 'loading',
36 'after': 'poll_loaded'
20586193
IB
37 },
38 {
39 'trigger': 'fail',
40 'source': 'loading',
41 'dest': 'failed'
42 },
43 {
44 'trigger': 'success',
45 'source': 'loading',
46 'dest': 'loaded'
47 },
48 {
49 'trigger': 'start_playing',
50 'source': 'loaded',
e55b29bb
IB
51 'dest': 'loaded_playing',
52 # if a child has no transitions, then it is bubbled to the parent,
53 # and we don't want that. Not useful in that machine precisely.
54 'conditions': ['is_loaded']
20586193
IB
55 },
56 {
57 'trigger': 'pause',
58 'source': 'loaded_playing',
59 'dest': 'loaded_paused'
60 },
61 {
62 'trigger': 'unpause',
63 'source': 'loaded_paused',
64 'dest': 'loaded_playing'
65 },
66 {
67 'trigger': 'stop_playing',
68 'source': ['loaded_playing','loaded_paused'],
69 'dest': 'loaded_stopping'
70 },
71 {
72 'trigger': 'stopped',
73 'source': '*',
74 'dest': 'loaded',
b7ca3fc2
IB
75 'before': 'trigger_stopped_events',
76 'conditions': ['is_in_use']
20586193
IB
77 }
78 ]
79
2e404903 80 def __init__(self, filename, mapping, name=None, gain=1):
20586193
IB
81 Machine(model=self, states=self.STATES,
82 transitions=self.TRANSITIONS, initial='initial',
51322669 83 ignore_invalid_triggers=True)
60979de4 84
b7ca3fc2 85 self.loaded_callbacks = []
1b4b78f5 86 self.mapping = mapping
be27763f 87 self.filename = filename
9de92b6d 88 self.name = name or filename
29597680 89 self.audio_segment = None
ccda4cb9 90 self.initial_volume_factor = gain
29597680 91 self.music_lock = Lock("music__" + filename)
be27763f 92
2e404903 93 threading.Thread(name="MSMusicLoad", target=self.load).start()
29597680 94
ab47d2a1
IB
95 def reload_properties(self, name=None, gain=1):
96 self.name = name or self.filename
97 if gain != self.initial_volume_factor:
98 self.initial_volume_factor = gain
99 self.reload_music_file()
100
101 def reload_music_file(self):
102 with file_lock:
103 try:
104 debug_print("Reloading « {} »".format(self.name))
105 initial_db_gain = gain(self.initial_volume_factor * 100)
106 self.audio_segment = pydub.AudioSegment \
107 .from_file(self.filename) \
108 .set_frame_rate(Config.frame_rate) \
109 .set_channels(Config.channels) \
110 .set_sample_width(Config.sample_width) \
111 .apply_gain(initial_db_gain)
112 except Exception as e:
113 error_print("failed to reload « {} »: {}"\
114 .format(self.name, e))
115 self.loading_error = e
116 self.to_failed()
117 else:
118 debug_print("Reloaded « {} »".format(self.name))
119
20586193 120 # Machine related events
29597680
IB
121 def on_enter_loading(self):
122 with file_lock:
123 try:
a24c34bc
IB
124 debug_print("Loading « {} »".format(self.name))
125 self.mixer = self.mapping.mixer or Mixer()
ccda4cb9 126 initial_db_gain = gain(self.initial_volume_factor * 100)
2e404903
IB
127 self.audio_segment = pydub.AudioSegment \
128 .from_file(self.filename) \
129 .set_frame_rate(Config.frame_rate) \
130 .set_channels(Config.channels) \
131 .set_sample_width(Config.sample_width) \
132 .apply_gain(initial_db_gain)
29597680
IB
133 self.sound_duration = self.audio_segment.duration_seconds
134 except Exception as e:
a24c34bc 135 error_print("failed to load « {} »: {}".format(self.name, e))
29597680
IB
136 self.loading_error = e
137 self.fail()
138 else:
139 self.success()
a24c34bc 140 debug_print("Loaded « {} »".format(self.name))
60979de4 141
20586193 142 def on_enter_loaded(self):
62bce32f
IB
143 self.cleanup()
144
145 def cleanup(self):
20586193
IB
146 self.gain_effects = []
147 self.set_gain(0, absolute=True)
148 self.current_audio_segment = None
149 self.volume = 100
150 self.wait_event = threading.Event()
151 self.current_loop = 0
152
153 def on_enter_loaded_playing(self):
154 self.mixer.add_file(self)
be27763f 155
20586193
IB
156 # Machine related states
157 def is_in_use(self):
158 return self.is_loaded(allow_substates=True) and not self.is_loaded()
0e5d59f7 159
20586193
IB
160 def is_in_use_not_stopping(self):
161 return self.is_loaded_playing() or self.is_loaded_paused()
9de92b6d 162
20586193
IB
163 # Machine related triggers
164 def trigger_stopped_events(self):
165 self.mixer.remove_file(self)
166 self.wait_event.set()
62bce32f 167 self.cleanup()
20586193
IB
168
169 # Actions and properties called externally
98ff4305
IB
170 @property
171 def sound_position(self):
20586193 172 if self.is_in_use():
29597680 173 return self.current_frame / self.current_audio_segment.frame_rate
98ff4305
IB
174 else:
175 return 0
176
2e404903 177 def play(self, fade_in=0, volume=100, loop=0, start_at=0):
b37c72a2 178 self.set_gain(gain(volume) + self.mapping.master_gain, absolute=True)
1b4b78f5 179 self.volume = volume
0cb786e3
IB
180 if loop < 0:
181 self.last_loop = float('inf')
182 else:
183 self.last_loop = loop
1b4b78f5 184
29597680 185 with self.music_lock:
ccda4cb9 186 self.current_audio_segment = self.audio_segment
ccc8b4f2 187 self.current_frame = int(start_at * self.audio_segment.frame_rate)
ccc8b4f2 188
29597680
IB
189 self.start_playing()
190
20586193
IB
191 if fade_in > 0:
192 db_gain = gain(self.volume, 0)[0]
193 self.set_gain(-db_gain)
194 self.add_fade_effect(db_gain, fade_in)
29597680 195
20586193
IB
196 def seek(self, value=0, delta=False):
197 if not self.is_in_use_not_stopping():
198 return
199
200 with self.music_lock:
201 self.abandon_all_effects()
202 if delta:
203 frame_count = int(self.audio_segment.frame_count())
204 frame_diff = int(value * self.audio_segment.frame_rate)
205 self.current_frame += frame_diff
206 while self.current_frame < 0:
207 self.current_loop -= 1
208 self.current_frame += frame_count
209 while self.current_frame > frame_count:
210 self.current_loop += 1
211 self.current_frame -= frame_count
212 if self.current_loop < 0:
213 self.current_loop = 0
214 self.current_frame = 0
215 if self.current_loop > self.last_loop:
216 self.current_loop = self.last_loop
217 self.current_frame = frame_count
218 else:
219 self.current_frame = max(
220 0,
221 int(value * self.audio_segment.frame_rate))
222
223 def stop(self, fade_out=0, wait=False, set_wait_id=None):
29597680 224 if self.is_loaded_playing():
20586193
IB
225 ms = int(self.sound_position * 1000)
226 ms_fo = max(1, int(fade_out * 1000))
227
228 new_audio_segment = self.current_audio_segment[: ms+ms_fo] \
229 .fade_out(ms_fo)
230 with self.music_lock:
231 self.current_audio_segment = new_audio_segment
29597680 232 self.stop_playing()
20586193
IB
233 if wait:
234 if set_wait_id is not None:
235 self.mapping.add_wait_id(set_wait_id, self.wait_event)
236 self.wait_end()
237 else:
29597680
IB
238 self.stopped()
239
20586193
IB
240 def abandon_all_effects(self):
241 db_gain = 0
242 for gain_effect in self.gain_effects:
243 db_gain += gain_effect.get_last_gain()
244
245 self.gain_effects = []
246 self.set_gain(db_gain)
247
248 def set_volume(self, value, delta=False, fade=0):
249 [db_gain, self.volume] = gain(
250 value + int(delta) * self.volume,
251 self.volume)
252
253 self.set_gain_with_effect(db_gain, fade=fade)
254
255 def set_gain_with_effect(self, db_gain, fade=0):
256 if not self.is_in_use():
257 return
258
259 if fade > 0:
260 self.add_fade_effect(db_gain, fade)
261 else:
262 self.set_gain(db_gain)
263
264 def wait_end(self):
265 self.wait_event.clear()
266 self.wait_event.wait()
267
b7ca3fc2
IB
268 # Let other subscribe for an event when they are ready
269 def subscribe_loaded(self, callback):
e55b29bb
IB
270 # FIXME: should lock to be sure we have no race, but it makes the
271 # initialization screen not showing until everything is loaded
272 if self.is_loaded(allow_substates=True):
273 callback(True)
274 elif self.is_failed():
275 callback(False)
276 else:
277 self.loaded_callbacks.append(callback)
b7ca3fc2
IB
278
279 def poll_loaded(self):
280 for callback in self.loaded_callbacks:
281 callback(self.is_loaded())
282 self.loaded_callbacks = []
283
20586193
IB
284 # Callbacks
285 def finished_callback(self):
286 self.stopped()
0deb82a5 287
22514f3a
IB
288 def play_callback(self, out_data_length, frame_count):
289 if self.is_loaded_paused():
290 return b'\0' * out_data_length
291
29597680 292 with self.music_lock:
ccc8b4f2
IB
293 [data, nb_frames] = self.get_next_sample(frame_count)
294 if nb_frames < frame_count:
0cb786e3
IB
295 if self.is_loaded_playing() and\
296 self.current_loop < self.last_loop:
1e44fe7e 297 self.current_loop += 1
ccc8b4f2 298 self.current_frame = 0
2e404903
IB
299 [new_data, new_nb_frames] = self.get_next_sample(
300 frame_count - nb_frames)
ccc8b4f2
IB
301 data += new_data
302 nb_frames += new_nb_frames
303 elif nb_frames == 0:
9925ce3b 304 # FIXME: too slow when mixing multiple streams
2e404903
IB
305 threading.Thread(
306 name="MSFinishedCallback",
307 target=self.finished_callback).start()
29597680 308
22514f3a 309 return data.ljust(out_data_length, b'\0')
ccc8b4f2 310
20586193
IB
311 # Helpers
312 def set_gain(self, db_gain, absolute=False):
313 if absolute:
314 self.db_gain = db_gain
315 else:
316 self.db_gain += db_gain
317
ccc8b4f2 318 def get_next_sample(self, frame_count):
20586193 319 fw = self.audio_segment.frame_width
ccc8b4f2
IB
320
321 data = b""
322 nb_frames = 0
ccc8b4f2
IB
323
324 segment = self.current_audio_segment
325 max_val = int(segment.frame_count())
326
327 start_i = max(self.current_frame, 0)
328 end_i = min(self.current_frame + frame_count, max_val)
2e404903 329 data += segment._data[start_i*fw : end_i*fw]
ccc8b4f2
IB
330 nb_frames += end_i - start_i
331 self.current_frame += end_i - start_i
332
aee1334c
IB
333 volume_factor = self.volume_factor(self.effects_next_gain(nb_frames))
334
335 data = audioop.mul(data, Config.sample_width, volume_factor)
ccda4cb9 336
ccc8b4f2 337 return [data, nb_frames]
be27763f 338
20586193
IB
339 def add_fade_effect(self, db_gain, fade_duration):
340 if not self.is_in_use():
52d58baf 341 return
20586193
IB
342
343 self.gain_effects.append(GainEffect(
344 "fade",
345 self.current_audio_segment,
346 self.current_loop,
347 self.sound_position,
348 self.sound_position + fade_duration,
349 gain=db_gain))
52d58baf 350
aee1334c
IB
351 def effects_next_gain(self, frame_count):
352 db_gain = 0
353 for gain_effect in self.gain_effects:
354 [new_gain, last_gain] = gain_effect.get_next_gain(
355 self.current_frame,
1e44fe7e 356 self.current_loop,
aee1334c
IB
357 frame_count)
358 if last_gain:
359 self.set_gain(new_gain)
360 self.gain_effects.remove(gain_effect)
361 else:
362 db_gain += new_gain
363 return db_gain
364
365
20586193 366 def volume_factor(self, additional_gain=0):
aee1334c
IB
367 return 10 ** ( (self.db_gain + additional_gain) / 20)
368