v0.76.0: Convert to MP3 for songs already in the library, and for Cassette arrivals
- right-click › Convert to MP3…: lossless songs become MP3s at a chosen bitrate; same tracks (plays, ratings, playlists kept), originals to the trash, one undo step brings them back; Cancel changes nothing - Preferences › Importing › Convert songs from Cassette friends too - the bitrate list is just the numbers - conversions stage in ~/.cache, not /tmp
This commit is contained in:
+214
-116
@@ -1,123 +1,221 @@
|
||||
"""Round 107: opening DJ mode with both decks empty doesn't stop the song —
|
||||
Deck A loads it and takes over without a gap, and closing DJ mode goes back
|
||||
to where the main player left off."""
|
||||
"""Round 107: no quality labels on the bitrates, "Convert songs from Cassette
|
||||
friends too", and right-click › Convert to MP3… on songs already in the
|
||||
library."""
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from lintunes.dj import analysis, stems
|
||||
from lintunes.dj.audio import RATE, Source
|
||||
from lintunes.player import Player
|
||||
from tests.test_round93 import _tone
|
||||
from lintunes import tagging
|
||||
from lintunes.importers import lossless
|
||||
from lintunes.library_manager import LibraryManager
|
||||
from lintunes.models import Library, Playlist, Track
|
||||
from lintunes.preferences import Preferences
|
||||
from tests.test_round106 import _digest, _tagged_flac, _wait
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _staging_in_tmp(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache"))
|
||||
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def window(qapp, tmp_path, monkeypatch):
|
||||
from lintunes.gui import dj_shelf
|
||||
def fake_trash(tmp_path, monkeypatch):
|
||||
"""send/restore that never reach the real desktop trash."""
|
||||
bin_ = tmp_path / "trash-bin"
|
||||
bin_.mkdir()
|
||||
|
||||
def send(path):
|
||||
path = Path(path)
|
||||
if not path.exists():
|
||||
from lintunes.trash import TrashError
|
||||
raise TrashError(f"{path} doesn't exist")
|
||||
dest = bin_ / f"{len(list(bin_.iterdir()))}-{path.name}"
|
||||
shutil.move(str(path), dest)
|
||||
return dest
|
||||
|
||||
def restore(trashed, original):
|
||||
Path(original).parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.move(str(trashed), str(original))
|
||||
monkeypatch.setattr("lintunes.library_manager.trash.send_to_trash", send)
|
||||
monkeypatch.setattr("lintunes.library_manager.trash.restore_from_trash",
|
||||
restore)
|
||||
return bin_
|
||||
|
||||
|
||||
def _library_with_flacs(tmp_path, names):
|
||||
music = tmp_path / "media" / "Music" / "Nissa" / "Big Files"
|
||||
music.mkdir(parents=True)
|
||||
library = Library(music_folder=str(tmp_path / "media"))
|
||||
for tid, name in enumerate(names, start=1):
|
||||
path = _tagged_flac(music / f"{tid:02d} {name}.flac", name, seconds=2)
|
||||
fields = tagging.read_tags(path)
|
||||
library.tracks[tid] = Track(
|
||||
track_id=tid, name=name, artist="Nissa", album="Big Files",
|
||||
location=str(path), kind=fields["kind"], play_count=7 * tid,
|
||||
rating=80, total_time=fields["total_time"], size=fields["size"])
|
||||
library.playlists["P"] = Playlist(name="Mix", persistent_id="P",
|
||||
track_ids=list(library.tracks))
|
||||
return LibraryManager(library, tmp_path / "data")
|
||||
|
||||
|
||||
# ---- the setting ----
|
||||
|
||||
def test_bitrates_are_just_numbers(qapp, tmp_path):
|
||||
from unittest.mock import MagicMock
|
||||
from lintunes.gui.preferences_dialog import PreferencesDialog
|
||||
dialog = PreferencesDialog(Preferences(tmp_path / "data"), MagicMock())
|
||||
labels = [dialog._compress_kbps.itemText(i)
|
||||
for i in range(dialog._compress_kbps.count())]
|
||||
assert labels == ["320 kbps", "256 kbps", "192 kbps", "160 kbps", "128 kbps"]
|
||||
|
||||
|
||||
def test_cassette_setting_needs_the_main_one(qapp, tmp_path):
|
||||
from unittest.mock import MagicMock
|
||||
from lintunes.gui.preferences_dialog import PreferencesDialog
|
||||
prefs = Preferences(tmp_path / "data")
|
||||
assert lossless.cassette_kbps(prefs) is None
|
||||
dialog = PreferencesDialog(prefs, MagicMock())
|
||||
assert not dialog._compress_cassette.isEnabled()
|
||||
dialog._compress_check.setChecked(True)
|
||||
assert dialog._compress_cassette.isEnabled()
|
||||
assert lossless.cassette_kbps(prefs) is None # off by default
|
||||
dialog._compress_cassette.setChecked(True)
|
||||
assert lossless.cassette_kbps(prefs) == 256
|
||||
dialog._compress_check.setChecked(False)
|
||||
assert lossless.cassette_kbps(prefs) is None
|
||||
assert not dialog._compress_cassette.isEnabled()
|
||||
|
||||
|
||||
def test_a_lossless_cassette_arrival_is_converted(tmp_path, mp3_file):
|
||||
from lintunes.cassette import delivery
|
||||
outbox = tmp_path / "outbox"
|
||||
outbox.mkdir()
|
||||
flac = _tagged_flac(outbox / "7 ~ Huge.flac", "Huge")
|
||||
sent = _digest(flac)
|
||||
mp3 = shutil.copy(mp3_file, outbox / "8 ~ Small.mp3")
|
||||
plan = delivery.ReceivePlan(token="t", arrivals=[
|
||||
delivery.Arrival(7, flac, True, False),
|
||||
delivery.Arrival(8, Path(mp3), True, False)])
|
||||
music = tmp_path / "Music"
|
||||
result = delivery.run_plans([], [plan], music, compress_kbps=160)
|
||||
assert result.errors == []
|
||||
huge, small = result.staged
|
||||
assert huge.dest.name == "Huge.mp3" and huge.dest.parent.parent.name == "Nissa"
|
||||
assert huge.fields["kind"] == "MPEG audio file"
|
||||
assert 150 <= huge.fields["bit_rate"] <= 170
|
||||
assert small.dest.name == "Small.mp3"
|
||||
assert _digest(flac) == sent # the friend's copy is only read
|
||||
assert not any(lossless.staging_root().iterdir())
|
||||
# Off: as sent.
|
||||
result = delivery.run_plans([], [plan], tmp_path / "Music2")
|
||||
assert result.staged[0].dest.suffix == ".flac"
|
||||
|
||||
|
||||
def test_the_coordinator_reads_the_setting_each_pass(qapp, tmp_path):
|
||||
from unittest.mock import MagicMock
|
||||
from lintunes.gui.cassette_delivery import DeliveryCoordinator
|
||||
kbps = [None]
|
||||
service = MagicMock()
|
||||
coordinator = DeliveryCoordinator(service, MagicMock(),
|
||||
compress_kbps=lambda: kbps[0])
|
||||
coordinator._worker = MagicMock()
|
||||
coordinator._worker.busy.return_value = False
|
||||
from lintunes.cassette import delivery
|
||||
plan = delivery.ReceivePlan(token="t", arrivals=[MagicMock()])
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setattr(delivery, "plan_send", lambda *a: delivery.SendPlan(
|
||||
token="t", outbox=tmp_path))
|
||||
mp.setattr(delivery, "plan_receive", lambda *a, **k: plan)
|
||||
service.state.return_value.friends = {"t": MagicMock()}
|
||||
service.root = tmp_path
|
||||
kbps[0] = 192
|
||||
coordinator.run()
|
||||
assert coordinator._worker.start.call_args.args[3] == 192
|
||||
|
||||
|
||||
# ---- Convert to MP3 on library songs ----
|
||||
|
||||
def test_only_lossless_songs_are_convertible(tmp_path, mp3_file, m4a_file):
|
||||
from lintunes.gui.compress_import import convertible
|
||||
flac = _tagged_flac(tmp_path / "a.flac", "A")
|
||||
tracks = [Track(track_id=i, location=str(p)) for i, p in
|
||||
enumerate([flac, mp3_file, m4a_file, tmp_path / "gone.flac"])]
|
||||
assert [t.track_id for t in convertible(tracks)] == [0]
|
||||
|
||||
|
||||
def test_convert_swaps_files_keeps_the_track_and_undoes(qapp, tmp_path, fake_trash):
|
||||
from lintunes.gui.compress_import import ConvertLibrary
|
||||
manager = _library_with_flacs(tmp_path, ["Alpha", "Bravo"])
|
||||
originals = {tid: (Path(t.location), _digest(Path(t.location)))
|
||||
for tid, t in manager.library.tracks.items()}
|
||||
batch = ConvertLibrary(manager, list(manager.library.tracks.values()), 128)
|
||||
assert batch.window is not None
|
||||
over = []
|
||||
batch.over.connect(over.append)
|
||||
batch.start()
|
||||
_wait(qapp, batch)
|
||||
|
||||
assert over == ["Converted 2 songs to 128 kbps MP3"]
|
||||
for tid, (flac, digest) in originals.items():
|
||||
track = manager.library.tracks[tid]
|
||||
assert track.location == str(flac.with_suffix(".mp3"))
|
||||
assert Path(track.location).is_file() and not flac.exists()
|
||||
assert track.kind == "MPEG audio file" and track.bit_rate <= 136
|
||||
assert track.play_count == 7 * tid and track.rating == 80
|
||||
assert tagging.read_tags(track.location)["name"] == track.name
|
||||
assert manager.library.playlists["P"].track_ids == [1, 2]
|
||||
assert len(list(fake_trash.iterdir())) == 2
|
||||
assert not any(lossless.staging_root().iterdir())
|
||||
|
||||
manager.undo_stack.undo() # one step for the batch
|
||||
for tid, (flac, digest) in originals.items():
|
||||
track = manager.library.tracks[tid]
|
||||
assert track.location == str(flac) and _digest(flac) == digest
|
||||
assert track.kind == "FLAC audio file"
|
||||
assert not flac.with_suffix(".mp3").exists()
|
||||
manager.undo_stack.redo()
|
||||
assert all(t.location.endswith(".mp3") and Path(t.location).is_file()
|
||||
for t in manager.library.tracks.values())
|
||||
|
||||
|
||||
def test_cancel_changes_nothing(qapp, tmp_path, fake_trash):
|
||||
from lintunes.gui.compress_import import ConvertLibrary
|
||||
manager = _library_with_flacs(tmp_path, ["Alpha", "Bravo"])
|
||||
before = {t: tr.location for t, tr in manager.library.tracks.items()}
|
||||
batch = ConvertLibrary(manager, list(manager.library.tracks.values()), 128)
|
||||
over = []
|
||||
batch.over.connect(over.append)
|
||||
batch.start()
|
||||
batch.request_cancel()
|
||||
_wait(qapp, batch)
|
||||
assert {t: tr.location for t, tr in manager.library.tracks.items()} == before
|
||||
assert all(Path(p).exists() for p in before.values())
|
||||
assert list(fake_trash.iterdir()) == []
|
||||
assert not manager.undo_stack.can_undo()
|
||||
assert over == ["Convert to MP3 cancelled — nothing was changed"]
|
||||
assert not any(lossless.staging_root().iterdir())
|
||||
|
||||
|
||||
def test_window_right_click_flow(qapp, tmp_path, fake_trash, monkeypatch):
|
||||
from lintunes.gui.main_window import MainWindow
|
||||
from lintunes.library_manager import LibraryManager
|
||||
from lintunes.models import Track
|
||||
from lintunes.models.library import Library
|
||||
from lintunes.preferences import Preferences
|
||||
monkeypatch.setattr("lintunes.gui.main_window.load_config", lambda: {})
|
||||
monkeypatch.setattr("lintunes.gui.main_window.save_config", lambda c: None)
|
||||
monkeypatch.setattr(dj_shelf.DeckLoader, "request", lambda *a, **k: None)
|
||||
monkeypatch.setattr(stems, "available", lambda: False)
|
||||
monkeypatch.setattr(dj_shelf.tagging, "read_embedded_artwork", lambda p: None)
|
||||
library = Library()
|
||||
for tid in (1, 2):
|
||||
library.tracks[tid] = Track(track_id=tid, name=f"Song {tid}", artist="Test",
|
||||
location=f"/x{tid}.mp3", bpm=120)
|
||||
made = MainWindow(LibraryManager(library, tmp_path), Preferences(tmp_path))
|
||||
# A main player "playing" song 1, 42 s in.
|
||||
state = {"track": library.tracks[1], "playing": True, "ms": 42_000, "seeks": []}
|
||||
monkeypatch.setattr(Player, "current_track", property(lambda self: state["track"]))
|
||||
player = made.player
|
||||
player.is_playing = lambda: state["playing"]
|
||||
player.position_ms = lambda: state["ms"]
|
||||
player.pause = lambda: state.update(playing=False)
|
||||
player.play = lambda: state.update(playing=True)
|
||||
player.seek = lambda ms: state["seeks"].append(ms)
|
||||
made.state = state
|
||||
made.library = library
|
||||
yield made
|
||||
made.close()
|
||||
|
||||
|
||||
def _finish_loading(window, track):
|
||||
from lintunes.dj.loader import Loaded
|
||||
samples = _tone(seconds=60.0)
|
||||
window._dj._on_loader_result("A", Loaded(
|
||||
track_id=track.track_id, source=Source(samples),
|
||||
peaks=analysis.peaks(samples, RATE), bpm=120.0, offset=0.0, detected=False))
|
||||
|
||||
|
||||
def _close(window, qapp):
|
||||
window.set_dj_mode(False)
|
||||
window._dj_anim.stop()
|
||||
window._dj_closed()
|
||||
|
||||
|
||||
def test_empty_decks_take_the_playing_song_over(window, qapp):
|
||||
state = window.state
|
||||
window.set_dj_mode(True)
|
||||
shelf = window._dj
|
||||
a = shelf.views[0]
|
||||
assert state["playing"], "the song keeps playing while Deck A loads"
|
||||
assert window.player.suspended
|
||||
assert a.track is state["track"]
|
||||
assert shelf.crossfader.value() == 0 # Deck A alone
|
||||
_finish_loading(window, state["track"])
|
||||
assert a.deck.playing
|
||||
assert a.deck.position / RATE == pytest.approx(42.0 + shelf.latency_ms() / 1000, abs=0.01)
|
||||
qapp.processEvents() # the latency passes
|
||||
assert not state["playing"]
|
||||
assert window._dj_pin == (1, 42_000, True)
|
||||
_close(window, qapp)
|
||||
assert state["seeks"] == [42_000] and state["playing"]
|
||||
assert window._dj_pin is None
|
||||
|
||||
|
||||
def test_a_paused_song_is_cued_and_stays_paused(window, qapp):
|
||||
state = window.state
|
||||
state["playing"] = False
|
||||
window.set_dj_mode(True)
|
||||
a = window._dj.views[0]
|
||||
_finish_loading(window, state["track"])
|
||||
assert not a.deck.playing
|
||||
assert a.deck.position / RATE == pytest.approx(42.0, abs=0.01)
|
||||
_close(window, qapp)
|
||||
assert not state["playing"]
|
||||
|
||||
|
||||
def test_closing_before_the_deck_loads_leaves_the_song_playing(window, qapp):
|
||||
state = window.state
|
||||
window.set_dj_mode(True)
|
||||
_close(window, qapp)
|
||||
assert state["playing"] and not window.player.suspended
|
||||
assert window._dj.views[0].handoff is None
|
||||
assert window._dj_pin is None
|
||||
|
||||
|
||||
def test_a_loaded_deck_means_the_song_just_stops(window, qapp):
|
||||
state = window.state
|
||||
window.set_dj_mode(True)
|
||||
_finish_loading(window, state["track"])
|
||||
qapp.processEvents()
|
||||
_close(window, qapp)
|
||||
window._dj.load(window._dj.views[1], window.library.tracks[2])
|
||||
window._dj.views[0].track = None # only Deck B holds something now
|
||||
state["playing"] = True
|
||||
window.set_dj_mode(True)
|
||||
assert not state["playing"]
|
||||
assert window._dj.views[0].track is None # nothing loaded for it
|
||||
_close(window, qapp)
|
||||
assert not state["playing"]
|
||||
|
||||
|
||||
def test_a_failed_load_stops_the_song(window, qapp):
|
||||
state = window.state
|
||||
window.set_dj_mode(True)
|
||||
window._dj._on_loader_failed("A", 1, "no decoder")
|
||||
assert not state["playing"]
|
||||
_close(window, qapp)
|
||||
assert not state["playing"]
|
||||
manager = _library_with_flacs(tmp_path, ["Alpha"])
|
||||
window = MainWindow(manager, Preferences(tmp_path / "data"))
|
||||
asked = []
|
||||
monkeypatch.setattr(window, "_ask_convert_kbps",
|
||||
lambda tracks: asked.append(len(tracks)) or 192)
|
||||
try:
|
||||
window._convert_to_mp3([1])
|
||||
assert asked == [1]
|
||||
batch = window._compress
|
||||
assert batch is not None and batch.window is None # one song
|
||||
assert window._sync_label.isVisibleTo(window)
|
||||
_wait(qapp, batch)
|
||||
assert window._compress is None
|
||||
assert manager.library.tracks[1].location.endswith(".mp3")
|
||||
# Nothing lossless left: says so, starts nothing.
|
||||
window._convert_to_mp3([1])
|
||||
assert window._compress is None and asked == [1]
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
Reference in New Issue
Block a user