Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion radiostudio/services/audio_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,9 @@ def _pump(self):
while len(item["pending"]) >= PCM_BYTES_PER_FRAME:
frame = bytes(item["pending"][:PCM_BYTES_PER_FRAME])
del item["pending"][:PCM_BYTES_PER_FRAME]
self.broadcast.push_audio(f"input:{channel}", frame, self.monitor_gain)
# The monitor slider only controls local listening. Live inputs
# must reach the program bus at unity just like the main deck.
self.broadcast.push_audio(f"input:{channel}", frame, 1.0)
buffer = self.monitor_buffers.get(channel)
if self.monitor_enabled and buffer is not None:
buffer.append(frame)
Expand Down
5 changes: 5 additions & 0 deletions radiostudio/services/autodj.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,11 @@ def filter_tracks(tracks, filters):
track_year = int(track.get("year") or 0)
except (TypeError, ValueError, OverflowError):
track_year = 0
# An unknown year cannot satisfy a user-requested year range. Previously
# year_to by itself treated missing/invalid years as year zero and let
# those tracks through.
if (year_from or year_to) and track_year <= 0:
continue
if year_from and track_year < year_from:
continue
if year_to and track_year > year_to:
Expand Down
3 changes: 1 addition & 2 deletions radiostudio/ui/autodj_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def __init__(self, libraries, program=None, parent=None):
day_box = QGroupBox("Dias da semana")
day_layout = QHBoxLayout(day_box)
saved_days = set()
raw_days = program.get("days", range(7))
raw_days = program.get("days", list(range(7)))
if isinstance(raw_days, (list, tuple, set)):
for day in raw_days:
try:
Expand Down Expand Up @@ -542,4 +542,3 @@ def clear_history(self):
return
self.library.clear_history()
self.refresh_history(); self.main_window.save_state()

16 changes: 13 additions & 3 deletions radiostudio/ui/playlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@
from ..runtime_safety import guarded


def m3u_entries(lines):
"""Return meaningful M3U path entries with surrounding whitespace removed."""
result = []
for raw in lines:
line = str(raw).strip()
if line and not line.startswith("#"):
result.append(line)
return result


class PlaylistMixin:
@guarded
def refresh_playlist(self):
Expand Down Expand Up @@ -90,9 +100,9 @@ def open_m3u(self):
return
self.cancel_pending_transition()
base = Path(path).parent
lines = Path(path).read_text(encoding="utf-8-sig", errors="replace").splitlines()
lines = m3u_entries(Path(path).read_text(encoding="utf-8-sig", errors="replace").splitlines())
self.tracks = [str((base / line).resolve()) if not Path(line).is_absolute() else line
for line in lines if line.strip() and not line.startswith("#")]
for line in lines]
self.track_sources = ["manual"] * len(self.tracks)
self.current_index = -1
self.refresh_playlist()
Expand Down Expand Up @@ -181,7 +191,7 @@ def reorder_tracks(self, rows, target):
self.tracks = [track for _, track, _source in ordered]
self.track_sources = [source for _, _track, source in ordered]
if old_current >= 0:
self.current_index = next((new_index for new_index, (old_index, _track)
self.current_index = next((new_index for new_index, (old_index, _track, _source)
in enumerate(ordered) if old_index == old_current), -1)
self.refresh_playlist()
self.playlist.clearSelection()
Expand Down
9 changes: 7 additions & 2 deletions radiostudio/ui/settings_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,14 @@ def show_settings(self):
self.apply_audio_devices()
self.audio_input_controller.speech_threshold_db = self.speech_threshold_db
self.update_music_duck_target()
if current_track and self.player.playbackState() != QMediaPlayer.StoppedState:
# The modal settings window can stay open long enough for playback to
# advance. Re-read the current row here instead of publishing metadata
# captured when the dialog was opened.
current_on_air = (read_track_metadata(self.tracks[self.current_index])
if 0 <= self.current_index < len(self.tracks) else None)
if current_on_air and self.player.playbackState() != QMediaPlayer.StoppedState:
self.broadcast.set_title(format_broadcast_title(
self.station_metadata["title_format"], current_track, self.station_metadata))
self.station_metadata["title_format"], current_on_air, self.station_metadata))
if self.broadcast.local_server:
server = self.broadcast.local_server
server.station = self.broadcast_panel.local_config()["station"] or self.station_metadata["name"]
Expand Down
56 changes: 53 additions & 3 deletions tests/test_audio_inputs.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import struct
import unittest

from PySide6.QtCore import QCoreApplication
from PySide6.QtWidgets import QApplication
from PySide6.QtMultimedia import QAudioFormat

from radiostudio.services.audio_inputs import (convert_input_to_master,
convert_master_to_device,
mix_pcm_chunks, pcm_rms_db,
AudioInputController)
from radiostudio.services.broadcast import SAMPLE_RATE
from radiostudio.services.broadcast import PCM_BYTES_PER_FRAME, SAMPLE_RATE


class AudioInputConversionTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = QCoreApplication.instance() or QCoreApplication([])
cls.app = QApplication.instance() or QApplication([])

def test_mono_int16_input_becomes_stereo_master_pcm(self):
audio_format = QAudioFormat()
Expand Down Expand Up @@ -88,6 +88,56 @@ def test_missing_monitor_device_is_reported_once_per_error_state(self):
controller.deleteLater()
self.app.processEvents()

