]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blob - helpers/music_file.py
Cleanup actions and subscribe to music events for loading
[perso/Immae/Projets/Python/MusicSampler.git] / helpers / music_file.py
1 import threading
2 import pydub
3 import time
4 from transitions.extensions import HierarchicalMachine as Machine
5
6 import os.path
7
8 import audioop
9
10 from .lock import Lock
11 from . import Config, gain, debug_print, error_print
12 from .mixer import Mixer
13 from .music_effect import GainEffect
14
15 file_lock = Lock("file")
16
17 class MusicFile:
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',
35 'dest': 'loading',
36 'after': 'poll_loaded'
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',
72 'before': 'trigger_stopped_events',
73 'conditions': ['is_in_use']
74 }
75 ]
76
77 def __init__(self, filename, mapping, name=None, gain=1):
78 Machine(model=self, states=self.STATES,
79 transitions=self.TRANSITIONS, initial='initial',
80 ignore_invalid_triggers=True)
81
82 self.loaded_callbacks = []
83 self.mapping = mapping
84 self.filename = filename
85 self.name = name or filename
86 self.audio_segment = None
87 self.initial_volume_factor = gain
88 self.music_lock = Lock("music__" + filename)
89
90 threading.Thread(name="MSMusicLoad", target=self.load).start()
91
92 # Machine related events
93 def on_enter_loading(self):
94 with file_lock:
95 try:
96 debug_print("Loading « {} »".format(self.name))
97 self.mixer = self.mapping.mixer or Mixer()
98 initial_db_gain = gain(self.initial_volume_factor * 100)
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)
105 self.sound_duration = self.audio_segment.duration_seconds
106 except Exception as e:
107 error_print("failed to load « {} »: {}".format(self.name, e))
108 self.loading_error = e
109 self.fail()
110 else:
111 self.success()
112 debug_print("Loaded « {} »".format(self.name))
113
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)
124
125 # Machine related states
126 def is_in_use(self):
127 return self.is_loaded(allow_substates=True) and not self.is_loaded()
128
129 def is_in_use_not_stopping(self):
130 return self.is_loaded_playing() or self.is_loaded_paused()
131
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
138 @property
139 def sound_position(self):
140 if self.is_in_use():
141 return self.current_frame / self.current_audio_segment.frame_rate
142 else:
143 return 0
144
145 def play(self, fade_in=0, volume=100, loop=0, start_at=0):
146 self.set_gain(gain(volume) + self.mapping.master_gain, absolute=True)
147 self.volume = volume
148 if loop < 0:
149 self.last_loop = float('inf')
150 else:
151 self.last_loop = loop
152
153 with self.music_lock:
154 self.current_audio_segment = self.audio_segment
155 self.current_frame = int(start_at * self.audio_segment.frame_rate)
156
157 self.start_playing()
158
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)
163
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):
192 if self.is_loaded_playing():
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
200 self.stop_playing()
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:
206 self.stopped()
207
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
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
251 # Callbacks
252 def finished_callback(self):
253 self.stopped()
254
255 def play_callback(self, out_data_length, frame_count):
256 if self.is_loaded_paused():
257 return b'\0' * out_data_length
258
259 with self.music_lock:
260 [data, nb_frames] = self.get_next_sample(frame_count)
261 if nb_frames < frame_count:
262 if self.is_loaded_playing() and\
263 self.current_loop < self.last_loop:
264 self.current_loop += 1
265 self.current_frame = 0
266 [new_data, new_nb_frames] = self.get_next_sample(
267 frame_count - nb_frames)
268 data += new_data
269 nb_frames += new_nb_frames
270 elif nb_frames == 0:
271 # FIXME: too slow when mixing multiple streams
272 threading.Thread(
273 name="MSFinishedCallback",
274 target=self.finished_callback).start()
275
276 return data.ljust(out_data_length, b'\0')
277
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
285 def get_next_sample(self, frame_count):
286 fw = self.audio_segment.frame_width
287
288 data = b""
289 nb_frames = 0
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)
296 data += segment._data[start_i*fw : end_i*fw]
297 nb_frames += end_i - start_i
298 self.current_frame += end_i - start_i
299
300 volume_factor = self.volume_factor(self.effects_next_gain(nb_frames))
301
302 data = audioop.mul(data, Config.sample_width, volume_factor)
303
304 return [data, nb_frames]
305
306 def add_fade_effect(self, db_gain, fade_duration):
307 if not self.is_in_use():
308 return
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))
317
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,
323 self.current_loop,
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
333 def volume_factor(self, additional_gain=0):
334 return 10 ** ( (self.db_gain + additional_gain) / 20)
335