forked from trav/lintunes
File → Export Playlist…, and the same item on a playlist's right-click
menu. A sibling of device_sync: pure plan_export() first, then a worker
on a daemon thread sharing the status-bar progress widgets. The manifest
(index.html / .m3u) is written last, so an interrupted export never
leaves a page naming files that aren't there.
Two destinations. A folder gives the audio under "Artist - Title" names
plus an extended .m3u. A web mix gives a self-contained static site
reproducing the hand-made yearly mixes, with a dialog for title,
description and hero image.
audio.js and jQuery are gone. The old pages shipped ~293 KB: a build of
audio.js whose upstream hasn't moved since 2012, plus jQuery 3.2.1
(CVE-2019-11358, CVE-2020-11022, CVE-2020-11023 — unexploitable on a
static page, since nothing untrusted reaches a jQuery HTML sink, but
dead weight regardless). audio.js never used jQuery; jQuery was there
for ~25 lines of tracklist glue. Both are replaced by a dependency-free
player.js plus a player.css transcribed from the customized audio.js
skin, so the page looks identical — same 250px #c7b563 bar, same
player-graphics.gif (byte-identical: it's an animated GIF whose loading
frame is a spinner), same shortcuts. ~293 KB → ~6 KB. The Flash
fallback went too; audio.js gated it on !canPlayType("audio/mpeg;"),
unreachable since ~2010.
Conversion happens only when a browser genuinely can't decode a file,
never because of bitrate — a 320 kbps MP3 is copied verbatim. Everything
that does convert targets FLAC, so a conversion cannot cost a bit; a
test asserts the exported FLAC's decoded PCM hashes identical to the
ALAC source. Against the real library that's 105 Apple Lossless and 8
AIFF out of 21,382 tracks. DRM'd tracks are reported in a confirmation
dialog, never silently dropped and never attempted. ffmpeg is the CLI
binary here, not Qt's ffmpeg backend, so it's detected at runtime.
Verified in Chromium 151 and Firefox 153 over CDP/Marionette: every
exported format decodes including the converted FLAC, the player builds,
click / space / arrows / scrubber-seek / autoplay-next all work, and the
network log shows no request for jquery, audio.min.js or any .swf.
mix-example/ removed; the template reproduces it.
112 lines
4.3 KiB
Python
112 lines
4.3 KiB
Python
"""What a browser can play, and how to fix what it can't.
|
|
|
|
The gate for the web-mix export, modelled on ``lintunes/cast/support.py``:
|
|
deny-by-default on the suffix, with the iTunes ``kind`` string breaking the
|
|
tie inside the ``.m4a`` container (which holds plain AAC, Apple Lossless and
|
|
FairPlay-protected audio alike — the suffix alone can't tell them apart).
|
|
|
|
Two rules carry the whole design:
|
|
|
|
* **Bitrate is never a conversion trigger.** A 320 kbps MP3 is copied
|
|
byte-for-byte, because every browser plays it. Only *unplayable* formats
|
|
are touched.
|
|
* **Every conversion targets FLAC**, so a conversion can never cost a single
|
|
bit. ALAC and AIFF are both lossless already, so FLAC round-trips them
|
|
exactly (and AIFF, being uncompressed PCM, actually gets smaller). For the
|
|
rare lossy oddity FLAC is wasteful in bytes but still incapable of adding
|
|
generation loss, which is the property worth protecting.
|
|
|
|
FLAC in ``<audio>`` is native in Chrome 56+, Firefox 51+ and Safari 11+.
|
|
"""
|
|
|
|
import shutil
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
# Audio containers every current browser decodes from an <audio> element.
|
|
_BROWSER_OK = {
|
|
".mp3", ".mpga", ".m4a", ".m4b", ".aac", ".wav",
|
|
".flac", ".ogg", ".oga", ".opus", ".webm",
|
|
}
|
|
|
|
# iTunes ``kind`` strings for things living in an .m4a that a browser can't
|
|
# decode. "Purchased AAC audio file" is deliberately absent: those are
|
|
# DRM-free iTunes Plus downloads and play fine.
|
|
_CONVERT_KINDS = {"Apple Lossless audio file"}
|
|
_REFUSED_KINDS = {"Protected AAC audio file": "it's copy-protected AAC"}
|
|
|
|
# Suffixes that are hopeless regardless of kind. FairPlay can't be decrypted,
|
|
# so there is nothing to convert — the track is reported, never attempted.
|
|
_REFUSED_SUFFIXES = {".m4p": "it's copy-protected AAC"}
|
|
|
|
|
|
def conversion_for(location: str, kind: str = "") -> tuple[str | None, str | None]:
|
|
"""How to get `location` onto a web page.
|
|
|
|
Returns ``(target_ext, refusal_reason)``:
|
|
|
|
* ``(None, None)`` — already playable, copy it verbatim.
|
|
* ``("flac", None)`` — needs a lossless transcode.
|
|
* ``(None, reason)`` — can't be exported at all; `reason` is phrased to
|
|
follow "skipped X because …".
|
|
"""
|
|
if not location:
|
|
return None, "it has no file"
|
|
if kind in _REFUSED_KINDS:
|
|
return None, _REFUSED_KINDS[kind]
|
|
suffix = Path(location).suffix.lower()
|
|
if suffix in _REFUSED_SUFFIXES:
|
|
return None, _REFUSED_SUFFIXES[suffix]
|
|
# Checked before _BROWSER_OK: ALAC wears a perfectly playable .m4a suffix.
|
|
if kind in _CONVERT_KINDS:
|
|
return "flac", None
|
|
if suffix in _BROWSER_OK:
|
|
return None, None
|
|
return "flac", None
|
|
|
|
|
|
def ffmpeg_available() -> bool:
|
|
"""Whether the ffmpeg *binary* is on PATH.
|
|
|
|
Separate from Qt Multimedia's ffmpeg backend, which is a shared library:
|
|
a machine can play audio in the app and still have no ``ffmpeg`` command.
|
|
"""
|
|
return shutil.which("ffmpeg") is not None
|
|
|
|
|
|
def convert_to_flac(src: Path, dest: Path, cancel=None) -> None:
|
|
"""Transcode `src` to FLAC at `dest`. Raises OSError on failure.
|
|
|
|
`-vn` drops the cover art: mutagen re-attaches tags downstream if we ever
|
|
want them, and a video stream in a FLAC container trips some decoders.
|
|
`-nostdin` stops ffmpeg from eating the terminal's stdin when lintunes is
|
|
launched from a shell.
|
|
"""
|
|
cmd = [
|
|
"ffmpeg", "-nostdin", "-loglevel", "error", "-y",
|
|
"-i", str(src), "-vn", "-c:a", "flac", "-compression_level", "5",
|
|
str(dest),
|
|
]
|
|
try:
|
|
proc = subprocess.Popen(cmd, stdin=subprocess.DEVNULL,
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.PIPE)
|
|
except (OSError, ValueError) as e:
|
|
raise OSError(f"couldn't run ffmpeg: {e}") from e
|
|
|
|
while True:
|
|
try:
|
|
_, err = proc.communicate(timeout=0.25)
|
|
break
|
|
except subprocess.TimeoutExpired:
|
|
if cancel is not None and cancel.is_set():
|
|
proc.kill()
|
|
proc.communicate()
|
|
dest.unlink(missing_ok=True)
|
|
return
|
|
if proc.returncode != 0:
|
|
dest.unlink(missing_ok=True)
|
|
detail = (err or b"").decode("utf-8", "replace").strip().splitlines()
|
|
raise OSError(f"ffmpeg failed on {src.name}"
|
|
+ (f": {detail[-1]}" if detail else ""))
|