]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blobdiff - helpers/music_file.py
Do gain at the last moment
[perso/Immae/Projets/Python/MusicSampler.git] / helpers / music_file.py
index ebe458beb595aefc0d9ac2c9f5d0de2f35f985e5..56060bd8d9368ab8e9e08d7f2cd9a4f7b37f0c1d 100644 (file)
@@ -3,11 +3,13 @@ import pydub
 import time
 from transitions.extensions import HierarchicalMachine as Machine
 
-import sounddevice as sd
 import os.path
 
+import audioop
+
 from .lock import Lock
-from . import gain
+from . import Config, gain, debug_print, error_print
+from .mixer import Mixer
 
 file_lock = Lock("file")
 
@@ -27,7 +29,7 @@ class MusicFile(Machine):
             { 'trigger': 'pause', 'source':  'loaded_playing', 'dest': 'loaded_paused'},
             { 'trigger': 'unpause', 'source':  'loaded_paused', 'dest': 'loaded_playing'},
             { 'trigger': 'stop_playing', 'source': ['loaded_playing','loaded_paused'], 'dest': 'loaded_stopping'},
-            { 'trigger': 'stopped', 'source':  'loaded_stopping', 'dest': 'loaded_stopped'}
+            { 'trigger': 'stopped', 'source':  'loaded_stopping', 'dest': 'loaded_stopped', 'after': 'trigger_stopped_events'}
         ]
 
         Machine.__init__(self, states=states, transitions=transitions, initial='initial')
@@ -35,31 +37,32 @@ class MusicFile(Machine):
         self.volume = 100
         self.mapping = mapping
         self.filename = filename
-        self.stream = None
         self.name = name or filename
         self.audio_segment = None
         self.audio_segment_frame_width = 0
-        self.volume_factor = gain
+        self.initial_volume_factor = gain
         self.music_lock = Lock("music__" + filename)
         self.wait_event = threading.Event()
+        self.db_gain = 0
 
         threading.Thread(name = "MSMusicLoad", target = self.load).start()
 
     def on_enter_loading(self):
         with file_lock:
             try:
-                print("Loading « {} »".format(self.name))
-                db_gain = gain(self.volume_factor * 100)
-                self.audio_segment = pydub.AudioSegment.from_file(self.filename).set_frame_rate(44100).apply_gain(db_gain)
+                debug_print("Loading « {} »".format(self.name))
+                self.mixer = self.mapping.mixer or Mixer()
+                initial_db_gain = gain(self.initial_volume_factor * 100)
+                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)
                 self.audio_segment_frame_width = self.audio_segment.frame_width
                 self.sound_duration = self.audio_segment.duration_seconds
             except Exception as e:
-                print("failed to load « {} »: {}".format(self.name, e))
+                error_print("failed to load « {} »: {}".format(self.name, e))
                 self.loading_error = e
                 self.fail()
             else:
                 self.success()
-                print("Loaded « {} »".format(self.name))
+                debug_print("Loaded « {} »".format(self.name))
 
     def check_is_loaded(self):
         return self.state.startswith('loaded_')
@@ -78,14 +81,14 @@ class MusicFile(Machine):
             return 0
 
     def play(self, fade_in = 0, volume = 100, loop = 0, start_at = 0):
-        db_gain = gain(volume) + self.mapping.master_gain
+        self.db_gain = gain(volume) + self.mapping.master_gain
         self.volume = volume
         self.loop = loop
 
         ms = int(start_at * 1000)
         ms_fi = int(fade_in * 1000)
         with self.music_lock:
-            self.current_audio_segment = (self.audio_segment + db_gain)
+            self.current_audio_segment = self.audio_segment
             self.current_frame = int(start_at * self.audio_segment.frame_rate)
             if ms_fi > 0:
                 # FIXME: apply it to repeated when looping?
@@ -94,26 +97,10 @@ class MusicFile(Machine):
             else:
                 self.a_s_with_effect = None
 
-        self.before_loaded_playing()
         self.start_playing()
 
