Debian Codegraph @

beetsplug/replaygain.py

raw
1 from __future__ import annotations
2
3 import collections
4 import contextvars
5 import enum
6 import math
7 import os
8 import queue
9 import shutil
10 import signal
11 import subprocess
12 import sys
13 import warnings
14 from abc import ABC, abstractmethod
15 from dataclasses import dataclass
16 from multiprocessing.pool import ThreadPool
17 from pathlib import Path
18 from threading import Event, Thread
19 from typing import TYPE_CHECKING, Any, ClassVar, Literal, Protocol, TypeVar
20
21 from beets import ui
22 from beets.exceptions import UserError
23 from beets.plugins import BeetsPlugin
24 from beets.util import command_output, syspath
25
26 if TYPE_CHECKING:
27 from collections.abc import Callable, Sequence
28 from logging import Logger
29 from types import FrameType
30
31 from confuse import ConfigView
32 from gi.repository import Gst
33
34 from beets.importer import ImportSession, ImportTask
35 from beets.library import Album, Item, Library
36 from beets.util import CommandOutput
37
38 from ._typing import JSONDict
39
40
41 class ReplayGainCLIOpts(Protocol):
42 album: bool
43 force: bool
44 threads: int | None
45 write: bool | None
46
47
48 # Utilities.
49
50
51 class ReplayGainError(Exception):
52 """Raised when a local (to a track or an album) error occurs in one
53 of the backends.
54 """
55
56
57 class FatalReplayGainError(Exception):
58 """Raised when a fatal error occurs in one of the backends."""
59
60
61 class FatalGstreamerPluginReplayGainError(FatalReplayGainError):
62 """Raised when a fatal error occurs in the GStreamerBackend when
63 loading the required plugins."""
64
65
66 def call(args: Sequence[str], log: Logger, **kwargs: Any) -> CommandOutput:
67 """Execute the command and return its output or raise a
68 ReplayGainError on failure.
69 """
70 try:
71 return command_output(args, **kwargs)
72 except subprocess.CalledProcessError as e:
73 log.debug(e.output.decode("utf8", "ignore"))
74 raise ReplayGainError(f"{args[0]} exited with status {e.returncode}")
75
76
77 def db_to_lufs(db: float) -> float:
78 """Convert db to LUFS.
79
80 According to https://wiki.hydrogenaud.io/index.php?title=
81 ReplayGain_2.0_specification#Reference_level
82 """
83 return db - 107
84
85
86 def lufs_to_db(db: float) -> float:
87 """Convert LUFS to db.
88
89 According to https://wiki.hydrogenaud.io/index.php?title=
90 ReplayGain_2.0_specification#Reference_level
91 """
92 return db + 107
93
94
95 # Backend base and plumbing classes.
96
97
98 @dataclass
99 class Gain:
100 # gain: in LU to reference level
101 gain: float
102 # peak: part of full scale (FS is 1.0)
103 peak: float
104
105
106 class PeakMethod(enum.Enum):
107 true = 1
108 sample = 2
109
110
111 class RgTask:
112 """State and methods for a single replaygain calculation (rg version).
113
114 Bundles the state (parameters and results) of a single replaygain
115 calculation (either for one item, one disk, or one full album).
116
117 This class provides methods to store the resulting gains and peaks as plain
118 old rg tags.
119 """
120
121 def __init__(
122 self,
123 items: Sequence[Item],
124 album: Album | None,
125 target_level: float,
126 peak_method: PeakMethod | None,
127 backend_name: str,
128 log: Logger,
129 ) -> None:
130 self.items = items
131 self.album = album
132 self.target_level = target_level
133 self.peak_method = peak_method
134 self.backend_name = backend_name
135 self._log = log
136 self.album_gain: Gain | None = None
137 self.track_gains: list[Gain] | None = None
138
139 def _store_track_gain(self, item: Item, track_gain: Gain) -> None:
140 """Store track gain for a single item in the database."""
141 item.r128_track_gain = None
142 item.rg_track_gain = track_gain.gain
143 item.rg_track_peak = track_gain.peak
144 item.store()
145 self._log.debug(
146 "applied track gain {0.rg_track_gain} LU, peak {0.rg_track_peak} of FS",
147 item,
148 )
149
150 def _store_album_gain(self, item: Item, album_gain: Gain) -> None:
151 """Store album gain for a single item in the database.
152
153 The caller needs to ensure that `self.album_gain is not None`.
154 """
155 item.r128_album_gain = None
156 item.rg_album_gain = album_gain.gain
157 item.rg_album_peak = album_gain.peak
158 item.store()
159 self._log.debug(
160 "applied album gain {0.rg_album_gain} LU, peak {0.rg_album_peak} of FS",
161 item,
162 )
163
164 def _store_track(self, write: bool) -> None:
165 """Store track gain for the first track of the task in the database."""
166 item = self.items[0]
167 if self.track_gains is None or len(self.track_gains) != 1:
168 # In some cases, backends fail to produce a valid
169 # `track_gains` without throwing FatalReplayGainError
170 # => raise non-fatal exception & continue
171 raise ReplayGainError(
172 f"ReplayGain backend `{self.backend_name}` failed for track"
173 f" {item}"
174 )
175
176 self._store_track_gain(item, self.track_gains[0])
177 if write:
178 item.try_write()
179 self._log.debug("done analyzing {}", item)
180
181 def _store_album(self, write: bool) -> None:
182 """Store track/album gains for all tracks of the task in the database."""
183 if (
184 self.album_gain is None
185 or self.track_gains is None
186 or len(self.track_gains) != len(self.items)
187 ):
188 # In some cases, backends fail to produce a valid
189 # `album_gain` without throwing FatalReplayGainError
190 # => raise non-fatal exception & continue
191 raise ReplayGainError(
192 f"ReplayGain backend `{self.backend_name}` failed "
193 f"for some tracks in album {self.album}"
194 )
195 for item, track_gain in zip(self.items, self.track_gains):
196 self._store_track_gain(item, track_gain)
197 self._store_album_gain(item, self.album_gain)
198 if write:
199 item.try_write()
200 self._log.debug("done analyzing {}", item)
201
202 def store(self, write: bool) -> None:
203 """Store computed gains for the items of this task in the database."""
204 if self.album is not None:
205 self._store_album(write)
206 else:
207 self._store_track(write)
208
209
210 class R128Task(RgTask):
211 """State and methods for a single replaygain calculation (r128 version).
212
213 Bundles the state (parameters and results) of a single replaygain
214 calculation (either for one item, one disk, or one full album).
215
216 This class provides methods to store the resulting gains and peaks as R128
217 tags.
218 """
219
220 def __init__(
221 self,
222 items: Sequence[Item],
223 album: Album | None,
224 target_level: float,
225 backend_name: str,
226 log: Logger,
227 ) -> None:
228 # R128_* tags do not store the track/album peak
229 super().__init__(items, album, target_level, None, backend_name, log)
230
231 def _store_track_gain(self, item: Item, track_gain: Gain) -> None:
232 item.rg_track_gain = None
233 item.rg_track_peak = None
234 item.r128_track_gain = track_gain.gain
235 item.store()
236 self._log.debug("applied r128 track gain {.r128_track_gain} LU", item)
237
238 def _store_album_gain(self, item: Item, album_gain: Gain) -> None:
239 """
240
241 The caller needs to ensure that `self.album_gain is not None`.
242 """
243 item.rg_album_gain = None
244 item.rg_album_peak = None
245 item.r128_album_gain = album_gain.gain
246 item.store()
247 self._log.debug("applied r128 album gain {.r128_album_gain} LU", item)
248
249
250 AnyRgTask = TypeVar("AnyRgTask", bound=RgTask)
251
252
253 class Backend(ABC):
254 """An abstract class representing engine for calculating RG values."""
255
256 NAME = ""
257 do_parallel = False
258
259 def __init__(self, config: ConfigView, log: Logger) -> None:
260 """Initialize the backend with the configuration view for the
261 plugin.
262 """
263 self._log = log
264
265 @abstractmethod
266 def compute_track_gain(self, task: AnyRgTask) -> AnyRgTask:
267 """Computes the track gain for the tracks belonging to `task`, and sets
268 the `track_gains` attribute on the task. Returns `task`.
269 """
270 raise NotImplementedError()
271
272 @abstractmethod
273 def compute_album_gain(self, task: AnyRgTask) -> AnyRgTask:
274 """Computes the album gain for the album belonging to `task`, and sets
275 the `album_gain` attribute on the task. Returns `task`.
276 """
277 raise NotImplementedError()
278
279
280 # ffmpeg backend
281 class FfmpegBackend(Backend):
282 """A replaygain backend using ffmpeg's ebur128 filter."""
283
284 NAME = "ffmpeg"
285 do_parallel = True
286
287 def __init__(self, config: ConfigView, log: Logger) -> None:
288 super().__init__(config, log)
289 self._ffmpeg_path = "ffmpeg"
290
291 # check that ffmpeg is installed
292 try:
293 ffmpeg_version_out = call([self._ffmpeg_path, "-version"], log)
294 except OSError:
295 raise FatalReplayGainError(
296 f"could not find ffmpeg at {self._ffmpeg_path}"
297 )
298 incompatible_ffmpeg = True
299 for line in ffmpeg_version_out.stdout.splitlines():
300 if line.startswith(b"configuration:"):
301 if b"--enable-libebur128" in line:
302 incompatible_ffmpeg = False
303 if line.startswith(b"libavfilter"):
304 version_parts = (
305 line.split(b" ", 1)[1].split(b"/", 1)[0].split(b".")
306 )
307 version = tuple(map(int, version_parts))
308 if version >= (6, 67, 100):
309 incompatible_ffmpeg = False
310 if incompatible_ffmpeg:
311 raise FatalReplayGainError(
312 "Installed FFmpeg version does not support ReplayGain."
313 "calculation. Either libavfilter version 6.67.100 or above or"
314 "the --enable-libebur128 configuration option is required."
315 )
316
317 def compute_track_gain(self, task: AnyRgTask) -> AnyRgTask:
318 """Computes the track gain for the tracks belonging to `task`, and sets
319 the `track_gains` attribute on the task. Returns `task`.
320 """
321 task.track_gains = [
322 self._analyse_item(
323 item, task.target_level, task.peak_method, count_blocks=False
324 )[0] # take only the gain, discarding number of gating blocks
325 for item in task.items
326 ]
327
328 return task
329
330 def compute_album_gain(self, task: AnyRgTask) -> AnyRgTask:
331 """Computes the album gain for the album belonging to `task`, and sets
332 the `album_gain` attribute on the task. Returns `task`.
333 """
334 target_level_lufs = db_to_lufs(task.target_level)
335
336 # analyse tracks
337 # Gives a list of tuples (track_gain, track_n_blocks)
338 track_results: list[tuple[Gain, int]] = [
339 self._analyse_item(
340 item, task.target_level, task.peak_method, count_blocks=True
341 )
342 for item in task.items
343 ]
344
345 track_gains: list[Gain] = [tg for tg, _nb in track_results]
346
347 # Album peak is maximum track peak
348 album_peak = max(tg.peak for tg in track_gains)
349
350 # Total number of BS.1770 gating blocks
351 n_blocks = sum(nb for _tg, nb in track_results)
352
353 def sum_of_track_powers(track_gain: Gain, track_n_blocks: int) -> float:
354 # convert `LU to target_level` -> LUFS
355 loudness = target_level_lufs - track_gain.gain
356
357 # This reverses ITU-R BS.1770-4 p. 6 equation (5) to convert
358 # from loudness to power. The result is the average gating
359 # block power.
360 power = 10 ** ((loudness + 0.691) / 10)
361
362 # Multiply that average power by the number of gating blocks to get
363 # the sum of all block powers in this track.
364 return track_n_blocks * power
365
366 # calculate album gain
367 if n_blocks > 0:
368 # Sum over all tracks to get the sum of BS.1770 gating block powers
369 # for the entire album.
370 sum_powers = sum(
371 sum_of_track_powers(tg, nb) for tg, nb in track_results
372 )
373
374 # compare ITU-R BS.1770-4 p. 6 equation (5)
375 # Album gain is the replaygain of the concatenation of all tracks.
376 album_gain = -0.691 + 10 * math.log10(sum_powers / n_blocks)
377 else:
378 album_gain = -70
379
380 # convert LUFS -> `LU to target_level`
381 album_gain = target_level_lufs - album_gain
382
383 self._log.debug(
384 "{.album}: gain {} LU, peak {}", task, album_gain, album_peak
385 )
386
387 task.album_gain = Gain(album_gain, album_peak)
388 task.track_gains = track_gains
389
390 return task
391
392 def _construct_cmd(
393 self, item: Item, peak_method: PeakMethod | None
394 ) -> list[str]:
395 """Construct the shell command to analyse items."""
396 return [
397 self._ffmpeg_path,
398 "-nostats",
399 "-hide_banner",
400 "-i",
401 str(item.filepath),
402 "-map",
403 "a:0",
404 "-filter",
405 f"ebur128=peak={'none' if peak_method is None else peak_method.name}",
406 "-f",
407 "null",
408 "-",
409 ]
410
411 def _analyse_item(
412 self,
413 item: Item,
414 target_level: float,
415 peak_method: PeakMethod | None,
416 count_blocks: bool = True,
417 ) -> tuple[Gain, int]:
418 """Analyse item. Return a pair of a Gain object and the number
419 of gating blocks above the threshold.
420
421 If `count_blocks` is False, the number of gating blocks returned
422 will be 0.
423 """
424 target_level_lufs = db_to_lufs(target_level)
425
426 # call ffmpeg
427 self._log.debug("analyzing {}", item)
428 cmd = self._construct_cmd(item, peak_method)
429 self._log.debug("executing {}", " ".join(cmd))
430 output = call(cmd, self._log).stderr.splitlines()
431
432 # parse output
433
434 if peak_method is None:
435 peak = 0.0
436 else:
437 line_peak = self._find_line(
438 output,
439 # `peak_method` is non-`None` in this arm of the conditional
440 f" {peak_method.name.capitalize()} peak:".encode(),
441 start_line=len(output) - 1,
442 step_size=-1,
443 )
444 peak = self._parse_float(
445 output[self._find_line(output, b" Peak:", line_peak)]
446 )
447 # convert TPFS -> part of FS
448 peak = 10 ** (peak / 20)
449
450 line_integrated_loudness = self._find_line(
451 output,
452 b" Integrated loudness:",
453 start_line=len(output) - 1,
454 step_size=-1,
455 )
456 gain = self._parse_float(
457 output[self._find_line(output, b" I:", line_integrated_loudness)]
458 )
459 # convert LUFS -> LU from target level
460 gain = target_level_lufs - gain
461
462 # count BS.1770 gating blocks
463 n_blocks = 0
464 if count_blocks:
465 gating_threshold = self._parse_float(
466 output[
467 self._find_line(
468 output,
469 b" Threshold:",
470 start_line=line_integrated_loudness,
471 )
472 ]
473 )
474 for line in output:
475 if not line.startswith(b"[Parsed_ebur128"):
476 continue
477 if line.endswith(b"Summary:"):
478 continue
479 line_parts = line.split(b"M:", 1)
480 if len(line_parts) < 2:
481 continue
482 if (
483 self._parse_float(b"M: " + line_parts[1])
484 >= gating_threshold
485 ):
486 n_blocks += 1
487 self._log.debug(
488 "{}: {} blocks over {} LUFS", item, n_blocks, gating_threshold
489 )
490
491 self._log.debug("{}: gain {} LU, peak {}", item, gain, peak)
492
493 return Gain(gain, peak), n_blocks
494
495 def _find_line(
496 self,
497 output: Sequence[bytes],
498 search: bytes,
499 start_line: int = 0,
500 step_size: int = 1,
501 ) -> int:
502 """Return index of line beginning with `search`.
503
504 Begins searching at index `start_line` in `output`.
505 """
506 end_index = len(output) if step_size > 0 else -1
507 for i in range(start_line, end_index, step_size):
508 if output[i].startswith(search):
509 return i
510 raise ReplayGainError(
511 f"ffmpeg output: missing {search!r} after line {start_line}"
512 )
513
514 def _parse_float(self, line: bytes) -> float:
515 """Extract a float from a key value pair in `line`.
516
517 This format is expected: /[^:]:[[:space:]]*value.*/, where `value` is
518 the float.
519 """
520 # extract value
521 parts = line.split(b":", 1)
522 if len(parts) < 2:
523 raise ReplayGainError(
524 f"ffmpeg output: expected key value pair, found {line!r}"
525 )
526 value = parts[1].lstrip()
527 # strip unit
528 value = value.split(b" ", 1)[0]
529 # cast value to float
530 try:
531 return float(value)
532 except ValueError:
533 raise ReplayGainError(
534 f"ffmpeg output: expected float value, found {value!r}"
535 )
536
537
538 # mpgain/aacgain CLI tool backend.
539 Tool = Literal["mp3rgain", "aacgain", "mp3gain"]
540
541
542 class CommandBackend(Backend):
543 NAME = "command"
544 SUPPORTED_FORMATS_BY_TOOL: ClassVar[dict[Tool, set[str]]] = {
545 "mp3rgain": {"AAC", "MP3"},
546 "aacgain": {"AAC", "MP3"},
547 "mp3gain": {"MP3"},
548 }
549 do_parallel = True
550
551 cmd_name: Tool
552
553 def __init__(self, config: ConfigView, log: Logger) -> None:
554 super().__init__(config, log)
555 config.add({"command": "", "noclip": True})
556
557 cmd_path = Path(config["command"].as_str())
558 supported_tools = set(self.SUPPORTED_FORMATS_BY_TOOL)
559
560 if (cmd_name := cmd_path.name) not in supported_tools:
561 raise FatalReplayGainError(
562 f"replaygain.command must be one of {supported_tools!r},"
563 f" not {cmd_name!r}"
564 )
565
566 if command_exec := shutil.which(str(cmd_path)):
567 self.command = command_exec
568 self.cmd_name = cmd_name # type: ignore[assignment]
569 else:
570 raise FatalReplayGainError(
571 f"replaygain command not found: {cmd_path}"
572 )
573
574 self.noclip = config["noclip"].get(bool)
575
576 def compute_track_gain(self, task: AnyRgTask) -> AnyRgTask:
577 """Computes the track gain for the tracks belonging to `task`, and sets
578 the `track_gains` attribute on the task. Returns `task`.
579 """
580 supported_items = list(filter(self.format_supported, task.items))
581 output = self.compute_gain(supported_items, task.target_level, False)
582 task.track_gains = output
583 return task
584
585 def compute_album_gain(self, task: AnyRgTask) -> AnyRgTask:
586 """Computes the album gain for the album belonging to `task`, and sets
587 the `album_gain` attribute on the task. Returns `task`.
588 """
589 # TODO: What should be done when not all tracks in the album are
590 # supported?
591
592 supported_items = list(filter(self.format_supported, task.items))
593 if len(supported_items) != len(task.items):
594 self._log.debug("tracks are of unsupported format")
595 task.album_gain = None
596 task.track_gains = None
597 return task
598
599 output = self.compute_gain(supported_items, task.target_level, True)
600 task.album_gain = output[-1]
601 task.track_gains = output[:-1]
602 return task
603
604 def format_supported(self, item: Item) -> bool:
605 """Checks whether the given item is supported by the selected tool."""
606 return item.format in self.SUPPORTED_FORMATS_BY_TOOL[self.cmd_name]
607
608 def compute_gain(
609 self, items: Sequence[Item], target_level: float, is_album: bool
610 ) -> list[Gain]:
611 """Computes the track or album gain of a list of items, returns
612 a list of TrackGain objects.
613
614 When computing album gain, the last TrackGain object returned is
615 the album gain
616 """
617 if not items:
618 self._log.debug("no supported tracks to analyze")
619 return []
620
621 """Compute ReplayGain values and return a list of results
622 dictionaries as given by `parse_tool_output`.
623 """
624 # Construct shell command. The "-o" option makes the output
625 # easily parseable (tab-delimited). "-s s" forces gain
626 # recalculation even if tags are already present and disables
627 # tag-writing; this turns the mp3gain/aacgain tool into a gain
628 # calculator rather than a tag manipulator because we take care
629 # of changing tags ourselves.
630 cmd = [
631 self.command,
632 "-o",
633 "-s",
634 "s",
635 # Avoid clipping or disable clipping warning
636 "-k" if self.noclip else "-c",
637 "-d",
638 str(int(target_level - 89)),
639 *[str(i.filepath) for i in items],
640 ]
641
642 self._log.debug("analyzing {} files", len(items))
643 self._log.debug("executing {}", " ".join(cmd))
644 output = call(cmd, self._log).stdout
645 self._log.debug("analysis finished")
646 return self.parse_tool_output(
647 output, len(items) + (1 if is_album else 0)
648 )
649
650 def parse_tool_output(self, text: bytes, num_lines: int) -> list[Gain]:
651 """Given the tab-delimited output from an invocation of mp3gain
652 or aacgain, parse the text and return a list of dictionaries
653 containing information about each analyzed file.
654 """
655 out = []
656 for line in text.split(b"\n")[1 : num_lines + 1]:
657 parts = line.split(b"\t")
658 if len(parts) != 6 or parts[0] == b"File":
659 self._log.debug("bad tool output: {}", text)
660 raise ReplayGainError("mp3gain failed")
661
662 # _file = parts[0]
663 # _mp3gain = int(parts[1])
664 gain = float(parts[2])
665 peak = float(parts[3]) / (1 << 15)
666 # _maxgain = int(parts[4])
667 # _mingain = int(parts[5])
668
669 out.append(Gain(gain, peak))
670 return out
671
672
673 # metaflac CLI tool backend.
674
675
676 class MetaflacBackend(Backend):
677 """A replaygain backend using the ``metaflac`` command-line tool."""
678
679 NAME = "metaflac"
680 do_parallel = True
681
682 SUPPORTED_FORMATS: ClassVar[set[str]] = {"FLAC"}
683
684 def __init__(self, config: ConfigView, log: Logger) -> None:
685 super().__init__(config, log)
686 config.add({"metaflac": "metaflac"})
687
688 command = config["metaflac"].as_str()
689 path = shutil.which(command)
690 if path is None:
691 raise FatalReplayGainError(
692 f"replaygain metaflac command not found: {command!r}"
693 )
694 self.command = path
695
696 def format_supported(self, item: Item) -> bool:
697 """Return whether metaflac can process this item."""
698 return item.format in self.SUPPORTED_FORMATS
699
700 def compute_track_gain(self, task: AnyRgTask) -> AnyRgTask:
701 """Compute the track gain for each FLAC item in the task."""
702 track_gains = []
703 for item in filter(self.format_supported, task.items):
704 self._add_replay_gain([item])
705 track_gains.append(
706 self._read_gain(item, "TRACK", task.target_level)
707 )
708 task.track_gains = track_gains
709 return task
710
711 def compute_album_gain(self, task: AnyRgTask) -> AnyRgTask:
712 """Compute the album gain and per-track gains for the FLAC items."""
713 items = list(task.items)
714 if not items or not all(self.format_supported(i) for i in items):
715 task.album_gain = None
716 task.track_gains = None
717 return task
718
719 self._add_replay_gain(items)
720 task.track_gains = [
721 self._read_gain(item, "TRACK", task.target_level) for item in items
722 ]
723 task.album_gain = self._read_gain(items[0], "ALBUM", task.target_level)
724 return task
725
726 def _add_replay_gain(self, items: Sequence[Item]) -> None:
727 """Run ``metaflac --add-replay-gain`` on the given files."""
728 paths = [str(item.filepath) for item in items]
729 call([self.command, "--add-replay-gain", *paths], self._log)
730
731 def _read_gain(self, item: Item, kind: str, target_level: float) -> Gain:
732 """Read the REPLAYGAIN gain and peak tags back from a file."""
733 gain_tag = f"REPLAYGAIN_{kind}_GAIN"
734 peak_tag = f"REPLAYGAIN_{kind}_PEAK"
735 command = [
736 self.command,
737 f"--show-tag={gain_tag}",
738 f"--show-tag={peak_tag}",
739 str(item.filepath),
740 ]
741 tags = self._parse_tags(call(command, self._log).stdout)
742 try:
743 gain = self._parse_gain(tags[gain_tag])
744 peak = float(tags[peak_tag])
745 except (KeyError, IndexError, ValueError) as exc:
746 raise ReplayGainError(
747 f"could not read metaflac replaygain tags for {item}: {exc!r}"
748 )
749 # metaflac uses an 89 dB reference, like the other backends
750 return Gain(gain=gain + (target_level - 89.0), peak=peak)
751
752 @staticmethod
753 def _parse_tags(output: bytes) -> dict[str, str]:
754 """Turn metaflac's NAME=VALUE output into a dict."""
755 tags: dict[str, str] = {}
756 for line in output.decode("utf-8", "ignore").splitlines():
757 name, sep, value = line.partition("=")
758 if sep:
759 tags[name.strip().upper()] = value.strip()
760 return tags
761
762 @staticmethod
763 def _parse_gain(value: str) -> float:
764 """Turn a '-7.89 dB' tag value into a float."""
765 return float(value.split()[0])
766
767
768 # GStreamer-based backend.
769
770
771 class GStreamerBackend(Backend):
772 NAME = "gstreamer"
773
774 _error: ReplayGainError | None = None
775
776 def __init__(self, config: ConfigView, log: Logger) -> None:
777 super().__init__(config, log)
778 self._import_gst()
779
780 # Initialized a GStreamer pipeline of the form filesrc ->
781 # decodebin -> audioconvert -> audioresample -> rganalysis ->
782 # fakesink The connection between decodebin and audioconvert is
783 # handled dynamically after decodebin figures out the type of
784 # the input file.
785 self._src = self.Gst.ElementFactory.make("filesrc", "src")
786 self._decbin = self.Gst.ElementFactory.make("decodebin", "decbin")
787 self._conv = self.Gst.ElementFactory.make("audioconvert", "conv")
788 self._res = self.Gst.ElementFactory.make("audioresample", "res")
789 self._rg = self.Gst.ElementFactory.make("rganalysis", "rg")
790
791 if (
792 self._src is None
793 or self._decbin is None
794 or self._conv is None
795 or self._res is None
796 or self._rg is None
797 ):
798 raise FatalGstreamerPluginReplayGainError(
799 "Failed to load required GStreamer plugins"
800 )
801
802 # We check which files need gain ourselves, so all files given
803 # to rganalsys should have their gain computed, even if it
804 # already exists.
805 self._rg.set_property("forced", True)
806 self._sink = self.Gst.ElementFactory.make("fakesink", "sink")
807
808 self._pipe = self.Gst.Pipeline()
809 self._pipe.add(self._src)
810 self._pipe.add(self._decbin)
811 self._pipe.add(self._conv)
812 self._pipe.add(self._res)
813 self._pipe.add(self._rg)
814 self._pipe.add(self._sink)
815
816 self._src.link(self._decbin)
817 self._conv.link(self._res)
818 self._res.link(self._rg)
819 self._rg.link(self._sink)
820
821 self._bus = self._pipe.get_bus()
822 self._bus.add_signal_watch()
823 self._bus.connect("message::eos", self._on_eos)
824 self._bus.connect("message::error", self._on_error)
825 self._bus.connect("message::tag", self._on_tag)
826 # Needed for handling the dynamic connection between decodebin
827 # and audioconvert
828 self._decbin.connect("pad-added", self._on_pad_added)
829 self._decbin.connect("pad-removed", self._on_pad_removed)
830
831 self._main_loop = self.GLib.MainLoop()
832
833 self._files: list[bytes] = []
834
835 def _import_gst(self) -> None:
836 """Import the necessary GObject-related modules and assign `Gst`
837 and `GObject` fields on this object.
838 """
839
840 try:
841 import gi
842 except ImportError:
843 raise FatalReplayGainError(
844 "Failed to load GStreamer: python-gi not found"
845 )
846
847 try:
848 gi.require_version("Gst", "1.0")
849 except ValueError as e:
850 raise FatalReplayGainError(f"Failed to load GStreamer 1.0: {e}")
851
852 from gi.repository import GLib, GObject, Gst
853
854 # Calling GObject.threads_init() is not needed for
855 # PyGObject 3.10.2+
856 with warnings.catch_warnings():
857 warnings.simplefilter("ignore")
858 GObject.threads_init()
859 Gst.init([sys.argv[0]])
860
861 self.GObject = GObject
862 self.GLib = GLib
863 self.Gst = Gst
864
865 def compute(
866 self, items: Sequence[Item], target_level: float, album: bool
867 ) -> None:
868 if len(items) == 0:
869 return
870
871 self._error = None
872 self._files = [i.path for i in items]
873
874 # FIXME: Turn this into DefaultDict[bytes, Gain]
875 self._file_tags: collections.defaultdict[bytes, dict[str, float]] = (
876 collections.defaultdict(dict)
877 )
878
879 self._rg.set_property("reference-level", target_level)
880
881 if album:
882 self._rg.set_property("num-tracks", len(self._files))
883
884 if self._set_first_file():
885 self._main_loop.run()
886 if self._error is not None:
887 raise self._error
888
889 def compute_track_gain(self, task: AnyRgTask) -> AnyRgTask:
890 """Computes the track gain for the tracks belonging to `task`, and sets
891 the `track_gains` attribute on the task. Returns `task`.
892 """
893 self.compute(task.items, task.target_level, False)
894 if len(self._file_tags) != len(task.items):
895 raise ReplayGainError("Some tracks did not receive tags")
896
897 ret = []
898 for item in task.items:
899 ret.append(
900 Gain(
901 self._file_tags[item.path]["TRACK_GAIN"],
902 self._file_tags[item.path]["TRACK_PEAK"],
903 )
904 )
905
906 task.track_gains = ret
907 return task
908
909 def compute_album_gain(self, task: AnyRgTask) -> AnyRgTask:
910 """Computes the album gain for the album belonging to `task`, and sets
911 the `album_gain` attribute on the task. Returns `task`.
912 """
913 items = list(task.items)
914 self.compute(items, task.target_level, True)
915 if len(self._file_tags) != len(items):
916 raise ReplayGainError("Some items in album did not receive tags")
917
918 # Collect track gains.
919 track_gains = []
920 for item in items:
921 try:
922 gain = self._file_tags[item.path]["TRACK_GAIN"]
923 peak = self._file_tags[item.path]["TRACK_PEAK"]
924 except KeyError:
925 raise ReplayGainError("results missing for track")
926 track_gains.append(Gain(gain, peak))
927
928 # Get album gain information from the last track.
929 last_tags = self._file_tags[items[-1].path]
930 try:
931 gain = last_tags["ALBUM_GAIN"]
932 peak = last_tags["ALBUM_PEAK"]
933 except KeyError:
934 raise ReplayGainError("results missing for album")
935
936 task.album_gain = Gain(gain, peak)
937 task.track_gains = track_gains
938 return task
939
940 def close(self) -> None:
941 self._bus.remove_signal_watch()
942
943 def _on_eos(self, bus: str, message: Gst.Message) -> None:
944 # A file finished playing in all elements of the pipeline. The
945 # RG tags have already been propagated. If we don't have a next
946 # file, we stop processing.
947 if not self._set_next_file():
948 self._pipe.set_state(self.Gst.State.NULL)
949 self._main_loop.quit()
950
951 def _on_error(self, bus: str, message: Gst.Message) -> None:
952 self._pipe.set_state(self.Gst.State.NULL)
953 self._main_loop.quit()
954 err, debug = message.parse_error()
955 f = self._src.get_property("location")
956 # A GStreamer error, either an unsupported format or a bug.
957 self._error = ReplayGainError(
958 f"Error {err!r} - {debug!r} on file {f!r}"
959 )
960
961 def _on_tag(self, bus: str, message: Gst.Message) -> None:
962 tags = message.parse_tag()
963
964 def handle_tag(taglist: Gst.TagList, tag: bool, userdata: Any) -> None:
965 # The rganalysis element provides both the existing tags for
966 # files and the new computes tags. In order to ensure we
967 # store the computed tags, we overwrite the RG values of
968 # received a second time.
969 if tag == self.Gst.TAG_TRACK_GAIN:
970 self._file_tags[self._file]["TRACK_GAIN"] = taglist.get_double(
971 tag
972 )[1]
973 elif tag == self.Gst.TAG_TRACK_PEAK:
974 self._file_tags[self._file]["TRACK_PEAK"] = taglist.get_double(
975 tag
976 )[1]
977 elif tag == self.Gst.TAG_ALBUM_GAIN:
978 self._file_tags[self._file]["ALBUM_GAIN"] = taglist.get_double(
979 tag
980 )[1]
981 elif tag == self.Gst.TAG_ALBUM_PEAK:
982 self._file_tags[self._file]["ALBUM_PEAK"] = taglist.get_double(
983 tag
984 )[1]
985 elif tag == self.Gst.TAG_REFERENCE_LEVEL:
986 self._file_tags[self._file]["REFERENCE_LEVEL"] = (
987 taglist.get_double(tag)[1]
988 )
989
990 tags.foreach(handle_tag, None)
991
992 def _set_first_file(self) -> bool:
993 if len(self._files) == 0:
994 return False
995
996 self._file = self._files.pop(0)
997 self._pipe.set_state(self.Gst.State.NULL)
998 self._src.set_property("location", os.fsdecode(syspath(self._file)))
999 self._pipe.set_state(self.Gst.State.PLAYING)
1000 return True
1001
1002 def _set_file(self) -> bool:
1003 """Initialize the filesrc element with the next file to be analyzed."""
1004 # No more files, we're done
1005 if len(self._files) == 0:
1006 return False
1007
1008 self._file = self._files.pop(0)
1009
1010 # Ensure the filesrc element received the paused state of the
1011 # pipeline in a blocking manner
1012 self._src.sync_state_with_parent()
1013 self._src.get_state(self.Gst.CLOCK_TIME_NONE)
1014
1015 # Ensure the decodebin element receives the paused state of the
1016 # pipeline in a blocking manner
1017 self._decbin.sync_state_with_parent()
1018 self._decbin.get_state(self.Gst.CLOCK_TIME_NONE)
1019
1020 # Disconnect the decodebin element from the pipeline, set its
1021 # state to READY to to clear it.
1022 self._decbin.unlink(self._conv)
1023 self._decbin.set_state(self.Gst.State.READY)
1024
1025 # Set a new file on the filesrc element, can only be done in the
1026 # READY state
1027 self._src.set_state(self.Gst.State.READY)
1028 self._src.set_property("location", os.fsdecode(syspath(self._file)))
1029
1030 self._decbin.link(self._conv)
1031 self._pipe.set_state(self.Gst.State.READY)
1032
1033 return True
1034
1035 def _set_next_file(self) -> bool:
1036 """Set the next file to be analyzed while keeping the pipeline
1037 in the PAUSED state so that the rganalysis element can correctly
1038 handle album gain.
1039 """
1040 # A blocking pause
1041 self._pipe.set_state(self.Gst.State.PAUSED)
1042 self._pipe.get_state(self.Gst.CLOCK_TIME_NONE)
1043
1044 # Try setting the next file
1045 ret = self._set_file()
1046 if ret:
1047 # Seek to the beginning in order to clear the EOS state of the
1048 # various elements of the pipeline
1049 self._pipe.seek_simple(
1050 self.Gst.Format.TIME, self.Gst.SeekFlags.FLUSH, 0
1051 )
1052 self._pipe.set_state(self.Gst.State.PLAYING)
1053
1054 return ret
1055
1056 def _on_pad_added(self, decbin: Gst.Element, pad: Gst.Pad) -> None:
1057 sink_pad = self._conv.get_compatible_pad(pad, None)
1058 assert sink_pad is not None
1059 pad.link(sink_pad)
1060
1061 def _on_pad_removed(self, decbin: Gst.Element, pad: Gst.Pad) -> None:
1062 # Called when the decodebin element is disconnected from the
1063 # rest of the pipeline while switching input files
1064 peer = pad.get_peer()
1065 assert peer is None
1066
1067
1068 class AudioToolsBackend(Backend):
1069 """ReplayGain backend that uses `Python Audio Tools
1070 <http://audiotools.sourceforge.net/>`_ and its capabilities to read more
1071 file formats and compute ReplayGain values using it replaygain module.
1072 """
1073
1074 NAME = "audiotools"
1075
1076 def __init__(self, config: ConfigView, log: Logger) -> None:
1077 super().__init__(config, log)
1078 self._import_audiotools()
1079
1080 def _import_audiotools(self) -> None:
1081 """Check whether it's possible to import the necessary modules.
1082 There is no check on the file formats at runtime.
1083
1084 :raises :exc:`ReplayGainError`: if the modules cannot be imported
1085 """
1086 try:
1087 import audiotools
1088 import audiotools.replaygain
1089 except ImportError:
1090 raise FatalReplayGainError(
1091 "Failed to load audiotools: audiotools not found"
1092 )
1093 self._mod_audiotools = audiotools
1094 self._mod_replaygain = audiotools.replaygain
1095
1096 def open_audio_file(self, item: Item) -> Any:
1097 """Open the file to read the PCM stream from the using
1098 ``item.path``.
1099
1100 :return: the audiofile instance
1101 :rtype: :class:`audiotools.AudioFile`
1102 :raises :exc:`ReplayGainError`: if the file is not found or the
1103 file format is not supported
1104 """
1105 try:
1106 audiofile = self._mod_audiotools.open(
1107 os.fsdecode(syspath(item.path))
1108 )
1109 except OSError:
1110 raise ReplayGainError(f"File {item.filepath} was not found")
1111 except self._mod_audiotools.UnsupportedFile:
1112 raise ReplayGainError(f"Unsupported file type {item.format}")
1113
1114 return audiofile
1115
1116 def init_replaygain(self, audiofile: Any, item: Item) -> Any:
1117 """Return an initialized :class:`audiotools.replaygain.ReplayGain`
1118 instance, which requires the sample rate of the song(s) on which
1119 the ReplayGain values will be computed. The item is passed in case
1120 the sample rate is invalid to log the stored item sample rate.
1121
1122 :return: initialized replagain object
1123 :rtype: :class:`audiotools.replaygain.ReplayGain`
1124 :raises: :exc:`ReplayGainError` if the sample rate is invalid
1125 """
1126 try:
1127 rg = self._mod_replaygain.ReplayGain(audiofile.sample_rate())
1128 except ValueError:
1129 raise ReplayGainError(f"Unsupported sample rate {item.samplerate}")
1130 return rg
1131
1132 def compute_track_gain(self, task: AnyRgTask) -> AnyRgTask:
1133 """Computes the track gain for the tracks belonging to `task`, and sets
1134 the `track_gains` attribute on the task. Returns `task`.
1135 """
1136 gains = [
1137 self._compute_track_gain(i, task.target_level) for i in task.items
1138 ]
1139 task.track_gains = gains
1140 return task
1141
1142 def _with_target_level(self, gain: float, target_level: float) -> float:
1143 """Return `gain` relative to `target_level`.
1144
1145 Assumes `gain` is relative to 89 db.
1146 """
1147 return gain + (target_level - 89)
1148
1149 def _title_gain(
1150 self, rg: Any, audiofile: Any, target_level: float
1151 ) -> tuple[float, float]:
1152 """Get the gain result pair from PyAudioTools using the `ReplayGain`
1153 instance `rg` for the given `audiofile`.
1154
1155 Wraps `rg.title_gain(audiofile.to_pcm())` and throws a
1156 `ReplayGainError` when the library fails.
1157 """
1158 try:
1159 # The method needs an audiotools.PCMReader instance that can
1160 # be obtained from an audiofile instance.
1161 gain, peak = rg.title_gain(audiofile.to_pcm())
1162 except ValueError as exc:
1163 # `audiotools.replaygain` can raise a `ValueError` if the sample
1164 # rate is incorrect.
1165 self._log.debug("error in rg.title_gain() call: {}", exc)
1166 raise ReplayGainError("audiotools audio data error")
1167 return self._with_target_level(gain, target_level), peak
1168
1169 def _compute_track_gain(self, item: Item, target_level: float) -> Gain:
1170 """Compute ReplayGain value for the requested item.
1171
1172 :rtype: :class:`Gain`
1173 """
1174 audiofile = self.open_audio_file(item)
1175 rg = self.init_replaygain(audiofile, item)
1176
1177 # Each call to title_gain on a ReplayGain object returns peak and gain
1178 # of the track.
1179 rg_track_gain, rg_track_peak = self._title_gain(
1180 rg, audiofile, target_level
1181 )
1182
1183 self._log.debug(
1184 "ReplayGain for track {0.artist} - {0.title}: {1:.2f}, {2:.2f}",
1185 item,
1186 rg_track_gain,
1187 rg_track_peak,
1188 )
1189 return Gain(gain=rg_track_gain, peak=rg_track_peak)
1190
1191 def compute_album_gain(self, task: AnyRgTask) -> AnyRgTask:
1192 """Computes the album gain for the album belonging to `task`, and sets
1193 the `album_gain` attribute on the task. Returns `task`.
1194 """
1195 # The first item is taken and opened to get the sample rate to
1196 # initialize the replaygain object. The object is used for all the
1197 # tracks in the album to get the album values.
1198 item = next(iter(task.items))
1199 audiofile = self.open_audio_file(item)
1200 rg = self.init_replaygain(audiofile, item)
1201
1202 track_gains = []
1203 for item in task.items:
1204 audiofile = self.open_audio_file(item)
1205 rg_track_gain, rg_track_peak = self._title_gain(
1206 rg, audiofile, task.target_level
1207 )
1208 track_gains.append(Gain(gain=rg_track_gain, peak=rg_track_peak))
1209 self._log.debug(
1210 "ReplayGain for track {}: {.2f}, {.2f}",
1211 item,
1212 rg_track_gain,
1213 rg_track_peak,
1214 )
1215
1216 # After getting the values for all tracks, it's possible to get the
1217 # album values.
1218 rg_album_gain, rg_album_peak = rg.album_gain()
1219 rg_album_gain = self._with_target_level(
1220 rg_album_gain, task.target_level
1221 )
1222 self._log.debug(
1223 "ReplayGain for album {.items[0].album}: {.2f}, {.2f}",
1224 task,
1225 rg_album_gain,
1226 rg_album_peak,
1227 )
1228
1229 task.album_gain = Gain(gain=rg_album_gain, peak=rg_album_peak)
1230 task.track_gains = track_gains
1231 return task
1232
1233
1234 class ExceptionWatcher(Thread):
1235 """Monitors a queue for exceptions asynchronously.
1236 Once an exception occurs, raise it and execute a callback.
1237 """
1238
1239 def __init__(
1240 self, queue: queue.Queue[BaseException], callback: Callable[[], None]
1241 ) -> None:
1242 self._queue = queue
1243 self._callback = callback
1244 self._stopevent = Event()
1245 Thread.__init__(self)
1246
1247 def run(self) -> None:
1248 while not self._stopevent.is_set():
1249 try:
1250 exc = self._queue.get_nowait()
1251 self._callback()
1252 raise exc
1253 except queue.Empty:
1254 # No exceptions yet, loop back to check
1255 # whether `_stopevent` is set
1256 pass
1257
1258 def join(self, timeout: float | None = None) -> None:
1259 self._stopevent.set()
1260 Thread.join(self, timeout)
1261
1262
1263 # Main plugin logic.
1264
1265 BACKEND_CLASSES: list[type[Backend]] = [
1266 CommandBackend,
1267 MetaflacBackend,
1268 GStreamerBackend,
1269 AudioToolsBackend,
1270 FfmpegBackend,
1271 ]
1272 BACKENDS: dict[str, type[Backend]] = {b.NAME: b for b in BACKEND_CLASSES}
1273
1274
1275 class ReplayGainPlugin(BeetsPlugin):
1276 """Provides ReplayGain analysis."""
1277
1278 pool: ThreadPool | None = None
1279
1280 def __init__(self) -> None:
1281 super().__init__()
1282
1283 # default backend is 'command' for backward-compatibility.
1284 self.config.add(
1285 {
1286 "overwrite": False,
1287 "auto": True,
1288 "backend": "command",
1289 "threads": os.cpu_count(),
1290 "parallel_on_import": False,
1291 "per_disc": False,
1292 "peak": "true",
1293 "targetlevel": 89,
1294 "r128": ["Opus"],
1295 "r128_targetlevel": lufs_to_db(-23),
1296 }
1297 )
1298
1299 # FIXME: Consider renaming the configuration option and deprecating the
1300 # old name 'overwrite'.
1301 self.force_on_import: bool = self.config["overwrite"].get(bool)
1302
1303 # Remember which backend is used for CLI feedback
1304 self.backend_name = self.config["backend"].as_str()
1305
1306 if self.backend_name not in BACKENDS:
1307 raise UserError(
1308 f"Selected ReplayGain backend {self.backend_name} is not"
1309 f" supported. Please select one of: {', '.join(BACKENDS)}"
1310 )
1311
1312 # FIXME: Consider renaming the configuration option to 'peak_method'
1313 # and deprecating the old name 'peak'.
1314 peak_method = self.config["peak"].as_str()
1315 if peak_method not in PeakMethod.__members__:
1316 raise UserError(
1317 f"Selected ReplayGain peak method {peak_method} is not"
1318 " supported. Please select one of:"
1319 f" {', '.join(PeakMethod.__members__)}"
1320 )
1321 # This only applies to plain old rg tags, r128 doesn't store peak
1322 # values.
1323 self.peak_method = PeakMethod[peak_method]
1324
1325 # On-import analysis.
1326 if self.config["auto"]:
1327 self.register_listener("import_begin", self.import_begin)
1328 self.register_listener("import", self.import_end)
1329 self.import_stages = [self.imported]
1330
1331 # Formats to use R128.
1332 self.r128_whitelist = self.config["r128"].as_str_seq()
1333
1334 try:
1335 self.backend_instance = BACKENDS[self.backend_name](
1336 self.config, self._log
1337 )
1338 except (ReplayGainError, FatalReplayGainError) as e:
1339 raise UserError(f"replaygain initialization failed: {e}")
1340
1341 def should_use_r128(self, item: Item) -> bool:
1342 """Checks the plugin setting to decide whether the calculation
1343 should be done using the EBU R128 standard and use R128_ tags instead.
1344 """
1345 return item.format in self.r128_whitelist
1346
1347 @staticmethod
1348 def has_r128_track_data(item: Item) -> bool:
1349 return item.r128_track_gain is not None
1350
1351 @staticmethod
1352 def has_rg_track_data(item: Item) -> bool:
1353 return item.rg_track_gain is not None and item.rg_track_peak is not None
1354
1355 def track_requires_gain(self, item: Item) -> bool:
1356 if self.should_use_r128(item):
1357 if not self.has_r128_track_data(item):
1358 return True
1359 else:
1360 if not self.has_rg_track_data(item):
1361 return True
1362
1363 return False
1364
1365 @staticmethod
1366 def has_r128_album_data(item: Item) -> bool:
1367 return (
1368 item.r128_track_gain is not None
1369 and item.r128_album_gain is not None
1370 )
1371
1372 @staticmethod
1373 def has_rg_album_data(item: Item) -> bool:
1374 return item.rg_album_gain is not None and item.rg_album_peak is not None
1375
1376 def album_requires_gain(self, album: Album) -> bool:
1377 # Skip calculating gain only when *all* files don't need
1378 # recalculation. This way, if any file among an album's tracks
1379 # needs recalculation, we still get an accurate album gain
1380 # value.
1381 for item in album.items():
1382 if self.should_use_r128(item):
1383 if not self.has_r128_album_data(item):
1384 return True
1385 else:
1386 if not self.has_rg_album_data(item):
1387 return True
1388
1389 return False
1390
1391 def create_task(
1392 self, items: Sequence[Item], use_r128: bool, album: Album | None = None
1393 ) -> RgTask:
1394 if use_r128:
1395 return R128Task(
1396 items,
1397 album,
1398 self.config["r128_targetlevel"].as_number(),
1399 self.backend_instance.NAME,
1400 self._log,
1401 )
1402 return RgTask(
1403 items,
1404 album,
1405 self.config["targetlevel"].as_number(),
1406 self.peak_method,
1407 self.backend_instance.NAME,
1408 self._log,
1409 )
1410
1411 def handle_album(
1412 self, album: Album, write: bool, force: bool = False
1413 ) -> None:
1414 """Compute album and track replay gain store it in all of the
1415 album's items.
1416
1417 If ``write`` is truthy then ``item.write()`` is called for each
1418 item. If replay gain information is already present in all
1419 items, nothing is done.
1420 """
1421 if not force and not self.album_requires_gain(album):
1422 self._log.info("Skipping album {}", album)
1423 return
1424
1425 items_iter = iter(album.items())
1426 use_r128 = self.should_use_r128(next(items_iter))
1427 if any(use_r128 != self.should_use_r128(i) for i in items_iter):
1428 self._log.error(
1429 "Cannot calculate gain for album {} (incompatible formats)",
1430 album,
1431 )
1432 return
1433
1434 self._log.info("analyzing {}", album)
1435
1436 discs: dict[int, list[Item]] = {}
1437 if self.config["per_disc"].get(bool):
1438 for item in album.items():
1439 if discs.get(item.disc) is None:
1440 discs[item.disc] = []
1441 discs[item.disc].append(item)
1442 else:
1443 discs[1] = list(album.items())
1444
1445 def store_cb(task: RgTask) -> None:
1446 task.store(write)
1447
1448 for discnumber, items in discs.items():
1449 task = self.create_task(items, use_r128, album=album)
1450 try:
1451 self._apply(
1452 self.backend_instance.compute_album_gain,
1453 args=[task],
1454 kwds={},
1455 callback=store_cb,
1456 )
1457 except ReplayGainError as e:
1458 self._log.info("ReplayGain error: {}", e)
1459 except FatalReplayGainError as e:
1460 raise UserError(f"Fatal replay gain error: {e}")
1461
1462 def handle_track(
1463 self, item: Item, write: bool, force: bool = False
1464 ) -> None:
1465 """Compute track replay gain and store it in the item.
1466
1467 If ``write`` is truthy then ``item.write()`` is called to write
1468 the data to disk. If replay gain information is already present
1469 in the item, nothing is done.
1470 """
1471 if not force and not self.track_requires_gain(item):
1472 self._log.info("Skipping track {}", item)
1473 return
1474
1475 use_r128 = self.should_use_r128(item)
1476
1477 def store_cb(task: RgTask) -> None:
1478 task.store(write)
1479
1480 task = self.create_task([item], use_r128)
1481 try:
1482 self._apply(
1483 self.backend_instance.compute_track_gain,
1484 args=[task],
1485 kwds={},
1486 callback=store_cb,
1487 )
1488 except ReplayGainError as e:
1489 self._log.info("ReplayGain error: {}", e)
1490 except FatalReplayGainError as e:
1491 raise UserError(f"Fatal replay gain error: {e}")
1492
1493 def open_pool(self, threads: int) -> None:
1494 """Open a `ThreadPool` instance in `self.pool`"""
1495 if self.pool is None and self.backend_instance.do_parallel:
1496 self.pool = ThreadPool(threads)
1497 self.exc_queue: queue.Queue[BaseException] = queue.Queue()
1498
1499 signal.signal(signal.SIGINT, self._interrupt)
1500
1501 self.exc_watcher = ExceptionWatcher(
1502 self.exc_queue, # threads push exceptions here
1503 self.terminate_pool, # abort once an exception occurs
1504 )
1505 self.exc_watcher.start()
1506
1507 def _apply(
1508 self,
1509 func: Callable[..., AnyRgTask],
1510 args: Sequence[RgTask],
1511 kwds: JSONDict,
1512 callback: Callable[[AnyRgTask], Any],
1513 ) -> None:
1514 if self.pool is not None:
1515 # Apply the caller's context to both the worker and its callbacks
1516 # so lazy path expansion keeps the library root in pool threads.
1517 ctx = contextvars.copy_context()
1518
1519 def handle_exc(exc: BaseException) -> None:
1520 """Handle exceptions in the async work."""
1521 if isinstance(exc, ReplayGainError):
1522 self._log.info(exc.args[0]) # Log non-fatal exceptions.
1523 else:
1524 self.exc_queue.put(exc)
1525
1526 def run_func() -> Any:
1527 return ctx.run(func, *args, **kwds)
1528
1529 def run_callback(task: AnyRgTask) -> Any:
1530 return ctx.run(callback, task)
1531
1532 def run_handle_exc(exc: BaseException) -> Any:
1533 return ctx.run(handle_exc, exc)
1534
1535 self.pool.apply_async(
1536 run_func, callback=run_callback, error_callback=run_handle_exc
1537 )
1538 else:
1539 callback(func(*args, **kwds))
1540
1541 def terminate_pool(self) -> None:
1542 """Forcibly terminate the `ThreadPool` instance in `self.pool`
1543
1544 Sends SIGTERM to all processes.
1545 """
1546 if self.pool is not None:
1547 self.pool.terminate()
1548 self.pool.join()
1549 # Terminating the processes leaves the ExceptionWatcher's queues
1550 # in an unknown state, so don't wait for it.
1551 # self.exc_watcher.join()
1552 self.pool = None
1553
1554 def _interrupt(self, signal: int, frame: FrameType | None) -> None:
1555 try:
1556 self._log.info("interrupted")
1557 self.terminate_pool()
1558 sys.exit(0)
1559 except SystemExit:
1560 # Silence raised SystemExit ~ exit(0)
1561 pass
1562
1563 def close_pool(self) -> None:
1564 """Regularly close the `ThreadPool` instance in `self.pool`."""
1565 if self.pool is not None:
1566 self.pool.close()
1567 self.pool.join()
1568 self.exc_watcher.join()
1569 self.pool = None
1570
1571 def import_begin(self, session: ImportSession) -> None:
1572 """Handle `import_begin` event -> open pool"""
1573 threads: int = self.config["threads"].get(int)
1574
1575 if (
1576 self.config["parallel_on_import"]
1577 and self.config["auto"]
1578 and threads
1579 ):
1580 self.open_pool(threads)
1581
1582 def import_end(self, lib: Library, paths: list[bytes]) -> None:
1583 """Handle `import` event -> close pool"""
1584 self.close_pool()
1585
1586 def imported(self, session: ImportSession, task: ImportTask) -> None:
1587 """Add replay gain info to items or albums of ``task``."""
1588 if self.config["auto"]:
1589 if task.is_album:
1590 self.handle_album(task.album, False, self.force_on_import)
1591 else:
1592 # Should be a SingletonImportTask
1593 assert hasattr(task, "item")
1594 self.handle_track(task.item, False, self.force_on_import)
1595
1596 def command_func(
1597 self, lib: Library, opts: ReplayGainCLIOpts, args: list[str]
1598 ) -> None:
1599 try:
1600 write = ui.should_write(opts.write)
1601 force = opts.force
1602
1603 # Bypass self.open_pool() if called with `--threads 0`
1604 if opts.threads != 0:
1605 threads: int = opts.threads or self.config["threads"].get(int)
1606 self.open_pool(threads)
1607
1608 if opts.album:
1609 albums = lib.albums(args)
1610 self._log.info(
1611 f"Analyzing {len(albums)} albums ~"
1612 f" {self.backend_name} backend..."
1613 )
1614 for album in albums:
1615 self.handle_album(album, write, force)
1616 else:
1617 items = lib.items(args)
1618 self._log.info(
1619 f"Analyzing {len(items)} tracks ~"
1620 f" {self.backend_name} backend..."
1621 )
1622 for item in items:
1623 self.handle_track(item, write, force)
1624
1625 self.close_pool()
1626 except (SystemExit, KeyboardInterrupt):
1627 # Silence interrupt exceptions
1628 pass
1629
1630 def commands(self) -> list[ui.Subcommand]:
1631 """Return the "replaygain" ui subcommand."""
1632 cmd = ui.Subcommand("replaygain", help="analyze for ReplayGain")
1633 cmd.parser.add_album_option()
1634 cmd.parser.add_option(
1635 "-t",
1636 "--threads",
1637 dest="threads",
1638 type=int,
1639 help=(
1640 "change the number of threads, defaults to maximum available"
1641 " processors"
1642 ),
1643 )
1644 cmd.parser.add_option(
1645 "-f",
1646 "--force",
1647 dest="force",
1648 action="store_true",
1649 default=False,
1650 help=(
1651 "analyze all files, including those that already have"
1652 " ReplayGain metadata"
1653 ),
1654 )
1655 cmd.parser.add_option(
1656 "-w",
1657 "--write",
1658 default=None,
1659 action="store_true",
1660 help="write new metadata to files' tags",
1661 )
1662 cmd.parser.add_option(
1663 "-W",
1664 "--nowrite",
1665 dest="write",
1666 action="store_false",
1667 help="don't write metadata (opposite of -w)",
1668 )
1669 cmd.func = self.command_func
1670 return [cmd]