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