v0.79.3: editing the playing song's tags or art no longer glitches playback
This commit is contained in:
@@ -1239,6 +1239,15 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
|
||||
the file to the desktop trash via `trash.py` — never `unlink`, so it stays
|
||||
recoverable. Nothing else may move, rewrite or remove music files. The library
|
||||
JSON is the source of truth for everything else.
|
||||
**The playing song's tags are never saved in place** (Round 111):
|
||||
mutagen shifts the audio inside the file when a tag outgrows its
|
||||
padding, and the decoder, reading by offset, glitched (~1.3 M samples
|
||||
wrong in a 20 s test). `tagging.in_use` (MainWindow: the player's
|
||||
current track) names those files; `tagging._editable` saves them to a
|
||||
copy beside them and `os.replace`s it over, so the open file keeps the
|
||||
old inode, untouched (0 samples wrong). Everything else stays in place —
|
||||
a full copy per file would make a big batch edit cost gigabytes. No room
|
||||
for the copy falls back to in place.
|
||||
- **Versioning & self-update:** `__version__` in `lintunes/__init__.py` is
|
||||
the single source of truth (`setup.py` regex-reads it, never imports the
|
||||
package). Claude bumps minor for feature rounds and patch for fix-only
|
||||
|
||||
@@ -12,7 +12,7 @@ from PyQt6.QtCore import QRect, Qt, QEvent, QObject, QTimer, pyqtSignal
|
||||
from PyQt6.QtGui import QAction, QKeySequence
|
||||
|
||||
from lintunes import (bpm_detect, device_sync, loudness, music_folder, shazam,
|
||||
theme, url_import)
|
||||
tagging, theme, url_import)
|
||||
from lintunes.andtunes import layout as andtunes_layout
|
||||
from lintunes.andtunes import install as andtunes_install
|
||||
from lintunes.andtunes import sync as andtunes_sync
|
||||
@@ -120,6 +120,9 @@ class MainWindow(QMainWindow):
|
||||
# Volume normalization measures each song with ffmpeg as it comes up;
|
||||
# nothing is measured while it's off (the default, and in tests).
|
||||
self.player.loudness = loudness.LoudnessAnalyzer(parent=self)
|
||||
# A tag or art save on the playing song mustn't shift the audio
|
||||
# under the decoder (tagging._editable).
|
||||
tagging.in_use = self._files_in_use
|
||||
# Owns the cast session, if any. Built before the transport bar, which
|
||||
# takes it to drive the little cast indicator under the volume slider.
|
||||
self._cast = CastController(self.player, self)
|
||||
@@ -3053,6 +3056,11 @@ class MainWindow(QMainWindow):
|
||||
ctx=ctx, shuffle=self.player.is_shuffle(),
|
||||
track_id=None if isinstance(key, str) else key))
|
||||
|
||||
def _files_in_use(self):
|
||||
track = getattr(self.player, "current_track", None)
|
||||
location = getattr(track, "location", None)
|
||||
return (location,) if location else ()
|
||||
|
||||
def _on_track_meta_updated(self, track_id: int):
|
||||
current = self.player.current_track
|
||||
if current is not None and current.track_id == track_id:
|
||||
|
||||
+65
-2
@@ -5,6 +5,11 @@ name, artist, album_artist, album, genre, composer, grouping, comments,
|
||||
year (int), track_number, track_count, disc_number, disc_count,
|
||||
compilation (bool), total_time (ms, read-only), bit_rate, sample_rate, size.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
import mutagen
|
||||
@@ -16,6 +21,53 @@ from mutagen.flac import FLAC
|
||||
|
||||
from lintunes.perf import timed
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# The files something is reading right now — the playing song. MainWindow
|
||||
# sets it. mutagen saves in place, and when a tag outgrows its padding it
|
||||
# shifts all the audio after it inside the same file, so a decoder reading
|
||||
# by offset plays garbage for a moment (Round 111: ~1.3 M samples wrong in
|
||||
# a 20 s test). Those files are edited as a copy beside them, renamed over:
|
||||
# the open file keeps the old inode, untouched, until playback lets go.
|
||||
in_use = lambda: () # noqa: E731
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _editable(path: str):
|
||||
"""Where to save ``path``'s new tags: the file itself, or — while it is
|
||||
in use — a copy that replaces it atomically once saved. A copy that
|
||||
can't be made (no room, say) falls back to saving in place."""
|
||||
busy = {os.path.abspath(p) for p in in_use() if p}
|
||||
if os.path.abspath(path) not in busy:
|
||||
yield path
|
||||
return
|
||||
folder, name = os.path.split(path)
|
||||
try:
|
||||
fd, work = tempfile.mkstemp(dir=folder or ".", prefix=".lintunes-tag-",
|
||||
suffix=os.path.splitext(name)[1])
|
||||
os.close(fd)
|
||||
shutil.copyfile(path, work)
|
||||
shutil.copymode(path, work)
|
||||
except OSError as e:
|
||||
log.warning("saving %s in place, no room for a copy: %s", path, e)
|
||||
try:
|
||||
os.unlink(work)
|
||||
except (OSError, UnboundLocalError):
|
||||
pass
|
||||
yield path
|
||||
return
|
||||
try:
|
||||
yield work
|
||||
with open(work, "rb+") as f:
|
||||
os.fsync(f.fileno()) # all there before it takes the name
|
||||
os.replace(work, path)
|
||||
except BaseException:
|
||||
try:
|
||||
os.unlink(work)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
# EasyID3 has no 'comment' key by default; COMM frames need explicit handling.
|
||||
def _comm_get(id3, _key):
|
||||
@@ -148,7 +200,12 @@ def write_tags(path: str | Path, fields: dict):
|
||||
One parse and ONE save per call: grouping/compilation/bpm are covered by
|
||||
the Easy keys registered above, so no second raw-tag pass is needed."""
|
||||
path = str(path)
|
||||
audio = mutagen.File(path, easy=True)
|
||||
with _editable(path) as work:
|
||||
_write_tags(work, fields, path)
|
||||
|
||||
|
||||
def _write_tags(work: str, fields: dict, path: str):
|
||||
audio = mutagen.File(work, easy=True)
|
||||
if audio is None:
|
||||
raise ValueError(f"Unsupported audio file: {path}")
|
||||
if audio.tags is None:
|
||||
@@ -217,11 +274,17 @@ def _kind_for(audio) -> str:
|
||||
|
||||
def write_artwork(path: str | Path, image_bytes: bytes, mime: str = "image/jpeg"):
|
||||
"""Replace the file's embedded cover art (front cover) with image_bytes."""
|
||||
path = str(path)
|
||||
with _editable(path) as work:
|
||||
_write_artwork(work, image_bytes, mime, path)
|
||||
|
||||
|
||||
def _write_artwork(work: str, image_bytes: bytes, mime: str, path: str):
|
||||
from mutagen.id3 import APIC
|
||||
from mutagen.mp4 import MP4Cover
|
||||
from mutagen.flac import Picture
|
||||
|
||||
audio = mutagen.File(str(path))
|
||||
audio = mutagen.File(work)
|
||||
if audio is None:
|
||||
raise ValueError(f"Unsupported audio file: {path}")
|
||||
if isinstance(audio, MP4):
|
||||
|
||||
@@ -26,6 +26,14 @@ def _no_real_device(monkeypatch):
|
||||
monkeypatch.setattr(device_sync, "find_device", lambda: None)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_file_in_use(monkeypatch):
|
||||
"""A MainWindow points tagging at its player (Round 111); one a test left
|
||||
behind mustn't decide how a later test's tag writes are saved."""
|
||||
from lintunes import tagging
|
||||
monkeypatch.setattr(tagging, "in_use", lambda: ())
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_dj_sound(monkeypatch):
|
||||
"""DJ mode's sink never opens in a test: the mixer would play the decks
|
||||
|
||||
+88
-43
@@ -1,53 +1,98 @@
|
||||
"""Round 111: the visualizer page's sliders are tall and jump where clicked;
|
||||
the radial dot size reads as a share of the spacing between dots."""
|
||||
from unittest.mock import MagicMock
|
||||
"""Round 111: a tag or art save on the playing song doesn't glitch playback.
|
||||
|
||||
from PyQt6.QtCore import QPoint, Qt
|
||||
from PyQt6.QtTest import QTest
|
||||
mutagen saves in place, shifting the audio inside the file when a tag
|
||||
outgrows its padding; a decoder holding the file open then reads from the
|
||||
wrong offsets. The playing file is instead edited as a copy and renamed
|
||||
over it, so what's already open stays byte for byte what it was."""
|
||||
import os
|
||||
|
||||
from lintunes.gui import preferences_dialog as pd
|
||||
from lintunes.gui.preferences_dialog import PreferencesDialog
|
||||
from lintunes.gui.transport import ClickJumpSlider
|
||||
from lintunes.preferences import Preferences
|
||||
import pytest
|
||||
|
||||
from lintunes import tagging
|
||||
|
||||
|
||||
def _dialog(tmp_path):
|
||||
dialog = PreferencesDialog(Preferences(tmp_path), MagicMock())
|
||||
dialog.resize(900, 700)
|
||||
dialog.pages_list.setCurrentRow(2)
|
||||
dialog._viz_radios["radial"].setChecked(True)
|
||||
dialog.show()
|
||||
QTest.qWait(20)
|
||||
return dialog
|
||||
def _big_art():
|
||||
# Far more than any padding: the in-place save would move the audio.
|
||||
return b"\xff\xd8\xff\xe0" + os.urandom(300_000)
|
||||
|
||||
|
||||
def test_visualizer_sliders_are_tall_click_jump_sliders(qapp, tmp_path):
|
||||
dialog = _dialog(tmp_path)
|
||||
sliders = [dialog._radial_dot_slider, dialog._fade_slider,
|
||||
dialog._sync_sliders["radial"], dialog._dot_slider]
|
||||
for slider in sliders:
|
||||
assert isinstance(slider, ClickJumpSlider)
|
||||
assert slider.property("tall")
|
||||
dialog.close()
|
||||
def _strays(path):
|
||||
return [p for p in path.parent.iterdir() if p.name.startswith(".lintunes-tag-")]
|
||||
|
||||
|
||||
def test_a_click_puts_the_handle_where_it_lands(qapp, tmp_path):
|
||||
dialog = _dialog(tmp_path)
|
||||
slider = dialog._radial_dot_slider
|
||||
y = slider.height() // 2
|
||||
QTest.mouseClick(slider, Qt.MouseButton.LeftButton, pos=QPoint(0, y))
|
||||
assert slider.value() == slider.minimum()
|
||||
QTest.mouseClick(slider, Qt.MouseButton.LeftButton,
|
||||
pos=QPoint(slider.width() - 1, y))
|
||||
assert slider.value() == slider.maximum()
|
||||
QTest.mouseClick(slider, Qt.MouseButton.LeftButton,
|
||||
pos=QPoint(slider.width() // 2, y))
|
||||
middle = (slider.minimum() + slider.maximum()) / 2
|
||||
assert abs(slider.value() - middle) <= 2 # not one page step from the end
|
||||
dialog.close()
|
||||
@pytest.mark.parametrize("fixture", ["mp3_file", "flac_file", "m4a_file"])
|
||||
def test_the_playing_file_is_replaced_not_rewritten(request, monkeypatch, fixture):
|
||||
path = request.getfixturevalue(fixture)
|
||||
original = path.read_bytes()
|
||||
monkeypatch.setattr(tagging, "in_use", lambda: (str(path),))
|
||||
with open(path, "rb") as playing: # the decoder's open file
|
||||
inode = os.fstat(playing.fileno()).st_ino
|
||||
tagging.write_artwork(path, _big_art())
|
||||
tagging.write_tags(path, {"name": "New Name", "artist": "Someone"})
|
||||
assert playing.read() == original # nothing moved under it
|
||||
assert os.stat(path).st_ino != inode
|
||||
assert tagging.read_tags(path)["name"] == "New Name"
|
||||
assert tagging.read_embedded_artwork(path) is not None
|
||||
assert _strays(path) == []
|
||||
|
||||
|
||||
def test_dot_size_is_a_share_of_the_spacing():
|
||||
# The automatic size (1×) is 70% of the gap; dots touch at 100%.
|
||||
assert pd._dot_text(1.0) == "70%"
|
||||
assert pd._dot_text(1 / 0.7) == "100%"
|
||||
def test_mode_is_kept(mp3_file, monkeypatch):
|
||||
os.chmod(mp3_file, 0o640)
|
||||
monkeypatch.setattr(tagging, "in_use", lambda: (str(mp3_file),))
|
||||
tagging.write_tags(mp3_file, {"name": "x"})
|
||||
assert os.stat(mp3_file).st_mode & 0o777 == 0o640
|
||||
|
||||
|
||||
def test_other_files_are_still_saved_in_place(mp3_file):
|
||||
inode = os.stat(mp3_file).st_ino
|
||||
tagging.write_tags(mp3_file, {"name": "In Place"})
|
||||
assert os.stat(mp3_file).st_ino == inode
|
||||
assert tagging.read_tags(mp3_file)["name"] == "In Place"
|
||||
|
||||
|
||||
def test_a_failed_save_leaves_the_file_and_no_copy(mp3_file, monkeypatch):
|
||||
original = mp3_file.read_bytes()
|
||||
monkeypatch.setattr(tagging, "in_use", lambda: (str(mp3_file),))
|
||||
real = tagging._write_tags
|
||||
|
||||
def broken(work, fields, path):
|
||||
real(work, fields, path)
|
||||
raise RuntimeError("disk on fire")
|
||||
|
||||
monkeypatch.setattr(tagging, "_write_tags", broken)
|
||||
with pytest.raises(RuntimeError):
|
||||
tagging.write_tags(mp3_file, {"name": "never"})
|
||||
assert mp3_file.read_bytes() == original
|
||||
assert _strays(mp3_file) == []
|
||||
|
||||
|
||||
def test_no_room_for_a_copy_saves_in_place(mp3_file, monkeypatch):
|
||||
monkeypatch.setattr(tagging, "in_use", lambda: (str(mp3_file),))
|
||||
|
||||
def full(*_a, **_k):
|
||||
raise OSError(28, "No space left on device")
|
||||
|
||||
monkeypatch.setattr(tagging.shutil, "copyfile", full)
|
||||
tagging.write_tags(mp3_file, {"name": "Squeezed"})
|
||||
assert tagging.read_tags(mp3_file)["name"] == "Squeezed"
|
||||
assert _strays(mp3_file) == []
|
||||
|
||||
|
||||
def test_the_window_names_the_playing_song(qapp, tmp_path):
|
||||
from lintunes.gui.main_window import MainWindow
|
||||
from lintunes.library_manager import LibraryManager
|
||||
from lintunes.models.library import Library
|
||||
from lintunes.models.track import Track
|
||||
from lintunes.preferences import Preferences
|
||||
library = Library()
|
||||
library.tracks[1] = Track(track_id=1, name="Song", location="/music/song.mp3")
|
||||
window = MainWindow(LibraryManager(library, tmp_path / "data"),
|
||||
Preferences(tmp_path / "data"))
|
||||
try:
|
||||
assert tagging.in_use == window._files_in_use
|
||||
assert tagging.in_use() == ()
|
||||
window.player._current_track = library.tracks[1]
|
||||
assert tagging.in_use() == ("/music/song.mp3",)
|
||||
finally:
|
||||
window.player._current_track = None
|
||||
window.close()
|
||||
|
||||
Reference in New Issue
Block a user