]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blame - helpers/music_file.py
Cleanup actions and subscribe to music events for loading
[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',
51 'dest': 'loaded_playing'
52 },
53 {
54 'trigger': 'pause',
55 'source': 'loaded_playing',
56 'dest': 'loaded_paused'
57 },
58 {
59 'trigger': 'unpause',
60 'source': 'loaded_paused',
61 'dest': 'loaded_playing'
62 },
63 {
64 'trigger': 'stop_playing',
65 'source': ['loaded_playing','loaded_paused'],
66 'dest': 'loaded_stopping'
67 },
68 {
69 'trigger': 'stopped',
70 'source': '*',
71 'dest': 'loaded',
b7ca3fc2
IB
72 'before': 'trigger_stopped_events',
73 'conditions': ['is_in_use']
20586193
IB
74 }
75 ]
76
2e404903 77 def __init__(self, filename, mapping, name=None, gain=1):
20586193
IB
78 Machine(model=self, states=self.STATES,
79 transitions=self.TRANSITIONS, initial='initial',
51322669 80 ignore_invalid_triggers=True)
60979de4 81
b7ca3fc2 82 self.loaded_callbacks = []
1b4b78f5 83 self.mapping = mapping
be27763f 84 self.filename = filename
9de92b6d 85 self.name = name or filename
29597680 86 self.audio_segment = None
ccda4cb9 87 self.initial_volume_factor = gain
29597680 88 self.music_lock = Lock("music__" + filename)
be27763f 89
2e404903 90 threading.Thread(name="MSMusicLoad", target=self.load).start()
29597680 91
20586193 92 # Machine related events
29597680
IB
93 def on_enter_loading(self):
94 with file_lock:
95 try:
a24c34bc
IB
96 debug_print("Loading « {} »".format(self.name))
97 self.mixer = self.mapping.mixer or Mixer()
ccda4cb9 98 initial_db_gain = gain(self.initial_volume_factor * 100)
2e404903
IB
99 self.audio_segment = pydub.AudioSegment \
100 .from_file(self.filename) \
101 .set_frame_rate(Config.frame_rate) \
102 .set_channels(Config.channels) \
103 .set_sample_width(Config.sample_width) \
104 .apply_gain(initial_db_gain)
29597680
IB
105 self.sound_duration = self.audio_segment.duration_seconds
106 except Exception as e:
a24c34bc 107 error_print("failed to load « {} »: {}".format(self.name, e))
29597680
IB
108 self.loading_error = e
109 self.fail()
110 else:
111 self.success()
a24c34bc 112 debug_print("Loaded « {} »".format(self.name))
60979de4 113
20586193
IB
114 def on_enter_loaded(self):
115 self.gain_effects = []
116 self.set_gain(0, absolute=True)
117 self.current_audio_segment = None
118 self.volume = 100
119 self.wait_event = threading.Event()
120 self.current_loop = 0
121
122 def on_enter_loaded_playing(self):
123 self.mixer.add_file(self)
be27763f 124
20586193
IB
125 # Machine related states
126 def is_in_use(self):
127 return self.is_loaded(allow_substates=True) and not self.is_loaded()
0e5d59f7 128
20586193
IB
129 def is_in_use_not_stopping(self):
130 return self.is_loaded_playing() or self.is_loaded_paused()
9de92b6d 131
20586193
IB
132 # Machine related triggers
133 def trigger_stopped_events(self):
134 self.mixer.remove_file(self)
135 self.wait_event.set()
136
137 # Actions and properties called externally
98ff4305
IB
138 @property
139 def sound_position(self):
20586193 140 if self.is_in_use():
29597680 141 return self.current_frame / self.current_audio_segment.frame_rate
98ff4305
IB
142 else:
143 return 0
144
2e404903 145 def play(self, fade_in=0, volume=100, loop=0, start_at=0):
b37c72a2 146 self.set_gain(gain(volume) + self.mapping.master_gain, absolute=True)
1b4b78f5 147 self.volume = volume
0cb786e3
IB
148 if loop < 0:
149 self.last_loop = float('inf')
150 else:
151 self.last_loop = loop
1b4b78f5 152
29597680 153 with self.music_lock:
ccda4cb9 154 self.current_audio_segment = self.audio_segment
ccc8b4f2 155 self.current_frame = int(start_at * self.audio_segment.frame_rate)
ccc8b4f2 156
29597680
IB
157 self.start_playing()
158
20586193
IB
159 if fade_in > 0:
160 db_gain = gain(self.volume, 0)[0]
161 self.set_gain(-db_gain)
162 self.add_fade_effect(db_gain, fade_in)
29597680 163
20586193
IB
164 def seek(self, value=0, delta=False):
165 if not self.is_in_use_not_stopping():
166 return
167
168 with self.music_lock:
169 self.abandon_all_effects()
170 if delta:
171 frame_count = int(self.audio_segment.frame_count())
172 frame_diff = int(value * self.audio_segment.frame_rate)
173 self.current_frame += frame_diff
174 while self.current_frame < 0:
175 self.current_loop -= 1
176 self.current_frame += frame_count
177 while self.current_frame > frame_count:
178 self.current_loop += 1
179 self.current_frame -= frame_count
180 if self.current_loop < 0:
181 self.current_loop = 0
182 self.current_frame = 0
183 if self.current_loop > self.last_loop:
184 self.current_loop = self.last_loop
185 self.current_frame = frame_count
186 else:
187 self.current_frame = max(
188 0,
189 int(value * self.audio_segment.frame_rate))
190
191 def stop(self, fade_out=0, wait=False, set_wait_id=None):
29597680 192 if self.is_loaded_playing():
20586193
IB
193 ms = int(self.sound_position * 1000)
194 ms_fo = max(1, int(fade_out * 1000))
195
196 new_audio_segment = self.current_audio_segment[: ms+ms_fo] \
197 .fade_out(ms_fo)
198 with self.music_lock:
199 self.current_audio_segment = new_audio_segment
29597680 200 self.stop_playing()
20586193
IB
201 if wait:
202 if set_wait_id is not None:
203 self.mapping.add_wait_id(set_wait_id, self.wait_event)
204 self.wait_end()
205 else:
29597680
IB
206 self.stopped()
207
20586193
IB
208 def abandon_all_effects(self):
209 db_gain = 0
210 for gain_effect in self.gain_effects:
211 db_gain += gain_effect.get_last_gain()
212
213 self.gain_effects = []
214 self.set_gain(db_gain)
215
216 def set_volume(self, value, delta=False, fade=0):
217 [db_gain, self.volume] = gain(
218 value + int(delta) * self.volume,
219 self.volume)
220
221 self.set_gain_with_effect(db_gain, fade=fade)
222
223 def set_gain_with_effect(self, db_gain, fade=0):
224 if not self.is_in_use():
225 return
226
227 if fade > 0:
228 self.add_fade_effect(db_gain, fade)
229 else:
230 self.set_gain(db_gain)
231
232 def wait_end(self):
233 self.wait_event.clear()
234 self.wait_event.wait()
235
b7ca3fc2
IB
236 # Let other subscribe for an event when they are ready
237 def subscribe_loaded(self, callback):
238 with file_lock:
239 if self.is_loaded(allow_substates=True):
240 callback(True)
241 elif self.is_failed():
242 callback(False)
243 else:
244 self.loaded_callbacks.append(callback)
245
246 def poll_loaded(self):
247 for callback in self.loaded_callbacks:
248 callback(self.is_loaded())
249 self.loaded_callbacks = []
250
20586193
IB
251 # Callbacks
252 def finished_callback(self):
253 self.stopped()
0deb82a5 254
22514f3a
IB
255 def play_callback(self, out_data_length, frame_count):
256 if self.is_loaded_paused():
257 return b'\0' * out_data_length
258
29597680 259 with self.music_lock:
ccc8b4f2
IB
260 [data, nb_frames] = self.get_next_sample(frame_count)
261 if nb_frames < frame_count:
0cb786e3
IB
262 if self.is_loaded_playing() and\
263 self.current_loop < self.last_loop:
1e44fe7e 264 self.current_loop += 1
ccc8b4f2 265 self.current_frame = 0
2e404903
IB
266 [new_data, new_nb_frames] = self.get_next_sample(
267 frame_count - nb_frames)
ccc8b4f2
IB
268 data += new_data
269 nb_frames += new_nb_frames
270 elif nb_frames == 0:
9925ce3b 271 # FIXME: too slow when mixing multiple streams
2e404903
IB
272 threading.Thread(
273 name="MSFinishedCallback",
274 target=self.finished_callback).start()
29597680 275
22514f3a 276 return data.ljust(out_data_length, b'\0')
ccc8b4f2 277
20586193
IB
278 # Helpers
279 def set_gain(self, db_gain, absolute=False):
280 if absolute:
281 self.db_gain = db_gain
282 else:
283 self.db_gain += db_gain
284
ccc8b4f2 285 def get_next_sample(self, frame_count):
20586193 286 fw = self.audio_segment.frame_width
ccc8b4f2
IB
287
288 data = b""
289 nb_frames = 0
ccc8b4f2
IB
290
291 segment = self.current_audio_segment
292 max_val = int(segment.frame_count())
293
294 start_i = max(self.current_frame, 0)
295 end_i = min(self.current_frame + frame_count, max_val)
2e404903 296 data += segment._data[start_i*fw : end_i*fw]
ccc8b4f2
IB
297 nb_frames += end_i - start_i
298 self.current_frame += end_i - start_i
299
aee1334c
IB
300 volume_factor = self.volume_factor(self.effects_next_gain(nb_frames))
301
302 data = audioop.mul(data, Config.sample_width, volume_factor)
ccda4cb9 303
ccc8b4f2 304 return [data, nb_frames]
be27763f 305
20586193
IB
306 def add_fade_effect(self, db_gain, fade_duration):
307 if not self.is_in_use():
52d58baf 308 return
20586193
IB
309
310 self.gain_effects.append(GainEffect(
311 "fade",
312 self.current_audio_segment,
313 self.current_loop,
314 self.sound_position,
315 self.sound_position + fade_duration,
316 gain=db_gain))
52d58baf 317
aee1334c
IB
318 def effects_next_gain(self, frame_count):
319 db_gain = 0
320 for gain_effect in self.gain_effects:
321 [new_gain, last_gain] = gain_effect.get_next_gain(
322 self.current_frame,
1e44fe7e 323 self.current_loop,
aee1334c
IB
324 frame_count)
325 if last_gain:
326 self.set_gain(new_gain)
327 self.gain_effects.remove(gain_effect)
328 else:
329 db_gain += new_gain
330 return db_gain
331
332
20586193 333 def volume_factor(self, additional_gain=0):
aee1334c
IB
334 return 10 ** ( (self.db_gain + additional_gain) / 20)
335