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 -1
View File
@@ -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
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,
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):