def test_monitor_gain_does_not_attenuate_broadcast_input(self):
class FakeBroadcast:
def __init__(self):
self.calls = []

def push_audio(self, source, data, gain=1.0):
self.calls.append((source, data, gain))

def remove_source(self, _source):
pass

class ReadDevice:
def __init__(self, data):
self.data = bytearray(data)

def bytesAvailable(self):
return len(self.data)

def read(self, length):
chunk = bytes(self.data[:length])
del self.data[:length]
return chunk

audio_format = QAudioFormat()
audio_format.setSampleRate(SAMPLE_RATE)
audio_format.setChannelCount(2)
audio_format.setSampleFormat(QAudioFormat.Int16)
frame = struct.pack("<" + "h" * (PCM_BYTES_PER_FRAME // 2),
*([12000] * (PCM_BYTES_PER_FRAME // 2)))
broadcast = FakeBroadcast()
controller = AudioInputController(broadcast)
controller.monitor_enabled = False
controller.monitor_gain = 0.05
controller.active["aux1"] = {
"io": ReadDevice(frame),
"format": audio_format,
"pending": bytearray(),
"raw_pending": bytearray(),
"input_frame_bytes": 4,
}

controller._pump()

self.assertEqual(len(broadcast.calls), 1)
self.assertEqual(broadcast.calls[0][0], "input:aux1")
self.assertEqual(broadcast.calls[0][2], 1.0)
controller.active.clear()
controller.deleteLater()
self.app.processEvents()


if __name__ == "__main__":
unittest.main()
12 changes: 12 additions & 0 deletions tests/test_autodj.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,18 @@ def test_filtering_by_tags_and_keywords(self):
"keyword_fields": ["title", "album"]})
self.assertEqual(["a"], [track["path"] for track in result])

def test_year_filter_excludes_tracks_with_unknown_year(self):
tracks = [
{"path": "known", "title": "Known", "year": "2008"},
{"path": "unknown", "title": "Unknown", "year": ""},
{"path": "invalid", "title": "Invalid", "year": "not-a-year"},
{"path": "newer", "title": "Newer", "year": "2015"},
]

result = filter_tracks(tracks, {"year_to": 2010})

self.assertEqual(["known"], [track["path"] for track in result])

def test_repeat_cooldowns_fall_back_without_stalling(self):
with tempfile.TemporaryDirectory() as folder:
first = Path(folder) / "first.mp3"; first.write_bytes(b"a")
Expand Down
25 changes: 25 additions & 0 deletions tests/test_autodj_panel_regressions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import unittest

from PySide6.QtWidgets import QApplication

from radiostudio.ui.autodj_panel import ProgramDialog


class AutoDJPanelRegressionTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = QApplication.instance() or QApplication([])

def test_new_program_defaults_to_all_weekdays(self):
dialog = ProgramDialog([])
try:
self.assertEqual(len(dialog.days), 7)
self.assertTrue(all(check.isChecked() for check in dialog.days))
finally:
dialog.close()
dialog.deleteLater()
self.app.processEvents()


if __name__ == "__main__":
unittest.main()
77 changes: 77 additions & 0 deletions tests/test_playlist_regressions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import unittest

from radiostudio.ui.playlist import PlaylistMixin, m3u_entries


class _SelectionModel:
def __init__(self):
self.selected = []

def select(self, index, flags):
self.selected.append((index, flags))


class _Model:
@staticmethod
def index(row, column):
return row, column


class _Playlist:
def __init__(self):
self.selection = _SelectionModel()
self.table_model = _Model()
self.cleared = False

def clearSelection(self):
self.cleared = True

def selectionModel(self):
return self.selection

def model(self):
return self.table_model


class _PlaylistHarness(PlaylistMixin):
def __init__(self):
self.tracks = ["a.mp3", "b.mp3", "c.mp3", "d.mp3"]
self.track_sources = ["manual", "autodj", "schedule", "manual"]
self.current_index = 2
self.playlist = _Playlist()
self.saved = False
self.refreshed = False

def cancel_pending_transition(self):
pass

def refresh_playlist(self):
self.refreshed = True

def save_state(self):
self.saved = True


class PlaylistRegressionTests(unittest.TestCase):
def test_reorder_preserves_current_track_and_its_source(self):
harness = _PlaylistHarness()

PlaylistMixin.reorder_tracks(harness, [2], 1)

self.assertEqual(harness.tracks, ["a.mp3", "c.mp3", "b.mp3", "d.mp3"])
self.assertEqual(harness.track_sources,
["manual", "schedule", "autodj", "manual"])
self.assertEqual(harness.current_index, 1)
self.assertTrue(harness.refreshed)
self.assertTrue(harness.saved)
self.assertTrue(harness.playlist.cleared)

def test_m3u_entries_strip_whitespace_and_ignore_indented_comments(self):
self.assertEqual(
m3u_entries([" #EXTM3U ", " song one.mp3 ", "", "\t#EXTINF:10,x", "sub/song two.mp3\t"]),
["song one.mp3", "sub/song two.mp3"],
)


if __name__ == "__main__":
unittest.main()
Loading