]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/commitdiff
Reorder MusicFile methods
authorIsmaël Bouya <ismael.bouya@normalesup.org>
Mon, 25 Jul 2016 14:53:46 +0000 (16:53 +0200)
committerIsmaël Bouya <ismael.bouya@normalesup.org>
Mon, 25 Jul 2016 14:53:46 +0000 (16:53 +0200)
helpers/action.py
helpers/mapping.py
helpers/mixer.py
helpers/music_file.py
music_sampler.py

index 99cd39966829c3075b44812bcd1d7c2db057675f..ec8fcb6f0b43748873eb2e8568589c62cfd36f58 100644 (file)
@@ -30,7 +30,7 @@ class Action:
 
     def ready(self):
         if 'music' in self.arguments:
-            return self.arguments['music'].check_is_loaded()
+            return self.arguments['music'].is_loaded(allow_substates=True)
         else:
             return True
 
@@ -71,14 +71,14 @@ class Action:
             loop=0, **kwargs):
         for music in self.music_list(music):
             if restart_if_running:
-                if music.is_not_stopped():
+                if music.is_in_use():
                     music.stop()
                 music.play(
                         volume=volume,
                         fade_in=fade_in,
                         start_at=start_at,
                         loop=loop)
-            elif not music.is_not_stopped():
+            elif not music.is_in_use():
                 music.play(
                         volume=volume,
                         fade_in=fade_in,
index d60e709bde0a80e96be783131d5ad4b847be6faa..c2a94e67baa52f3bfe4b06eccb78d88741805789 100644 (file)
@@ -10,7 +10,6 @@ import sys
 from .music_file import *
 from .mixer import Mixer
 from . import Config, gain, error_print
-from .music_effect import GainEffect
 from .action import Action
 
 class Mapping(RelativeLayout):
@@ -47,19 +46,7 @@ class Mapping(RelativeLayout):
                 self.master_volume)
 
         for music in self.open_files.values():
-            if not (music.is_loaded_playing() or music.is_loaded_paused()):
-                continue
-
-            if fade > 0:
-                music.gain_effects.append(GainEffect(
-                    "fade",
-                    music.current_audio_segment,
-                    music.current_loop,
-                    music.sound_position,
-                    music.sound_position + fade,
-                    gain=db_gain))
-            else:
-                music.set_gain(db_gain)
+            music.set_gain_with_effect(db_gain, fade=fade)
 
     def add_wait_id(self, wait_id, action_or_wait):
         self.wait_ids[wait_id] = action_or_wait
index 1d3f28fe21fb33e4986d829d154df822b81a6206..9242b61af9100e944b5060220bf40c0567741443 100644 (file)
@@ -35,7 +35,8 @@ class Mixer:
         self.start()
 
     def remove_file(self, music_file):
-        self.open_files.remove(music_file)
+        if music_file in self.open_files:
+            self.open_files.remove(music_file)
         if len(self.open_files) == 0:
             self.stop()
 
index 017fc596e236e14c700bff5bb88c746e56d38372..ccf60ce5eb8874f5b68dc81d48a89b9e86fd8626 100644 (file)
@@ -15,84 +15,78 @@ from .music_effect import GainEffect
 file_lock = Lock("file")
 
 class MusicFile:
+    STATES = [
+        'initial',
+        'loading',
+        'failed',
+        {
+            'name': 'loaded',
+            'children': [
+                'playing',
+                'paused',
+                'stopping'
+            ]
+        }
+    ]
+    TRANSITIONS = [
+        {
+            'trigger': 'load',
+            'source': 'initial',
+            'dest': 'loading'
+        },
+        {
+            'trigger': 'fail',
+            'source': 'loading',
+            'dest': 'failed'
+        },
+        {
+            'trigger': 'success',
+            'source': 'loading',
+            'dest': 'loaded'
+        },
+        {
+            'trigger': 'start_playing',
+            'source': 'loaded',
+            'dest': 'loaded_playing'
+        },
+        {
+            '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': '*',
+            'dest': 'loaded',
+            'before': 'trigger_stopped_events'
+        }
+    ]
+
     def __init__(self, filename, mapping, name=None, gain=1):
