v0.79.3: editing the playing song's tags or art no longer glitches playback

This commit is contained in:
2026-10-25 20:09:55 -07:00
parent b8f2325f0b
commit eba27e7b8c
5 changed files with 179 additions and 46 deletions
+9
View File
@@ -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 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 recoverable. Nothing else may move, rewrite or remove music files. The library
JSON is the source of truth for everything else. 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 - **Versioning & self-update:** `__version__` in `lintunes/__init__.py` is
the single source of truth (`setup.py` regex-reads it, never imports the 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 package). Claude bumps minor for feature rounds and patch for fix-only
+9 -1
View File
@@ -12,7 +12,7 @@ from PyQt6.QtCore import QRect, Qt, QEvent, QObject, QTimer, pyqtSignal
from PyQt6.QtGui import QAction, QKeySequence from PyQt6.QtGui import QAction, QKeySequence
from lintunes import (bpm_detect, device_sync, loudness, music_folder, shazam, 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 layout as andtunes_layout
from lintunes.andtunes import install as andtunes_install from lintunes.andtunes import install as andtunes_install
from lintunes.andtunes import sync as andtunes_sync 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; # Volume normalization measures each song with ffmpeg as it comes up;
# nothing is measured while it's off (the default, and in tests). # nothing is measured while it's off (the default, and in tests).
self.player.loudness = loudness.LoudnessAnalyzer(parent=self) 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 # Owns the cast session, if any. Built before the transport bar, which
# takes it to drive the little cast indicator under the volume slider. # takes it to drive the little cast indicator under the volume slider.
self._cast = CastController(self.player, self) self._cast = CastController(self.player, self)
@@ -3053,6 +3056,11 @@ class MainWindow(QMainWindow):
ctx=ctx, shuffle=self.player.is_shuffle(), ctx=ctx, shuffle=self.player.is_shuffle(),
track_id=None if isinstance(key, str) else key)) 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): def _on_track_meta_updated(self, track_id: int):
current = self.player.current_track current = self.player.current_track
if current is not None and current.track_id == track_id: if current is not None and current.track_id == track_id:
+65 -2
View File
@@ -5,6 +5,11 @@ name, artist, album_artist, album, genre, composer, grouping, comments,
year (int), track_number, track_count, disc_number, disc_count, year (int), track_number, track_count, disc_number, disc_count,
compilation (bool), total_time (ms, read-only), bit_rate, sample_rate, size. 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 from pathlib import Path
import mutagen import mutagen
@@ -16,6 +21,53 @@ from mutagen.flac import FLAC
from lintunes.perf import timed 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. # EasyID3 has no 'comment' key by default; COMM frames need explicit handling.
def _comm_get(id3, _key): 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 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.""" the Easy keys registered above, so no second raw-tag pass is needed."""
path = str(path) 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: if audio is None:
raise ValueError(f"Unsupported audio file: {path}") raise ValueError(f"Unsupported audio file: {path}")
if audio.tags is None: 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"): 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.""" """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.id3 import APIC
from mutagen.mp4 import MP4Cover from mutagen.mp4 import MP4Cover
from mutagen.flac import Picture from mutagen.flac import Picture
audio = mutagen.File(str(path)) audio = mutagen.File(work)
if audio is None: if audio is None:
raise ValueError(f"Unsupported audio file: {path}") raise ValueError(f"Unsupported audio file: {path}")
if isinstance(audio, MP4): if isinstance(audio, MP4):
+8
View File
@@ -26,6 +26,14 @@ def _no_real_device(monkeypatch):
monkeypatch.setattr(device_sync, "find_device", lambda: None) 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) @pytest.fixture(autouse=True)
def _no_dj_sound(monkeypatch): def _no_dj_sound(monkeypatch):
"""DJ mode's sink never opens in a test: the mixer would play the decks """DJ mode's sink never opens in a test: the mixer would play the decks
+95 -50
View File
@@ -1,53 +1,98 @@
"""Round 111: the visualizer page's sliders are tall and jump where clicked; """Round 111: a tag or art save on the playing song doesn't glitch playback.
the radial dot size reads as a share of the spacing between dots."""
from unittest.mock import MagicMock
from PyQt6.QtCore import QPoint, Qt mutagen saves in place, shifting the audio inside the file when a tag
from PyQt6.QtTest import QTest 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 import pytest
from lintunes.gui.preferences_dialog import PreferencesDialog
from lintunes.gui.transport import ClickJumpSlider from lintunes import tagging
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 _strays(path):
return [p for p in path.parent.iterdir() if p.name.startswith(".lintunes-tag-")]
@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_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 from lintunes.preferences import Preferences
library = Library()
library.tracks[1] = Track(track_id=1, name="Song", location="/music/song.mp3")
def _dialog(tmp_path): window = MainWindow(LibraryManager(library, tmp_path / "data"),
dialog = PreferencesDialog(Preferences(tmp_path), MagicMock()) Preferences(tmp_path / "data"))
dialog.resize(900, 700) try:
dialog.pages_list.setCurrentRow(2) assert tagging.in_use == window._files_in_use
dialog._viz_radios["radial"].setChecked(True) assert tagging.in_use() == ()
dialog.show() window.player._current_track = library.tracks[1]
QTest.qWait(20) assert tagging.in_use() == ("/music/song.mp3",)
return dialog finally:
window.player._current_track = None
window.close()
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 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()
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%"