-    def before_loaded_playing(self):
-        with self.music_lock:
-            segment = self.current_audio_segment
-
-            self.stream = sd.RawOutputStream(samplerate=segment.frame_rate,
-                            channels=segment.channels,
-                            dtype='int' + str(8*segment.sample_width), # FIXME: ?
-                            latency=1.,
-                            callback=self.play_callback,
-                            finished_callback=self.finished_callback
-                            )
-
     def on_enter_loaded_playing(self):
-        self.stream.start()
-
-    def on_enter_loaded_paused(self):
-        self.stream.stop()
+        self.mixer.add_file(self)
 
     def finished_callback(self):
         if self.is_loaded_playing():
@@ -121,10 +108,14 @@ class MusicFile(Machine):
         if self.is_loaded_stopping():
             self.stopped()
 
-    def on_enter_loaded_stopped(self):
+    def trigger_stopped_events(self):
+        self.mixer.remove_file(self)
         self.wait_event.set()
 
-    def play_callback(self, out_data, frame_count, time_info, status_flags):
+    def play_callback(self, out_data_length, frame_count):
+        if self.is_loaded_paused():
+            return b'\0' * out_data_length
+
         with self.music_lock:
             [data, nb_frames] = self.get_next_sample(frame_count)
             if nb_frames < frame_count:
@@ -135,9 +126,10 @@ class MusicFile(Machine):
                     data += new_data
                     nb_frames += new_nb_frames
                 elif nb_frames == 0:
-                    raise sd.CallbackStop
+                    # FIXME: too slow
+                    threading.Thread(name = "MSFinishedCallback", target=self.finished_callback).start()
 
-            out_data[:] = data.ljust(len(out_data), b'\0')
+            return data.ljust(out_data_length, b'\0')
 
     def get_next_sample(self, frame_count):
         fw = self.audio_segment_frame_width
@@ -171,6 +163,8 @@ class MusicFile(Machine):
         nb_frames += end_i - start_i
         self.current_frame += end_i - start_i
 
+        data = audioop.mul(data, Config.sample_width, self.volume_factor)
+
         return [data, nb_frames]
 
     def seek(self, value = 0, delta = False):
@@ -187,11 +181,10 @@ class MusicFile(Machine):
             ms = int(self.sound_position * 1000)
             ms_fo = max(1, int(fade_out * 1000))
 
-            # FIXME: stop fade_out puis seek -5 -> on abandonne le fade ? (cf
-            # commentaire dans fonction seek
+            new_audio_segment = self.current_audio_segment[:ms + ms_fo].fade_out(ms_fo)
             with self.music_lock:
-                self.current_audio_segment = self.current_audio_segment[:ms + ms_fo].fade_out(ms_fo)
-                self.stop_playing()
+                self.current_audio_segment = new_audio_segment
+            self.stop_playing()
             if wait:
                 self.wait_end()
         else:
@@ -199,18 +192,8 @@ class MusicFile(Machine):
             self.stopped()
 
     def set_gain(self, db_gain):
-        if not self.is_not_stopped():
-            return
-
-        new_audio_segment = self.current_audio_segment + db_gain
-
-        new_a_s_with_effect = None
-        if self.a_s_with_effect is not None:
-            new_a_s_with_effect = self.a_s_with_effect + db_gain
-
-        with self.music_lock:
-            self.current_audio_segment = new_audio_segment
-            self.a_s_with_effect = new_a_s_with_effect
+        self.db_gain += db_gain
+        self.volume_factor = 10 ** (self.db_gain / 20)
 
     def set_volume(self, value, delta = False):
         [db_gain, self.volume] = gain(value + int(delta) * self.volume, self.volume)
@@ -221,13 +204,3 @@ class MusicFile(Machine):
         self.wait_event.clear()
         self.wait_event.wait()
 
-# Add some more functions to AudioSegments
-def get_sample_slice_data(self, start_sample=0, end_sample=float('inf')):
-    max_val = int(self.frame_count())
-
-    start_i = max(start_sample, 0) * self.frame_width
-    end_i =   min(end_sample, max_val) * self.frame_width
-
-    return self._data[start_i:end_i]
-
-pydub.AudioSegment.get_sample_slice_data = get_sample_slice_data