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