0
1
mirror of https://github.com/radio95-rnt/RadioPlayer.git synced 2026-02-26 21:53:54 +01:00

compression?

This commit is contained in:
Kuba
2025-11-02 10:31:02 +01:00
parent 7769d95f0c
commit 3484f0cd61
8 changed files with 27 additions and 34 deletions

View File

@@ -40,6 +40,8 @@ class PlayerModule(BaseIMCModule):
def progress(self, index: int, track: Track, elapsed: float, total: float, real_total: float) -> None: def progress(self, index: int, track: Track, elapsed: float, total: float, real_total: float) -> None:
""" """
Real total and total differ in that, total is how much the track lasts, but real_total will be for how long we will play it for Real total and total differ in that, total is how much the track lasts, but real_total will be for how long we will play it for
Runs at a frequency around 1 Hz
Please don't put any blocking or code that takes time
""" """
pass pass
class PlaylistModifierModule: class PlaylistModifierModule:
@@ -92,6 +94,8 @@ class InterModuleCommunication:
self.active_modifier = active_modifier self.active_modifier = active_modifier
self.simple_modules = simple_modules self.simple_modules = simple_modules
self.names_modules: dict[str, BaseIMCModule] = {} self.names_modules: dict[str, BaseIMCModule] = {}
for module in simple_modules + [active_modifier, advisor]:
if module: module.imc(self)
def broadcast(self, source: BaseIMCModule, data: object) -> None: def broadcast(self, source: BaseIMCModule, data: object) -> None:
""" """
Send data to all modules, other than ourself Send data to all modules, other than ourself

View File

@@ -15,11 +15,11 @@ playlist_dir = "/home/user/playlists"
class Time: class Time:
@staticmethod @staticmethod
def get_playlist_modification_time(playlist_path): def get_playlist_modification_time(playlist_path) -> float:
try: return os.path.getmtime(playlist_path) try: return os.path.getmtime(playlist_path)
except OSError: return 0 except OSError: return 0
def check_if_playlist_modifed(playlist_path: str): def check_if_playlist_modifed(playlist_path: str) -> bool:
current_day, current_hour = datetime.datetime.now().strftime('%A').lower(), datetime.datetime.now().hour current_day, current_hour = datetime.datetime.now().strftime('%A').lower(), datetime.datetime.now().hour
morning_playlist_path = os.path.join(playlist_dir, current_day, 'morning') morning_playlist_path = os.path.join(playlist_dir, current_day, 'morning')
day_playlist_path = os.path.join(playlist_dir, current_day, 'day') day_playlist_path = os.path.join(playlist_dir, current_day, 'day')
@@ -107,7 +107,7 @@ class Module(PlaylistAdvisor):
logger.info("Playlist changed on disc, reloading...") logger.info("Playlist changed on disc, reloading...")
return True return True
return False return False
def imc(self, imc: InterModuleCommunication): def imc(self, imc: InterModuleCommunication) -> None:
self.class_imc = imc self.class_imc = imc
imc.register(self, "advisor") imc.register(self, "advisor")
def imc_data(self, source: PlayerModule | ActiveModifier | PlaylistAdvisor, source_name: str | None, data: object, broadcast: bool): def imc_data(self, source: PlayerModule | ActiveModifier | PlaylistAdvisor, source_name: str | None, data: object, broadcast: bool):

View File

