]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blame - helpers/music_file.py
Cleanup Machine use
[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:
2e404903 18 def __init__(self, filename, mapping, name=None, gain=1):
60979de4
IB
19 states = [
20 'initial',
21 'loading',
22 'failed',
2e404903
IB
23 {
24 'name': 'loaded',
108f858f
IB
25 'children': [
26 'stopped',
27 'playing',
28 'paused',
29 'stopping',
30 'stopped'
31 ]
2e404903 32 }
60979de4
IB
33 ]
34 transitions = [
2e404903
IB
35 {
36 'trigger': 'load',
37 'source': 'initial',
38 'dest': 'loading'
39 },
40 {
41 'trigger': 'fail',
42 'source': 'loading',
43 'dest': 'failed'
44 },
45 {
46 'trigger': 'success',
47 'source': 'loading',
48 'dest': 'loaded_stopped'
49 },
50 {
51 'trigger': 'start_playing',
52 'source': 'loaded_stopped',
53 'dest': 'loaded_playing'
54 },
55 {
56 'trigger': 'pause',
57 'source': 'loaded_playing',
58 'dest': 'loaded_paused'
59 },
60 {
61 'trigger': 'unpause',
62 'source': 'loaded_paused',
63 'dest': 'loaded_playing'
64 },
65 {
66 'trigger': 'stop_playing',
67 'source': ['loaded_playing','loaded_paused'],
68 'dest': 'loaded_stopping'
69 },
70 {
71 'trigger': 'stopped',
72 'source': 'loaded_stopping',
73 'dest': 'loaded_stopped',
74 'after': 'trigger_stopped_events'
75 }
60979de4
IB
76 ]
77
108f858f 78 Machine(model=self, states=states,
51322669
IB
79 transitions=transitions, initial='initial',
80 ignore_invalid_triggers=True)
60979de4 81
1b4b78f5
IB
82 self.volume = 100
83 self.mapping = mapping
be27763f 84 self.filename = filename
9de92b6d 85 self.name = name or filename
29597680 86 self.audio_segment = None
ccc8b4f2 87 self.audio_segment_frame_width = 0
ccda4cb9 88 self.initial_volume_factor = gain
29597680 89 self.music_lock = Lock("music__" + filename)
0deb82a5 90 self.wait_event = threading.Event()
ccda4cb9 91 self.db_gain = 0
aee1334c 92 self.gain_effects = []
be27763f 93
2e404903 94 threading.Thread(name="MSMusicLoad", target=self.load).start()
29597680
IB
95
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)
ccc8b4f2 108 self.audio_segment_frame_width = self.audio_segment.frame_width
29597680
IB
109 self.sound_duration = self.audio_segment.duration_seconds
110 except Exception as e:
a24c34bc 111 error_print("failed to load « {} »: {}".format(self.name, e))
29597680
IB
112 self.loading_error = e
113 self.fail()
114 else:
115 self.success()
a24c34bc 116 debug_print("Loaded « {} »".format(self.name))
60979de4
IB
117
118 def check_is_loaded(self):
119 return self.state.startswith('loaded_')
be27763f 120
29597680
IB
121 def is_not_stopped(self):
122 return self.check_is_loaded() and not self.is_loaded_stopped()
0e5d59f7 123
9de92b6d 124 def is_paused(self):
29597680 125 return self.is_loaded_paused()
9de92b6d 126
98ff4305
IB
127 @property
128 def sound_position(self):
29597680
IB
129 if self.is_not_stopped():
130 return self.current_frame / self.current_audio_segment.frame_rate
98ff4305
IB
131 else:
132 return 0
133
2e404903 134 def play(self, fade_in=0, volume=100, loop=0, start_at=0):
9925ce3b
IB
135 # FIXME: create a "reinitialize" method
136 self.gain_effects = []
b37c72a2 137 self.set_gain(gain(volume) + self.mapping.master_gain, absolute=True)
1b4b78f5 138 self.volume = volume
1e44fe7e 139 self.current_loop = 0
0cb786e3
IB
140 if loop < 0:
141 self.last_loop = float('inf')
142 else:
143 self.last_loop = loop
1b4b78f5 144
29597680 145 with self.music_lock:
ccda4cb9 146 self.current_audio_segment = self.audio_segment
ccc8b4f2 147 self.current_frame = int(start_at * self.audio_segment.frame_rate)
1e44fe7e
IB
148 if fade_in > 0:
149 db_gain = gain(self.volume, 0)[0]
150 self.set_gain(-db_gain)
151 self.gain_effects.append(GainEffect(
152 "fade",
153 self.current_audio_segment,
154 self.current_loop,
155 self.sound_position,
156 self.sound_position + fade_in,
157 gain=db_gain))
ccc8b4f2 158
29597680
IB
159 self.start_playing()
160
29597680 161 def on_enter_loaded_playing(self):
af27d782 162 self.mixer.add_file(self)
29597680
IB
163
164 def finished_callback(self):
165 if self.is_loaded_playing():
166 self.stop_playing()
167 if self.is_loaded_stopping():
168 self.stopped()
169
22514f3a 170 def trigger_stopped_events(self):
af27d782 171 self.mixer.remove_file(self)
0deb82a5
IB
172 self.wait_event.set()
173
22514f3a
IB
174 def play_callback(self, out_data_length, frame_count):
175 if self.is_loaded_paused():
176 return b'\0' * out_data_length
177
29597680 178 with self.music_lock:
ccc8b4f2
IB
179 [data, nb_frames] = self.get_next_sample(frame_count)
180 if nb_frames < frame_count:
0cb786e3
IB
181 if self.is_loaded_playing() and\
182 self.current_loop < self.last_loop:
1e44fe7e 183 self.current_loop += 1
ccc8b4f2 184 self.current_frame = 0
2e404903
IB
185 [new_data, new_nb_frames] = self.get_next_sample(
186 frame_count - nb_frames)
ccc8b4f2
IB
187 data += new_data
188 nb_frames += new_nb_frames
189 elif nb_frames == 0:
9925ce3b 190 # FIXME: too slow when mixing multiple streams
2e404903
IB
191 threading.Thread(
192 name="MSFinishedCallback",
193 target=self.finished_callback).start()
29597680 194
22514f3a 195 return data.ljust(out_data_length, b'\0')
ccc8b4f2
IB
196
197 def get_next_sample(self, frame_count):
198 fw = self.audio_segment_frame_width
199
200 data = b""
201 nb_frames = 0
ccc8b4f2
IB
202
203 segment = self.current_audio_segment
204 max_val = int(segment.frame_count())
205
206 start_i = max(self.current_frame, 0)
207 end_i = min(self.current_frame + frame_count, max_val)
2e404903 208 data += segment._data[start_i*fw : end_i*fw]
ccc8b4f2
IB
209 nb_frames += end_i - start_i
210 self.current_frame += end_i - start_i
211
aee1334c
IB
212 volume_factor = self.volume_factor(self.effects_next_gain(nb_frames))
213
214 data = audioop.mul(data, Config.sample_width, volume_factor)
ccda4cb9 215
ccc8b4f2 216 return [data, nb_frames]
be27763f 217
2e404903 218 def seek(self, value=0, delta=False):
52d58baf
IB
219 # We don't want to do that while stopping
220 if not (self.is_loaded_playing() or self.is_loaded_paused()):
221 return
222 with self.music_lock:
aee1334c 223 self.abandon_all_effects()
9925ce3b
IB
224 if delta:
225 frame_count = int(self.audio_segment.frame_count())
226 frame_diff = int(value * self.audio_segment.frame_rate)
227 self.current_frame += frame_diff
228 while self.current_frame < 0:
229 self.current_loop -= 1
230 self.current_frame += frame_count
231 while self.current_frame > frame_count:
232 self.current_loop += 1
233 self.current_frame -= frame_count
234 if self.current_loop < 0:
235 self.current_loop = 0
236 self.current_frame = 0
237 if self.current_loop > self.last_loop:
238 self.current_loop = self.last_loop
239 self.current_frame = frame_count
240 else:
241 self.current_frame = max(
242 0,
243 int(value * self.audio_segment.frame_rate))
52d58baf 244
aee1334c
IB
245 def effects_next_gain(self, frame_count):
246 db_gain = 0
247 for gain_effect in self.gain_effects:
248 [new_gain, last_gain] = gain_effect.get_next_gain(
249 self.current_frame,
1e44fe7e 250 self.current_loop,
aee1334c
IB
251 frame_count)
252 if last_gain:
253 self.set_gain(new_gain)
254 self.gain_effects.remove(gain_effect)
255 else:
256 db_gain += new_gain
257 return db_gain
258
259
260 def abandon_all_effects(self):
261 db_gain = 0
262 for gain_effect in self.gain_effects:
263 db_gain += gain_effect.get_last_gain()
264
265 self.gain_effects = []
266 self.set_gain(db_gain)
267
3aaddc9d 268 def stop(self, fade_out=0, wait=False, set_wait_id=None):
29597680
IB
269 if self.is_loaded_playing():
270 ms = int(self.sound_position * 1000)
271 ms_fo = max(1, int(fade_out * 1000))
272
2e404903
IB
273 new_audio_segment = self.current_audio_segment[: ms+ms_fo] \
274 .fade_out(ms_fo)
29597680 275 with self.music_lock:
22514f3a
IB
276 self.current_audio_segment = new_audio_segment
277 self.stop_playing()
1b4b78f5 278 if wait:
3aaddc9d
IB
279 if set_wait_id is not None:
280 self.mapping.add_wait_id(set_wait_id, self.wait_event)
1b4b78f5 281 self.wait_end()
0e5d59f7 282 else:
29597680
IB
283 self.stop_playing()
284 self.stopped()
0e5d59f7 285
aee1334c
IB
286 def volume_factor(self, additional_gain):
287 return 10 ** ( (self.db_gain + additional_gain) / 20)
288
b37c72a2
IB
289 def set_gain(self, db_gain, absolute=False):
290 if absolute:
291 self.db_gain = db_gain
292 else:
293 self.db_gain += db_gain
29597680 294
aee1334c 295 def set_volume(self, value, delta=False, fade=0):
2e404903
IB
296 [db_gain, self.volume] = gain(
297 value + int(delta) * self.volume,
298 self.volume)
1b4b78f5 299
55e4cf35
IB
300 if not (self.is_loaded_playing() or self.is_loaded_paused()):
301 return
302
aee1334c
IB
303 if fade > 0:
304 self.gain_effects.append(GainEffect(
305 "fade",
306 self.current_audio_segment,
1e44fe7e 307 self.current_loop,
aee1334c
IB
308 self.sound_position,
309 self.sound_position + fade,
310 gain=db_gain))
311 else:
312 self.set_gain(db_gain)
be27763f 313
b86db9f1 314 def wait_end(self):
0deb82a5
IB
315 self.wait_event.clear()
316 self.wait_event.wait()
d479af33 317