-        states = [
-            'initial',
-            'loading',
-            'failed',
-            {
-                'name': 'loaded',
-                'children': [
-                    'stopped',
-                    'playing',
-                    'paused',
-                    'stopping',
-                    'stopped'
-                ]
-            }
-        ]
-        transitions = [
-            {
-                'trigger': 'load',
-                'source': 'initial',
-                'dest': 'loading'
-            },
-            {
-                'trigger': 'fail',
-                'source': 'loading',
-                'dest': 'failed'
-            },
-            {
-                'trigger': 'success',
-                'source': 'loading',
-                'dest': 'loaded_stopped'
-            },
-            {
-                'trigger': 'start_playing',
-                'source': 'loaded_stopped',
-                'dest': 'loaded_playing'
-            },
-            {
-                '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',
-                'after': 'trigger_stopped_events'
-            }
-        ]
-
-        Machine(model=self, states=states,
-                transitions=transitions, initial='initial',
+        Machine(model=self, states=self.STATES,
+                transitions=self.TRANSITIONS, initial='initial',
                 ignore_invalid_triggers=True)
 
-        self.volume = 100
         self.mapping = mapping
         self.filename = filename
         self.name = name or filename
         self.audio_segment = None
-        self.audio_segment_frame_width = 0
         self.initial_volume_factor = gain
         self.music_lock = Lock("music__" + filename)
-        self.wait_event = threading.Event()
-        self.db_gain = 0
-        self.gain_effects = []
 
         threading.Thread(name="MSMusicLoad", target=self.load).start()
 
+    # Machine related events
     def on_enter_loading(self):
         with file_lock:
             try:
@@ -105,7 +99,6 @@ class MusicFile:
                         .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:
                 error_print("failed to load « {} »: {}".format(self.name, e))
@@ -115,28 +108,40 @@ class MusicFile:
                 self.success()
                 debug_print("Loaded « {} »".format(self.name))
 
-    def check_is_loaded(self):
-        return self.state.startswith('loaded_')
+    def on_enter_loaded(self):
+        self.gain_effects = []
+        self.set_gain(0, absolute=True)
+        self.current_audio_segment = None
+        self.volume = 100
+        self.wait_event = threading.Event()
+        self.current_loop = 0
+
+    def on_enter_loaded_playing(self):
+        self.mixer.add_file(self)
 
-    def is_not_stopped(self):
-        return self.check_is_loaded() and not self.is_loaded_stopped()
+    # Machine related states
+    def is_in_use(self):
+        return self.is_loaded(allow_substates=True) and not self.is_loaded()
 
-    def is_paused(self):
-        return self.is_loaded_paused()
+    def is_in_use_not_stopping(self):
+        return self.is_loaded_playing() or self.is_loaded_paused()
 
+    # Machine related triggers
+    def trigger_stopped_events(self):
+        self.mixer.remove_file(self)
+        self.wait_event.set()
+
+    # Actions and properties called externally
     @property
     def sound_position(self):
-        if self.is_not_stopped():
+        if self.is_in_use():
             return self.current_frame / self.current_audio_segment.frame_rate
         else:
             return 0
 
     def play(self, fade_in=0, volume=100, loop=0, start_at=0):
-        # FIXME: create a "reinitialize" method
-        self.gain_effects = []
         self.set_gain(gain(volume) + self.mapping.master_gain, absolute=True)
         self.volume = volume
-        self.current_loop = 0
         if loop < 0:
             self.last_loop = float('inf')
         else:
@@ -145,31 +150,89 @@ class MusicFile:
         with self.music_lock:
             self.current_audio_segment = self.audio_segment
             self.current_frame = int(start_at * self.audio_segment.frame_rate)
-            if fade_in > 0:
-                db_gain = gain(self.volume, 0)[0]
-                self.set_gain(-db_gain)
-                self.gain_effects.append(GainEffect(
-                    "fade",
-                    self.current_audio_segment,
-                    self.current_loop,
-                    self.sound_position,
-                    self.sound_position + fade_in,
-                    gain=db_gain))
 
         self.start_playing()
 
-    def on_enter_loaded_playing(self):
-        self.mixer.add_file(self)
+        if fade_in > 0:
+            db_gain = gain(self.volume, 0)[0]
+            self.set_gain(-db_gain)
+            self.add_fade_effect(db_gain, fade_in)
 
-    def finished_callback(self):
+    def seek(self, value=0, delta=False):
+        if not self.is_in_use_not_stopping():
+            return
+
+        with self.music_lock:
+            self.abandon_all_effects()
+            if delta:
+                frame_count = int(self.audio_segment.frame_count())
+                frame_diff = int(value * self.audio_segment.frame_rate)
+                self.current_frame += frame_diff
+                while self.current_frame < 0:
+                    self.current_loop -= 1
+                    self.current_frame += frame_count
+                while self.current_frame > frame_count:
+                    self.current_loop += 1
+                    self.current_frame -= frame_count
+                if self.current_loop < 0:
+                    self.current_loop = 0
+                    self.current_frame = 0
+                if self.current_loop > self.last_loop:
+                    self.current_loop = self.last_loop
+                    self.current_frame = frame_count
+            else:
+                self.current_frame = max(
+                        0,
+                        int(value * self.audio_segment.frame_rate))
+
+    def stop(self, fade_out=0, wait=False, set_wait_id=None):
         if self.is_loaded_playing():
+            ms = int(self.sound_position * 1000)
+            ms_fo = max(1, int(fade_out * 1000))
+
+            new_audio_segment = self.current_audio_segment[: ms+ms_fo] \
+                .fade_out(ms_fo)
+            with self.music_lock:
+                self.current_audio_segment = new_audio_segment
             self.stop_playing()
-        if self.is_loaded_stopping():
+            if wait:
+                if set_wait_id is not None:
+                    self.mapping.add_wait_id(set_wait_id, self.wait_event)
+                self.wait_end()
+        else:
             self.stopped()
 
-    def trigger_stopped_events(self):
-        self.mixer.remove_file(self)
-        self.wait_event.set()
+    def abandon_all_effects(self):
+        db_gain = 0
+        for gain_effect in self.gain_effects:
+            db_gain += gain_effect.get_last_gain()
+
+        self.gain_effects = []
+        self.set_gain(db_gain)
+
+    def set_volume(self, value, delta=False, fade=0):
+        [db_gain, self.volume] = gain(
+                value + int(delta) * self.volume,
+                self.volume)
+
+        self.set_gain_with_effect(db_gain, fade=fade)
+
+    def set_gain_with_effect(self, db_gain, fade=0):
+        if not self.is_in_use():
+            return
+
+        if fade > 0:
+            self.add_fade_effect(db_gain, fade)
+        else:
+            self.set_gain(db_gain)
+
+    def wait_end(self):
+        self.wait_event.clear()
+        self.wait_event.wait()
+
+    # Callbacks
+    def finished_callback(self):
+        self.stopped()
 
     def play_callback(self, out_data_length, frame_count):
         if self.is_loaded_paused():
@@ -194,8 +257,15 @@ class MusicFile:
 
             return data.ljust(out_data_length, b'\0')
 
+    # Helpers
+    def set_gain(self, db_gain, absolute=False):
+        if absolute:
+            self.db_gain = db_gain
+        else:
+            self.db_gain += db_gain
+
     def get_next_sample(self, frame_count):
-        fw = self.audio_segment_frame_width
+        fw = self.audio_segment.frame_width
 
         data = b""
         nb_frames = 0
@@ -215,32 +285,17 @@ class MusicFile:
 
         return [data, nb_frames]
 
-    def seek(self, value=0, delta=False):
-        # We don't want to do that while stopping
-        if not (self.is_loaded_playing() or self.is_loaded_paused()):
+    def add_fade_effect(self, db_gain, fade_duration):
+        if not self.is_in_use():
             return
-        with self.music_lock:
-            self.abandon_all_effects()
-            if delta:
-                frame_count = int(self.audio_segment.frame_count())
-                frame_diff = int(value * self.audio_segment.frame_rate)
-                self.current_frame += frame_diff
-                while self.current_frame < 0:
-                    self.current_loop -= 1
-                    self.current_frame += frame_count
-                while self.current_frame > frame_count:
-                    self.current_loop += 1
-                    self.current_frame -= frame_count
-                if self.current_loop < 0:
-                    self.current_loop = 0
-                    self.current_frame = 0
-                if self.current_loop > self.last_loop:
-                    self.current_loop = self.last_loop
-                    self.current_frame = frame_count
-            else:
-                self.current_frame = max(
-                        0,
-                        int(value * self.audio_segment.frame_rate))
+
+        self.gain_effects.append(GainEffect(
+            "fade",
+            self.current_audio_segment,
+            self.current_loop,
+            self.sound_position,
+            self.sound_position + fade_duration,
+            gain=db_gain))
 
     def effects_next_gain(self, frame_count):
         db_gain = 0
@@ -257,61 +312,6 @@ class MusicFile:
         return db_gain
 
 
-    def abandon_all_effects(self):
-        db_gain = 0
-        for gain_effect in self.gain_effects:
-            db_gain += gain_effect.get_last_gain()
-
-        self.gain_effects = []
-        self.set_gain(db_gain)
-
-    def stop(self, fade_out=0, wait=False, set_wait_id=None):
-        if self.is_loaded_playing():
-            ms = int(self.sound_position * 1000)
-            ms_fo = max(1, int(fade_out * 1000))
-
-            new_audio_segment = self.current_audio_segment[: ms+ms_fo] \
-                .fade_out(ms_fo)
-            with self.music_lock:
-                self.current_audio_segment = new_audio_segment
-            self.stop_playing()
-            if wait:
-                if set_wait_id is not None:
-                    self.mapping.add_wait_id(set_wait_id, self.wait_event)
-                self.wait_end()
-        else:
-            self.stop_playing()
-            self.stopped()
-
-    def volume_factor(self, additional_gain):
+    def volume_factor(self, additional_gain=0):
         return 10 ** ( (self.db_gain + additional_gain) / 20)
 
-    def set_gain(self, db_gain, absolute=False):
-        if absolute:
-            self.db_gain = db_gain
-        else:
-            self.db_gain += db_gain
-
-    def set_volume(self, value, delta=False, fade=0):
-        [db_gain, self.volume] = gain(
-                value + int(delta) * self.volume,
-                self.volume)
-
-        if not (self.is_loaded_playing() or self.is_loaded_paused()):
-            return
-
-        if fade > 0:
-            self.gain_effects.append(GainEffect(
-                "fade",
-                self.current_audio_segment,
-                self.current_loop,
-                self.sound_position,
-                self.sound_position + fade,
-                gain=db_gain))
-        else:
-            self.set_gain(db_gain)
-
-    def wait_end(self):
-        self.wait_event.clear()
-        self.wait_event.wait()
-
index d91e150aed51d93d9fa6e7432b2971c3cb05c398..41b71be5bd1bd96502b18981c96725bef8554446 100644 (file)
@@ -45,14 +45,14 @@ class PlayList(RelativeLayout):
         open_files = self.parent.ids['Mapping'].open_files
         self.playlist = []
         for music_file in open_files.values():
-            if not music_file.is_not_stopped():
+            if not music_file.is_in_use():
                 continue
 
             text = "{}/{}".format(
                     helpers.duration_to_min_sec(music_file.sound_position),
                     helpers.duration_to_min_sec(music_file.sound_duration))
 
-            if music_file.is_paused():
+            if music_file.is_loaded_paused():
                 self.playlist.append(["⏸", music_file.name, text, False])
             else:
                 self.playlist.append(["⏵", music_file.name, text, True])