]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blame - helpers/music_file.py
Do gain at the last moment
[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
1b4b78f5 13
29597680
IB
14file_lock = Lock("file")
15
60979de4 16class MusicFile(Machine):
1b4b78f5 17 def __init__(self, filename, mapping, name = None, gain = 1):
60979de4
IB
18 states = [
19 'initial',
20 'loading',
21 'failed',
29597680 22 { 'name': 'loaded', 'children': ['stopped', 'playing', 'paused', 'stopping'] }
60979de4
IB
23 ]
24 transitions = [
25 { 'trigger': 'load', 'source': 'initial', 'dest': 'loading'},
26 { 'trigger': 'fail', 'source': 'loading', 'dest': 'failed'},
27 { 'trigger': 'success', 'source': 'loading', 'dest': 'loaded_stopped'},
29597680
IB
28 { 'trigger': 'start_playing', 'source': 'loaded_stopped', 'dest': 'loaded_playing'},
29 { 'trigger': 'pause', 'source': 'loaded_playing', 'dest': 'loaded_paused'},
30 { 'trigger': 'unpause', 'source': 'loaded_paused', 'dest': 'loaded_playing'},
31 { 'trigger': 'stop_playing', 'source': ['loaded_playing','loaded_paused'], 'dest': 'loaded_stopping'},
22514f3a 32 { 'trigger': 'stopped', 'source': 'loaded_stopping', 'dest': 'loaded_stopped', 'after': 'trigger_stopped_events'}
60979de4
IB
33 ]
34
35 Machine.__init__(self, states=states, transitions=transitions, initial='initial')
36
1b4b78f5
IB
37 self.volume = 100
38 self.mapping = mapping
be27763f 39 self.filename = filename
9de92b6d 40 self.name = name or filename
29597680 41 self.audio_segment = None
ccc8b4f2 42 self.audio_segment_frame_width = 0
ccda4cb9 43 self.initial_volume_factor = gain
29597680 44 self.music_lock = Lock("music__" + filename)
0deb82a5 45 self.wait_event = threading.Event()
ccda4cb9 46 self.db_gain = 0
be27763f 47
29597680
IB
48 threading.Thread(name = "MSMusicLoad", target = self.load).start()
49
50 def on_enter_loading(self):
51 with file_lock:
52 try:
a24c34bc
IB
53 debug_print("Loading « {} »".format(self.name))
54 self.mixer = self.mapping.mixer or Mixer()
ccda4cb9
IB
55 initial_db_gain = gain(self.initial_volume_factor * 100)
56 self.audio_segment = pydub.AudioSegment.from_file(self.filename).set_frame_rate(Config.frame_rate).set_channels(Config.channels).set_sample_width(Config.sample_width).apply_gain(initial_db_gain)
ccc8b4f2 57 self.audio_segment_frame_width = self.audio_segment.frame_width
29597680
IB
58 self.sound_duration = self.audio_segment.duration_seconds
59 except Exception as e:
a24c34bc 60 error_print("failed to load « {} »: {}".format(self.name, e))
29597680
IB
61 self.loading_error = e
62 self.fail()
63 else:
64 self.success()
a24c34bc 65 debug_print("Loaded « {} »".format(self.name))
60979de4
IB
66
67 def check_is_loaded(self):
68 return self.state.startswith('loaded_')
be27763f 69
29597680
IB
70 def is_not_stopped(self):
71 return self.check_is_loaded() and not self.is_loaded_stopped()
0e5d59f7 72
9de92b6d 73 def is_paused(self):
29597680 74 return self.is_loaded_paused()
9de92b6d 75
98ff4305
IB
76 @property
77 def sound_position(self):
29597680
IB
78 if self.is_not_stopped():
79 return self.current_frame / self.current_audio_segment.frame_rate
98ff4305
IB
80 else:
81 return 0
82
6f4944c1 83 def play(self, fade_in = 0, volume = 100, loop = 0, start_at = 0):
ccda4cb9 84 self.db_gain = gain(volume) + self.mapping.master_gain
1b4b78f5 85 self.volume = volume
6f4944c1 86 self.loop = loop
1b4b78f5 87
29597680 88 ms = int(start_at * 1000)
ccc8b4f2 89 ms_fi = int(fade_in * 1000)
29597680 90 with self.music_lock:
ccda4cb9 91 self.current_audio_segment = self.audio_segment
ccc8b4f2
IB
92 self.current_frame = int(start_at * self.audio_segment.frame_rate)
93 if ms_fi > 0:
94 # FIXME: apply it to repeated when looping?
95 self.a_s_with_effect = self.current_audio_segment[ms:ms+ms_fi].fade_in(ms_fi)
96 self.current_frame_with_effect = 0
97 else:
98 self.a_s_with_effect = None
99
29597680
IB
100 self.start_playing()
101
29597680 102 def on_enter_loaded_playing(self):
af27d782 103 self.mixer.add_file(self)
29597680
IB
104
105 def finished_callback(self):
106 if self.is_loaded_playing():
107 self.stop_playing()
108 if self.is_loaded_stopping():
109 self.stopped()
110
22514f3a 111 def trigger_stopped_events(self):
af27d782 112 self.mixer.remove_file(self)
0deb82a5
IB
113 self.wait_event.set()
114
22514f3a
IB
115 def play_callback(self, out_data_length, frame_count):
116 if self.is_loaded_paused():
117 return b'\0' * out_data_length
118
29597680 119 with self.music_lock:
ccc8b4f2
IB
120 [data, nb_frames] = self.get_next_sample(frame_count)
121 if nb_frames < frame_count:
6f4944c1
IB
122 if self.is_loaded_playing() and self.loop != 0:
123 self.loop -= 1
ccc8b4f2
IB
124 self.current_frame = 0
125 [new_data, new_nb_frames] = self.get_next_sample(frame_count - nb_frames)
126 data += new_data
127 nb_frames += new_nb_frames
128 elif nb_frames == 0:
75d6cdba 129 # FIXME: too slow
22514f3a 130 threading.Thread(name = "MSFinishedCallback", target=self.finished_callback).start()
29597680 131
22514f3a 132 return data.ljust(out_data_length, b'\0')
ccc8b4f2
IB
133
134 def get_next_sample(self, frame_count):
135 fw = self.audio_segment_frame_width
136
137 data = b""
138 nb_frames = 0
139 if self.a_s_with_effect is not None:
140 segment = self.a_s_with_effect
141 max_val = int(segment.frame_count())
142
143 start_i = max(self.current_frame_with_effect, 0)
144 end_i = min(self.current_frame_with_effect + frame_count, max_val)
145
146 data += segment._data[(start_i * fw):(end_i * fw)]
147
148 frame_count = max(0, self.current_frame_with_effect + frame_count - max_val)
149
150 self.current_frame_with_effect += end_i - start_i
151 self.current_frame += end_i - start_i
152 nb_frames += end_i - start_i
153
154 if frame_count > 0:
155 self.a_s_with_effect = None
156
157 segment = self.current_audio_segment
158 max_val = int(segment.frame_count())
159
160 start_i = max(self.current_frame, 0)
161 end_i = min(self.current_frame + frame_count, max_val)
162 data += segment._data[(start_i * fw):(end_i * fw)]
163 nb_frames += end_i - start_i
164 self.current_frame += end_i - start_i
165
ccda4cb9
IB
166 data = audioop.mul(data, Config.sample_width, self.volume_factor)
167
ccc8b4f2 168 return [data, nb_frames]
be27763f 169
52d58baf
IB
170 def seek(self, value = 0, delta = False):
171 # We don't want to do that while stopping
172 if not (self.is_loaded_playing() or self.is_loaded_paused()):
173 return
174 with self.music_lock:
ccc8b4f2 175 self.a_s_with_effect = None
52d58baf 176 self.current_frame = max(0, int(delta) * self.current_frame + int(value * self.audio_segment.frame_rate))
ccc8b4f2 177 # FIXME: si on fait un seek + delta, adapter le "loop"
52d58baf 178
1b4b78f5 179 def stop(self, fade_out = 0, wait = False):
29597680
IB
180 if self.is_loaded_playing():
181 ms = int(self.sound_position * 1000)
182 ms_fo = max(1, int(fade_out * 1000))
183
22514f3a 184 new_audio_segment = self.current_audio_segment[:ms + ms_fo].fade_out(ms_fo)
29597680 185 with self.music_lock:
22514f3a
IB
186 self.current_audio_segment = new_audio_segment
187 self.stop_playing()
1b4b78f5
IB
188 if wait:
189 self.wait_end()
0e5d59f7 190 else:
29597680
IB
191 self.stop_playing()
192 self.stopped()
0e5d59f7 193
1b4b78f5 194 def set_gain(self, db_gain):
ccda4cb9
IB
195 self.db_gain += db_gain
196 self.volume_factor = 10 ** (self.db_gain / 20)
29597680 197
8e50011c
IB
198 def set_volume(self, value, delta = False):
199 [db_gain, self.volume] = gain(value + int(delta) * self.volume, self.volume)
1b4b78f5
IB
200
201 self.set_gain(db_gain)
be27763f 202
b86db9f1 203 def wait_end(self):
0deb82a5
IB
204 self.wait_event.clear()
205 self.wait_event.wait()
d479af33 206