@@ -1,14 +1,14 @@
from . import PlayerModule, Track from . import PlayerModule, Track
import os import os
def format_time(seconds): def format_time(seconds) -> str:
hours = int(seconds // 3600) hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60) minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60) secs = int(seconds % 60)
return f"{hours:02d}:{minutes:02d}:{secs:02d}" return f"{hours:02d}:{minutes:02d}:{secs:02d}"
class Module(PlayerModule): class Module(PlayerModule):
def progress(self, index: int, track: Track, elapsed: float, total: float, real_total: float): def progress(self, index: int, track: Track, elapsed: float, total: float, real_total: float) -> None:
if track.official: if track.official:
print(f"{os.path.basename(track.path)}: {format_time(elapsed)} / {format_time(total)}", end="\r", flush=True) print(f"{os.path.basename(track.path)}: {format_time(elapsed)} / {format_time(total)}", end="\r", flush=True)

View File

@@ -13,8 +13,8 @@ from . import PlaylistModifierModule, Track
class Module(PlaylistModifierModule): class Module(PlaylistModifierModule):
def __init__(self, file: str) -> None: def __init__(self, file: str) -> None:
self.file = file self.file = file
def modify(self, global_args: dict, playlist: list[Track]): def modify(self, global_args: dict, playlist: list[Track]) -> list[Track] | None:
if int(global_args.get("no_jingle", 0)): return playlist if int(global_args.get("no_jingle", 0)): return None
out: list[Track] = [] out: list[Track] = []
last_jingiel = True last_jingiel = True
for track in playlist: for track in playlist:
@@ -22,9 +22,9 @@ class Module(PlaylistModifierModule):
out.append(Track(track.path, True, False, True, track.args)) out.append(Track(track.path, True, False, True, track.args))
out.append(Track(self.file, False, False, False, {})) out.append(Track(self.file, False, False, False, {}))
last_jingiel = True last_jingiel = True
else: continue
out.append(Track(track.path, True, True, True, track.args)) out.append(Track(track.path, True, True, True, track.args))
last_jingiel = False last_jingiel = False
del last_jingiel del last_jingiel
return out return out

View File

@@ -7,7 +7,6 @@ name_table_path = "/home/user/mixes/name_table.txt"
rds_base = "Gramy: {} - {}" rds_base = "Gramy: {} - {}"
rds_default_artist = "radio95" rds_default_artist = "radio95"
rds_default_name = "Program Godzinny"
udp_host = ("127.0.0.1", 5000) udp_host = ("127.0.0.1", 5000)

View File

@@ -4,8 +4,7 @@ from . import PlaylistModifierModule, Track
class Module(PlaylistModifierModule): class Module(PlaylistModifierModule):
def modify(self, global_args: dict, playlist: list[Track]): def modify(self, global_args: dict, playlist: list[Track]):
if int(global_args.get("no_shuffle", 0)) == 0: if int(global_args.get("no_shuffle", 0)) == 0: random.shuffle(playlist)
random.shuffle(playlist) return None
return playlist
playlistmod = (Module(), 0) playlistmod = (Module(), 0)

View File

@@ -12,7 +12,7 @@ class Module(PlayerModule):
# discrepancy, which means that the playing file was modified by the active modifier # discrepancy, which means that the playing file was modified by the active modifier
# we are playing a file that was not determined in the playlist, that means it was chosen by the active modifier and made up on the fly # we are playing a file that was not determined in the playlist, that means it was chosen by the active modifier and made up on the fly
lines = self.playlist[:index] + [f"> ({track.path})"] + [self.playlist[index]] + self.playlist[index+1:] lines = self.playlist[:index] + [f"> ({track.path})"] + [self.playlist[index]] + self.playlist[index+1:]
logger.info("Next up:", self.playlist[index]) logger.info("Next up:", self.playlist[index]) # core no longer does this
else: else:
lines = self.playlist[:index] + [f"> {self.playlist[index]}"] + self.playlist[index+1:] lines = self.playlist[:index] + [f"> {self.playlist[index]}"] + self.playlist[index+1:]
if index + 1 < len(self.playlist): logger.info("Next up:", self.playlist[index+1]) if index + 1 < len(self.playlist): logger.info("Next up:", self.playlist[index+1])

View File

@@ -94,7 +94,6 @@ def handle_sigint(signum, frame):
logger.warning("Force-Quit pending") logger.warning("Force-Quit pending")
procman.stop_all() procman.stop_all()
raise SystemExit raise SystemExit
signal.signal(signal.SIGINT, handle_sigint) signal.signal(signal.SIGINT, handle_sigint)
def load_filelines(path): def load_filelines(path):
@@ -149,7 +148,7 @@ def parse_playlistfile(playlist_path: str) -> tuple[dict[str, str], list[tuple[l
return global_arguments, out return global_arguments, out
def play_playlist(playlist_path, starting_index: int = 0): def play_playlist(playlist_path, starting_index: int = 0):
if not playlist_advisor: raise Exception("No playlist advisor") if not playlist_advisor: raise Exception("No playlist advisor") # not sure how we would get this, but it makes pylance shut its fucking mouth
try: global_args, parsed = parse_playlistfile(playlist_path) try: global_args, parsed = parse_playlistfile(playlist_path)
except Exception as e: except Exception as e:
@@ -158,12 +157,11 @@ def play_playlist(playlist_path, starting_index: int = 0):
return return
playlist: list[Track] = [] playlist: list[Track] = []
for (lns, args) in parsed: [playlist.extend(Track(line, True, True, True, args) for line in lns) for (lns, args) in parsed] # i can read this, i think
playlist.extend([Track(line, True, True, True, args) for line in lns])
for module in playlist_modifier_modules: playlist = module.modify(global_args, playlist) or playlist for module in playlist_modifier_modules: playlist = module.modify(global_args, playlist) or playlist
for module in simple_modules: module.on_new_playlist(playlist)
if active_modifier: active_modifier.on_new_playlist(playlist) [mod.on_new_playlist(playlist) for mod in simple_modules + [active_modifier] if mod] # one liner'd everything
return_pending = False return_pending = False
@@ -176,7 +174,7 @@ def play_playlist(playlist_path, starting_index: int = 0):
if exit_pending: if exit_pending:
logger.info("Quit received, waiting for song end.") logger.info("Quit received, waiting for song end.")
procman.wait_all() procman.wait_all()
exit() raise SystemExit()
elif return_pending: elif return_pending:
logger.info("Return reached, next song will reload the playlist.") logger.info("Return reached, next song will reload the playlist.")
procman.wait_all() procman.wait_all()
@@ -199,9 +197,8 @@ def play_playlist(playlist_path, starting_index: int = 0):
track = old_track track = old_track
track_path = os.path.abspath(os.path.expanduser(track.path)) track_path = os.path.abspath(os.path.expanduser(track.path))
track_name = os.path.basename(track_path)
logger.info(f"Now playing: {track_name}") logger.info(f"Now playing: {os.path.basename(track_path)}")
for module in simple_modules: module.on_new_track(song_i, track) for module in simple_modules: module.on_new_track(song_i, track)
@@ -220,10 +217,7 @@ def play_playlist(playlist_path, starting_index: int = 0):
elapsed = time.monotonic() - start elapsed = time.monotonic() - start
remaining_until_end = end_time - time.monotonic() remaining_until_end = end_time - time.monotonic()
if elapsed < 1 and remaining_until_end > 0: time.sleep(min(1 - elapsed, remaining_until_end))
if elapsed < 1 and remaining_until_end > 0:
sleep_duration = min(1 - elapsed, remaining_until_end)
time.sleep(sleep_duration)
i += 1 i += 1
if not extend: song_i += 1 if not extend: song_i += 1
@@ -276,14 +270,11 @@ def main():
if not playlist_advisor: if not playlist_advisor:
logger.critical_error("Playlist advisor was not found") logger.critical_error("Playlist advisor was not found")
exit(1) raise SystemExit(1)
logger.info("Modules initialized, starting the IMC") logger.info("Modules initialized, starting the IMC")
imc = InterModuleCommunication(playlist_advisor, active_modifier, simple_modules) InterModuleCommunication(playlist_advisor, active_modifier, simple_modules)
playlist_advisor.imc(imc)
if active_modifier: active_modifier.imc(imc)
for module in simple_modules: module.imc(imc)
logger.info("Starting playback.") logger.info("Starting playback.")
@@ -294,7 +285,7 @@ def main():
if playlist := playlist_advisor.advise(arg): if playlist := playlist_advisor.advise(arg):
logger.info(f"Advisor picked '{playlist}' to play") logger.info(f"Advisor picked '{playlist}' to play")
play_playlist(playlist) play_playlist(playlist)
if exit_pending: exit() if exit_pending: raise SystemExit
except Exception as e: except Exception as e:
logger.critical_error(f"Unexpected error: {e}") logger.critical_error(f"Unexpected error: {e}")
raise raise