]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blame - music_sampler/music_file.py
Use pip setup file
[perso/Immae/Projets/Python/MusicSampler.git] / music_sampler / 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
6ebe6247 11from .helpers 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:
dd2887c2
IB
104 if self.filename.startswith("/"):
105 filename = self.filename
106 else:
107 filename = Config.music_path + self.filename
108
ab47d2a1
IB
109 debug_print("Reloading « {} »".format(self.name))
110 initial_db_gain = gain(self.initial_volume_factor * 100)
111 self.audio_segment = pydub.AudioSegment \
dd2887c2 112 .from_file(filename) \
ab47d2a1
IB
113 .set_frame_rate(Config.frame_rate) \
114 .set_channels(Config.channels) \
115 .set_sample_width(Config.sample_width) \
116 .apply_gain(initial_db_gain)
117 except Exception as e:
118 error_print("failed to reload « {} »: {}"\
119 .format(self.name, e))
120 self.loading_error = e
121 self.to_failed()
122 else:
123 debug_print("Reloaded « {} »".format(self.name))
124
20586193 125 # Machine related events
29597680
IB
126 def on_enter_loading(self):
127 with file_lock:
128 try:
dd2887c2
IB
129 if self.filename.startswith("/"):
130 filename = self.filename
131 else:
132 filename = Config.music_path + self.filename
133
a24c34bc
IB
134 debug_print("Loading « {} »".format(self.name))
135 self.mixer = self.mapping.mixer or Mixer()
ccda4cb9 136 initial_db_gain = gain(self.initial_volume_factor * 100)
2e404903 137 self.audio_segment = pydub.AudioSegment \
dd2887c2 138 .from_file(filename) \
2e404903
IB
139 .set_frame_rate(Config.frame_rate) \
140 .set_channels(Config.channels) \
141 .set_sample_width(Config.sample_width) \
142 .apply_gain(initial_db_gain)
29597680
IB
143 self.sound_duration = self.audio_segment.duration_seconds
144 except Exception as e:
a24c34bc 145 error_print("failed to load « {} »: {}".format(self.name, e))
29597680
IB
146 self.loading_error = e
147 self.fail()
148 else:
149 self.success()
a24c34bc 150 debug_print("Loaded « {} »".format(self.name))
60979de4 151
20586193 152 def on_enter_loaded(self):
62bce32f
IB
153 self.cleanup()
154
155 def cleanup(self):
20586193
IB
156 self.gain_effects = []
157 self.set_gain(0, absolute=True)
158 self.current_audio_segment = None
159 self.volume = 100
160 self.wait_event = threading.Event()
161 self.current_loop = 0
162
163 def on_enter_loaded_playing(self):
164 self.mixer.add_file(self)
be27763f 165
20586193
IB
166 # Machine related states
167 def is_in_use(self):
168 return self.is_loaded(allow_substates=True) and not self.is_loaded()
0e5d59f7 169
20586193
IB
170 def is_in_use_not_stopping(self):
171 return self.is_loaded_playing() or self.is_loaded_paused()
9de92b6d 172
20586193
IB
173 # Machine related triggers
174 def trigger_stopped_events(self):
175 self.mixer.remove_file(self)
176 self.wait_event.set()
62bce32f 177 self.cleanup()
20586193
IB
178
179 # Actions and properties called externally
98ff4305
IB
180 @property
181 def sound_position(self):
20586193 182 if self.is_in_use():
29597680 183 return self.current_frame / self.current_audio_segment.frame_rate
98ff4305
IB
184 else:
185 return 0
186
2e404903 187 def play(self, fade_in=0, volume=100, loop=0, start_at=0):
b37c72a2 188 self.set_gain(gain(volume) + self.mapping.master_gain, absolute=True)
1b4b78f5 189 self.volume = volume
0cb786e3
IB
190 if loop < 0:
191 self.last_loop = float('inf')
192 else:
193 self.last_loop = loop
1b4b78f5 194
29597680 195 with self.music_lock:
ccda4cb9 196 self.current_audio_segment = self.audio_segment
ccc8b4f2 197 self.current_frame = int(start_at * self.audio_segment.frame_rate)
ccc8b4f2 198
29597680
IB
199 self.start_playing()
200
20586193
IB
201 if fade_in > 0:
202 db_gain = gain(self.volume, 0)[0]
203 self.set_gain(-db_gain)
204 self.add_fade_effect(db_gain, fade_in)
29597680 205
20586193
IB
206 def seek(self, value=0, delta=False):
207 if not self.is_in_use_not_stopping():
208 return
209
210 with self.music_lock:
211 self.abandon_all_effects()
212 if delta:
213 frame_count = int(self.audio_segment.frame_count())
214 frame_diff = int(value * self.audio_segment.frame_rate)
215 self.current_frame += frame_diff
216 while self.current_frame < 0:
217 self.current_loop -= 1
218 self.current_frame += frame_count
219 while self.current_frame > frame_count:
220 self.current_loop += 1
221 self.current_frame -= frame_count
222 if self.current_loop < 0:
223 self.current_loop = 0
224 self.current_frame = 0
225 if self.current_loop > self.last_loop:
226 self.current_loop = self.last_loop
227 self.current_frame = frame_count
228 else:
229 self.current_frame = max(
230 0,
231 int(value * self.audio_segment.frame_rate))
232
233 def stop(self, fade_out=0, wait=False, set_wait_id=None):
29597680 234 if self.is_loaded_playing():
20586193
IB
235 ms = int(self.sound_position * 1000)
236 ms_fo = max(1, int(fade_out * 1000))
237
238 new_audio_segment = self.current_audio_segment[: ms+ms_fo] \
239 .fade_out(ms_fo)
240 with self.music_lock:
241 self.current_audio_segment = new_audio_segment
29597680 242 self.stop_playing()
20586193
IB
243 if wait:
244 if set_wait_id is not None:
245 self.mapping.add_wait_id(set_wait_id, self.wait_event)
246 self.wait_end()
247 else:
29597680
IB
248 self.stopped()
249
20586193
IB
250 def abandon_all_effects(self):
251 db_gain = 0
252 for gain_effect in self.gain_effects:
253 db_gain += gain_effect.get_last_gain()
254
255 self.gain_effects = []
256 self.set_gain(db_gain)
257
258 def set_volume(self, value, delta=False, fade=0):
259 [db_gain, self.volume] = gain(
260 value + int(delta) * self.volume,
261 self.volume)
262
263 self.set_gain_with_effect(db_gain, fade=fade)
264
265 def set_gain_with_effect(self, db_gain, fade=0):
266 if not self.is_in_use():
267 return
268
269 if fade > 0:
270 self.add_fade_effect(db_gain, fade)
271 else:
272 self.set_gain(db_gain)
273
274 def wait_end(self):
275 self.wait_event.clear()
276 self.wait_event.wait()
277
b7ca3fc2
IB
278 # Let other subscribe for an event when they are ready
279 def subscribe_loaded(self, callback):
e55b29bb
IB
280 # FIXME: should lock to be sure we have no race, but it makes the
281 # initialization screen not showing until everything is loaded
282 if self.is_loaded(allow_substates=True):
283 callback(True)
284 elif self.is_failed():
285 callback(False)
286 else:
287 self.loaded_callbacks.append(callback)
b7ca3fc2
IB
288
289 def poll_loaded(self):
290 for callback in self.loaded_callbacks:
291 callback(self.is_loaded())
292 self.loaded_callbacks = []
293
20586193
IB
294 # Callbacks
295 def finished_callback(self):
296 self.stopped()
0deb82a5 297
22514f3a
IB
298 def play_callback(self, out_data_length, frame_count):
299 if self.is_loaded_paused():
300 return b'\0' * out_data_length
301
29597680 302 with self.music_lock:
ccc8b4f2
IB
303 [data, nb_frames] = self.get_next_sample(frame_count)
304 if nb_frames < frame_count:
0cb786e3
IB
305 if self.is_loaded_playing() and\
306 self.current_loop < self.last_loop:
1e44fe7e 307 self.current_loop += 1
ccc8b4f2 308 self.current_frame = 0
2e404903
IB
309 [new_data, new_nb_frames] = self.get_next_sample(
310 frame_count - nb_frames)
ccc8b4f2
IB
311 data += new_data
312 nb_frames += new_nb_frames
313 elif nb_frames == 0:
9925ce3b 314 # FIXME: too slow when mixing multiple streams
2e404903
IB
315 threading.Thread(
316 name="MSFinishedCallback",
317 target=self.finished_callback).start()
29597680 318
22514f3a 319 return data.ljust(out_data_length, b'\0')
ccc8b4f2 320
20586193
IB
321 # Helpers
322 def set_gain(self, db_gain, absolute=False):
323 if absolute:
324 self.db_gain = db_gain
325 else:
326 self.db_gain += db_gain
327
ccc8b4f2 328 def get_next_sample(self, frame_count):
20586193 329 fw = self.audio_segment.frame_width
ccc8b4f2
IB
330
331 data = b""
332 nb_frames = 0
ccc8b4f2
IB
333
334 segment = self.current_audio_segment
335 max_val = int(segment.frame_count())
336
337 start_i = max(self.current_frame, 0)
338 end_i = min(self.current_frame + frame_count, max_val)
2e404903 339 data += segment._data[start_i*fw : end_i*fw]
ccc8b4f2
IB
340 nb_frames += end_i - start_i
341 self.current_frame += end_i - start_i
342
aee1334c
IB
343 volume_factor = self.volume_factor(self.effects_next_gain(nb_frames))
344
345 data = audioop.mul(data, Config.sample_width, volume_factor)
ccda4cb9 346
ccc8b4f2 347 return [data, nb_frames]
be27763f 348
20586193
IB
349 def add_fade_effect(self, db_gain, fade_duration):
350 if not self.is_in_use():
52d58baf 351 return
20586193
IB
352
353 self.gain_effects.append(GainEffect(
354 "fade",
355 self.current_audio_segment,
356 self.current_loop,
357 self.sound_position,
358 self.sound_position + fade_duration,
359 gain=db_gain))
52d58baf 360
aee1334c
IB
361 def effects_next_gain(self, frame_count):
362 db_gain = 0
363 for gain_effect in self.gain_effects:
364 [new_gain, last_gain] = gain_effect.get_next_gain(
365 self.current_frame,
1e44fe7e 366 self.current_loop,
aee1334c
IB
367 frame_count)
368 if last_gain:
369 self.set_gain(new_gain)
370 self.gain_effects.remove(gain_effect)
371 else:
372 db_gain += new_gain
373 return db_gain
374
375
20586193 376 def volume_factor(self, additional_gain=0):
aee1334c
IB
377 return 10 ** ( (self.db_gain + additional_gain) / 20)
378