audio-transcode-watcher 0.6.2__tar.gz → 0.7.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/CHANGELOG.md +7 -0
  2. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/PKG-INFO +3 -2
  3. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/README.md +2 -1
  4. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/config.example.yaml +7 -1
  5. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/docs/ROADMAP.md +3 -2
  6. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/docs/configuration.md +28 -0
  7. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/docs/getting-started.md +2 -2
  8. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/docs/how-it-works.md +4 -0
  9. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/pyproject.toml +1 -1
  10. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/src/audio_transcode_watcher/__init__.py +1 -1
  11. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/src/audio_transcode_watcher/config.py +8 -0
  12. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/src/audio_transcode_watcher/main.py +3 -0
  13. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/src/audio_transcode_watcher/manifest.py +34 -0
  14. audio_transcode_watcher-0.7.0/src/audio_transcode_watcher/replaygain.py +312 -0
  15. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/src/audio_transcode_watcher/sync.py +73 -1
  16. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/src/audio_transcode_watcher/watcher.py +4 -0
  17. audio_transcode_watcher-0.7.0/tests/test_replaygain.py +521 -0
  18. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/uv.lock +1 -1
  19. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.beads/.gitignore +0 -0
  20. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.beads/README.md +0 -0
  21. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.beads/config.yaml +0 -0
  22. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.beads/hooks/commit-msg +0 -0
  23. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.beads/hooks/post-checkout +0 -0
  24. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.beads/hooks/post-merge +0 -0
  25. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.beads/hooks/pre-commit +0 -0
  26. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.beads/hooks/pre-push +0 -0
  27. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.beads/hooks/prepare-commit-msg +0 -0
  28. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.beads/metadata.json +0 -0
  29. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.claude/settings.json +0 -0
  30. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.coderabbit.yaml +0 -0
  31. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.github/FUNDING.yml +0 -0
  32. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.github/dependabot.yml +0 -0
  33. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.github/workflows/dockerhub-description.yml +0 -0
  34. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.github/workflows/release.yml +0 -0
  35. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.github/workflows/stale.yml +0 -0
  36. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.github/workflows/tests.yml +0 -0
  37. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/.gitignore +0 -0
  38. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/AGENTS.md +0 -0
  39. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/CLAUDE.md +0 -0
  40. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/Dockerfile +0 -0
  41. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/LICENSE +0 -0
  42. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/SECURITY.md +0 -0
  43. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/codecov.yml +0 -0
  44. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/docs/development.md +0 -0
  45. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/docs/images/banner.svg +0 -0
  46. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/docs/images/icon.png +0 -0
  47. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/docs/images/icon.svg +0 -0
  48. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/docs/images/social-preview.png +0 -0
  49. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/docs/usage.md +0 -0
  50. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/src/audio_transcode_watcher/encoder.py +0 -0
  51. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/src/audio_transcode_watcher/lyrics.py +0 -0
  52. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/src/audio_transcode_watcher/utils.py +0 -0
  53. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/tests/__init__.py +0 -0
  54. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/tests/conftest.py +0 -0
  55. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/tests/test_config.py +0 -0
  56. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/tests/test_encoder.py +0 -0
  57. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/tests/test_lyrics.py +0 -0
  58. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/tests/test_main.py +0 -0
  59. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/tests/test_manifest.py +0 -0
  60. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/tests/test_sync.py +0 -0
  61. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/tests/test_utils.py +0 -0
  62. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/tests/test_watcher.py +0 -0
  63. {audio_transcode_watcher-0.6.2 → audio_transcode_watcher-0.7.0}/tools/verify_sync.py +0 -0
@@ -2,6 +2,12 @@
2
2
 
3
3
  All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/).
4
4
 
5
+ ## [0.7.0] - 2026-10-06
6
+
7
+ ### Added
8
+
9
+ - `replaygain: true` gives the whole library even volume. It is a top-level key and off by default. The watcher measures every source that has no `REPLAYGAIN_TRACK_GAIN` tag with FFmpeg's EBU R128 filter. It writes ReplayGain 2.0 track gain, -18 LUFS minus the integrated loudness, like `-6.32 dB`, and the true peak as a linear value, like `0.988553`, into the source file in its own tag format. That means Vorbis comments for FLAC, Ogg and Opus, `TXXX` frames for MP3, WAV and AIFF, freeform atoms for M4A, and APEv2 for APE, WavPack and TAK. Every output gets the same two tags. New encodes carry them, existing outputs get them in place without a re-encode, and lossy copies are copied again. The first sync covers the existing library, and every file added later gets the same treatment. The watcher writes no album gain, because the library may be one flat folder. It logs and skips a file it cannot measure. It also recognises its own tag writes and updates the manifest after each one, so tagging a source never re-encodes it or rebuilds a `tolerant` copy. See [ReplayGain](docs/configuration.md#replaygain).
10
+
5
11
  ## [0.6.2] - 2026-10-05
6
12
 
7
13
  ### Added
@@ -59,6 +65,7 @@ All notable changes to this project are documented here. The format follows [Kee
59
65
  - Lossy copies are written through a temp file and renamed, like encodes, so a half-written copy is never visible.
60
66
  - `force_reencode: true` purges the outputs once at startup. It used to purge them again on every periodic sync, which re-encoded the whole library every five minutes.
61
67
 
68
+ [0.7.0]: https://github.com/GeiserX/audio-transcode-watcher/releases/tag/v0.7.0
62
69
  [0.6.2]: https://github.com/GeiserX/audio-transcode-watcher/releases/tag/v0.6.2
63
70
  [0.6.1]: https://github.com/GeiserX/audio-transcode-watcher/releases/tag/v0.6.1
64
71
  [0.6.0]: https://github.com/GeiserX/audio-transcode-watcher/releases/tag/v0.6.0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: audio-transcode-watcher
3
- Version: 0.6.2
3
+ Version: 0.7.0
4
4
  Summary: Watch a source folder and automatically transcode audio files to multiple formats
5
5
  Project-URL: Homepage, https://github.com/GeiserX/audio-transcode-watcher
6
6
  Project-URL: Repository, https://github.com/GeiserX/audio-transcode-watcher
@@ -54,6 +54,7 @@ Keep one library in several formats: lossless for the archive, lossy for phones
54
54
  - Copies lossy sources (MP3, M4A, Ogg, Opus, WMA) unchanged instead of inflating them into a lossless output.
55
55
  - Fails loudly on a source that does not decode cleanly, and writes no output for it.
56
56
  - Keeps ReplayGain, MusicBrainz ids, ISRC, label and sort tags in ALAC and AAC copies.
57
+ - Optionally measures every file and writes ReplayGain 2.0 track gain into the source and every output, so the whole library plays at one volume.
57
58
  - Fetches synced `.lrc` lyrics, and writes nothing when no real lyrics are found.
58
59
  - Embeds cover art if you want it.
59
60
  - Writes atomically and removes orphaned outputs, but never deletes anything when a folder looks empty.
@@ -66,7 +67,7 @@ Keep one library in several formats: lossless for the archive, lossy for phones
66
67
  curl -fsSL -o config.yaml https://raw.githubusercontent.com/GeiserX/audio-transcode-watcher/main/config.example.yaml
67
68
  docker run -d --name audio_transcoder -e CONFIG_FILE=/app/config.yaml \
68
69
  -v ./config.yaml:/app/config.yaml:ro -v /path/to/flac:/music/flac:ro -v /path/to/mp3:/music/mp3 \
69
- drumsergio/audio-transcoder:0.6.2
70
+ drumsergio/audio-transcoder:0.7.0
70
71
  ```
71
72
 
72
73
  Edit `config.yaml` first so its outputs match the folders you mount; the example writes ALAC, MP3 and AAC. [Getting started](https://github.com/GeiserX/audio-transcode-watcher/blob/main/docs/getting-started.md) has Docker Compose and the full `docker run`.
@@ -23,6 +23,7 @@ Keep one library in several formats: lossless for the archive, lossy for phones
23
23
  - Copies lossy sources (MP3, M4A, Ogg, Opus, WMA) unchanged instead of inflating them into a lossless output.
24
24
  - Fails loudly on a source that does not decode cleanly, and writes no output for it.
25
25
  - Keeps ReplayGain, MusicBrainz ids, ISRC, label and sort tags in ALAC and AAC copies.
26
+ - Optionally measures every file and writes ReplayGain 2.0 track gain into the source and every output, so the whole library plays at one volume.
26
27
  - Fetches synced `.lrc` lyrics, and writes nothing when no real lyrics are found.
27
28
  - Embeds cover art if you want it.
28
29
  - Writes atomically and removes orphaned outputs, but never deletes anything when a folder looks empty.
@@ -35,7 +36,7 @@ Keep one library in several formats: lossless for the archive, lossy for phones
35
36
  curl -fsSL -o config.yaml https://raw.githubusercontent.com/GeiserX/audio-transcode-watcher/main/config.example.yaml
36
37
  docker run -d --name audio_transcoder -e CONFIG_FILE=/app/config.yaml \
37
38
  -v ./config.yaml:/app/config.yaml:ro -v /path/to/flac:/music/flac:ro -v /path/to/mp3:/music/mp3 \
38
- drumsergio/audio-transcoder:0.6.2
39
+ drumsergio/audio-transcoder:0.7.0
39
40
  ```
40
41
 
41
42
  Edit `config.yaml` first so its outputs match the folders you mount; the example writes ALAC, MP3 and AAC. [Getting started](https://github.com/GeiserX/audio-transcode-watcher/blob/main/docs/getting-started.md) has Docker Compose and the full `docker run`.
@@ -1,4 +1,4 @@
1
- # Audio Transcode Watcher Configuration (0.6.2)
1
+ # Audio Transcode Watcher Configuration (0.7.0)
2
2
  # ======================================
3
3
  #
4
4
  # This configuration file defines the source folder and output destinations
@@ -41,6 +41,12 @@ outputs:
41
41
  channels: 2
42
42
  max_sample_rate: 48000
43
43
 
44
+ # Even volume across the library (default: false). Every source without a
45
+ # REPLAYGAIN_TRACK_GAIN tag is measured (EBU R128) and gets ReplayGain 2.0
46
+ # track gain and peak tags, written into the source file itself. Every output
47
+ # gets the same tags, without being re-encoded. No album gain is written.
48
+ replaygain: false
49
+
44
50
  # Optional settings
45
51
  settings:
46
52
  # Set to true to delete all outputs and re-encode everything on startup
@@ -1,6 +1,6 @@
1
1
  # Roadmap
2
2
 
3
- Current version: **0.6.2**
3
+ Current version: **0.7.0**
4
4
 
5
5
  ## Completed
6
6
 
@@ -14,8 +14,9 @@ Current version: **0.6.2**
14
14
  - **Lossy sources copied, not inflated**, corrupt sources fail loudly, ReplayGain and MusicBrainz tags kept in M4A outputs, configurable periodic sync (v0.6.0)
15
15
  - **Portable AAC**: stereo downmix and a 48 kHz cap for AAC outputs, per-output `channels` and `max_sample_rate` (v0.6.1)
16
16
  - **Damaged sources**: `corrupt_source: encode_anyway` makes a concealed copy instead of none (v0.6.2)
17
+ - **Even volume**: `replaygain: true` writes ReplayGain 2.0 track tags into every source and output (v0.7.0)
17
18
 
18
- ## v0.7.0 -- Quality of Life
19
+ ## v0.7.x -- Quality of Life
19
20
 
20
21
  - [ ] **Progress reporting during initial sync**
21
22
  - Show file count progress (e.g. 42/500)
@@ -44,6 +44,9 @@ outputs:
44
44
  bitrate: 128k
45
45
  path: /music/opus
46
46
 
47
+ # Even volume: write ReplayGain 2.0 track tags (default: false)
48
+ replaygain: false
49
+
47
50
  # Optional settings
48
51
  settings:
49
52
  # Delete all outputs and re-encode on startup
@@ -84,6 +87,31 @@ Set it under `settings` for every output, or on one output to override, for exam
84
87
 
85
88
  Either way the source is remembered as failed, so the strict attempt is not repeated on every scan. Replacing the file with a clean copy (a new size or modification time) clears that, and the next scan rebuilds the tolerant copy with the strict encode.
86
89
 
90
+ ### ReplayGain
91
+
92
+ With `replaygain: true` at the top level of the config, every track plays at the same loudness in any player that reads ReplayGain tags, such as Navidrome and foobar2000:
93
+
94
+ ```yaml
95
+ replaygain: true
96
+ ```
97
+
98
+ For each source that has no `REPLAYGAIN_TRACK_GAIN` tag yet, the watcher measures its loudness with FFmpeg's EBU R128 filter and writes two tags into the source file:
99
+
100
+ - `REPLAYGAIN_TRACK_GAIN`: -18 LUFS minus the measured integrated loudness, for example `-6.32 dB`.
101
+ - `REPLAYGAIN_TRACK_PEAK`: the true peak as a linear value, for example `0.988553`.
102
+
103
+ They are written in the file's own tag format: Vorbis comments in FLAC, Ogg and Opus, `TXXX` frames in MP3, WAV and AIFF, freeform atoms in M4A, and APEv2 in APE, WavPack and TAK. An ID3v2.3 file stays at 2.3. The M4A atoms use the names Picard writes, such as `----:com.apple.iTunes:replaygain_track_gain`. Raw `.aac` and `.wma` sources are left alone. A source that already has a track gain from any tool is never measured again, and a silent file gets no tag.
104
+
105
+ Every output gets the same two tags. New encodes carry them from the source. The watcher writes them into outputs that already exist without re-encoding them, and copies lossy sources again so each copy stays identical to its source.
106
+
107
+ This applies to the whole library on the first sync after you turn it on, and then to every file that arrives. The first pass decodes each untagged source once, through the same `parallel_workers` as encoding, so a large library takes a while. The watcher logs and skips a file it cannot measure, and tries it again after the next restart.
108
+
109
+ The watcher writes no album gain. Album gain needs to know which files form an album, and a folder does not say that reliably. Many libraries are one flat folder.
110
+
111
+ Writing the tags changes the source file's size and modification time. The watcher recognises its own writes, so a tagged source is not treated as a new version and nothing is re-encoded. Other tools that watch the source folder, like a media server's library scan or a sync job, see the change once.
112
+
113
+ `replaygain` is also accepted under `settings`.
114
+
87
115
  `whisper_fallback` and `whisper_model` were removed in 0.6.0 along with the Whisper lyrics fallback. A config that still sets them loads, and the first load logs one warning that they are ignored.
88
116
 
89
117
  ## Source formats
@@ -29,7 +29,7 @@ outputs:
29
29
  ```yaml
30
30
  services:
31
31
  audio-transcoder:
32
- image: drumsergio/audio-transcoder:0.6.2
32
+ image: drumsergio/audio-transcoder:0.7.0
33
33
  container_name: audio_transcoder
34
34
  environment:
35
35
  - TZ=Europe/Madrid
@@ -60,6 +60,6 @@ docker run -d \
60
60
  -v /path/to/flac:/music/flac:ro \
61
61
  -v /path/to/mp3:/music/mp3 \
62
62
  --restart unless-stopped \
63
- drumsergio/audio-transcoder:0.6.2
63
+ drumsergio/audio-transcoder:0.7.0
64
64
  ```
65
65
 
@@ -19,6 +19,10 @@ Each output folder holds `.atw-manifest.json`, a map from each output file to th
19
19
 
20
20
  FFmpeg runs with `-xerror` and `-err_detect crccheck+explode`, so a frame whose checksum does not match stops the encode. If a source does not decode cleanly, the encode fails even when FFmpeg exits 0 but printed a decode error. The error is logged with the file name and no output is written, unless `corrupt_source: encode_anyway` is set; then the file is encoded once more with FFmpeg's error concealment and marked `tolerant` in the manifest (see [Damaged sources](configuration.md#damaged-sources)). The strict attempt is not repeated until the file's modification time changes, or the service restarts.
21
21
 
22
+ ## ReplayGain
23
+
24
+ With `replaygain: true`, each source is checked before its outputs are written. The watcher measures a source with no `REPLAYGAIN_TRACK_GAIN` tag with FFmpeg's `ebur128` filter and tags it in place before encoding, so new outputs carry the tags. It writes the tags into existing outputs that lack them and copies lossy copies again. Each source is checked once per run of the service, and again only when its size or modification time changes. After a tag write, the manifest rows that described the source or output as it was are updated to match, so a `tolerant` copy is not rebuilt, and the watcher ignores the file events its own write causes. See [ReplayGain](configuration.md#replaygain).
25
+
22
26
  ## Recursive Directory Support
23
27
 
24
28
  Source folder hierarchy is automatically mirrored in all outputs. Both flat and nested structures work out of the box -- no configuration needed.
@@ -5,7 +5,7 @@ build-backend = "hatchling.build"
5
5
  [project]
6
6
  name = "audio-transcode-watcher"
7
7
 
8
- version = "0.6.2"
8
+ version = "0.7.0"
9
9
 
10
10
  description = "Watch a source folder and automatically transcode audio files to multiple formats"
11
11
  readme = "README.md"
@@ -1,3 +1,3 @@
1
1
  """Audio Transcode Watcher - Automatic audio file transcoding."""
2
2
 
3
- __version__ = "0.6.2"
3
+ __version__ = "0.7.0"
@@ -143,12 +143,17 @@ class Config:
143
143
  fetch_lyrics: bool = True # Auto-fetch .lrc lyrics via syncedlyrics
144
144
  sync_interval_seconds: int = 300 # Seconds between periodic full syncs
145
145
  corrupt_source: str = "skip" # Default for outputs that don't set it
146
+ replaygain: bool = False # Write ReplayGain 2.0 track tags (top-level key)
146
147
 
147
148
  def __post_init__(self) -> None:
148
149
  """Validate configuration after initialization."""
149
150
  if not self.source_path:
150
151
  raise ValueError("source_path is required")
151
152
 
153
+ if not isinstance(self.replaygain, bool):
154
+ # ValueError, like every other config error, so main reports it.
155
+ raise ValueError("replaygain must be true or false") # noqa: TRY004
156
+
152
157
  _check_corrupt_source(self.corrupt_source, "settings.corrupt_source")
153
158
 
154
159
  interval = self.sync_interval_seconds
@@ -206,6 +211,9 @@ class Config:
206
211
  fetch_lyrics=settings.get("fetch_lyrics", True),
207
212
  sync_interval_seconds=settings.get("sync_interval_seconds", 300),
208
213
  corrupt_source=settings.get("corrupt_source", "skip"),
214
+ # Documented at the top level; also read under settings, where
215
+ # every other option lives, so either place works.
216
+ replaygain=data.get("replaygain", settings.get("replaygain", False)),
209
217
  )
210
218
 
211
219
  @classmethod
@@ -65,6 +65,9 @@ def main() -> int:
65
65
  output.path,
66
66
  )
67
67
 
68
+ if config.replaygain:
69
+ logger.info("ReplayGain: sources and outputs get track gain tags")
70
+
68
71
  # Perform initial sync
69
72
  initial_sync(config)
70
73
 
@@ -112,6 +112,40 @@ def output_matches(row: dict, out_path: str) -> bool:
112
112
  )
113
113
 
114
114
 
115
+ def restat(
116
+ root: str,
117
+ out_path: str,
118
+ before: os.stat_result,
119
+ source_path: str | None = None,
120
+ ) -> None:
121
+ """
122
+ Keep *out_path*'s row trusted after a file was edited in place.
123
+
124
+ A tag write changes a file's size and mtime. With *source_path*, the
125
+ edited file is the source: the row's source size and mtime are updated
126
+ if they matched *before*. Without it, the edited file is *out_path*
127
+ and its output size and mtime are updated the same way. A row that no
128
+ longer described the file before the edit is left alone.
129
+ """
130
+ edited = source_path or out_path
131
+ try:
132
+ st = os.stat(edited)
133
+ except OSError:
134
+ return
135
+ fields = ("size", "mtime") if source_path else ("output_size", "output_mtime")
136
+ with _lock:
137
+ row = _load(root).get(_key(root, out_path))
138
+ if not row:
139
+ return
140
+ if (row.get(fields[0]), row.get(fields[1])) != (
141
+ before.st_size,
142
+ before.st_mtime,
143
+ ):
144
+ return
145
+ row[fields[0]], row[fields[1]] = st.st_size, st.st_mtime
146
+ _dirty.add(root)
147
+
148
+
115
149
  def prune(root: str) -> int:
116
150
  """Drop rows whose output file is gone. Returns how many were dropped."""
117
151
  with _lock:
@@ -0,0 +1,312 @@
1
+ """ReplayGain 2.0 track tags.
2
+
3
+ A file is measured with FFmpeg's EBU R128 filter (``ebur128=peak=true``):
4
+
5
+ - ``REPLAYGAIN_TRACK_GAIN`` = -18 LUFS (the ReplayGain 2.0 reference) minus
6
+ the integrated loudness, written like ``-6.32 dB``;
7
+ - ``REPLAYGAIN_TRACK_PEAK`` = the true peak as a linear value, ``0.988553``.
8
+
9
+ Album gain is not computed: an album is not something a folder of files can
10
+ be trusted to describe.
11
+
12
+ The tags are written in place with mutagen, in the file's own tag format:
13
+ Vorbis comments (FLAC, Ogg, Opus), ID3 ``TXXX`` frames (MP3, WAV, AIFF),
14
+ MP4 freeform atoms under the names Picard uses (M4A) and APEv2 (APE,
15
+ WavPack, TAK). Other formats (raw AAC, WMA) are left alone.
16
+
17
+ A tag write changes the file's size and modification time. Writes made
18
+ here are remembered, so the watcher can tell them from a real change and
19
+ does not re-encode the file because of its own edit.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import logging
25
+ import math
26
+ import os
27
+ import re
28
+ import subprocess
29
+ import threading
30
+
31
+ import mutagen
32
+ from mutagen._vorbis import VCommentDict
33
+ from mutagen.apev2 import APEv2
34
+ from mutagen.id3 import ID3, TXXX, Encoding
35
+ from mutagen.mp4 import MP4FreeForm, MP4Tags
36
+
37
+ from .utils import nfc_path
38
+
39
+ logger = logging.getLogger(__name__)
40
+
41
+ REFERENCE_LUFS = -18.0
42
+ GAIN_TAG = "REPLAYGAIN_TRACK_GAIN"
43
+ PEAK_TAG = "REPLAYGAIN_TRACK_PEAK"
44
+ _TAGS = (GAIN_TAG, PEAK_TAG)
45
+
46
+ # Integrated loudness at or below this means the gate found nothing to
47
+ # measure (digital silence); such a file gets no tag.
48
+ SILENCE_LUFS = -70.0
49
+
50
+ # A measurement that runs longer than this (seconds) is killed and skipped.
51
+ MEASURE_TIMEOUT = 1800
52
+
53
+ _MP4_FREEFORM = "----:com.apple.iTunes:"
54
+
55
+ _INTEGRATED_RE = re.compile(r"I:\s+(-?(?:[\d.]+|inf))\s+LUFS")
56
+ _PEAK_RE = re.compile(r"Peak:\s+(-?(?:[\d.]+|inf))\s+dBFS")
57
+
58
+ _lock = threading.Lock()
59
+ # Source path -> (size, mtime_ns) when it was last checked, so a periodic
60
+ # sync does not reread every file's tags. Lives for the process lifetime.
61
+ _checked: dict[str, tuple[int, int]] = {}
62
+ # Path -> (size, mtime_ns) after a tag write made here; None while the
63
+ # write is still running.
64
+ _own_writes: dict[str, tuple[int, int] | None] = {}
65
+
66
+
67
+ def _signature(path: str) -> tuple[int, int] | None:
68
+ try:
69
+ st = os.stat(path)
70
+ except OSError:
71
+ return None
72
+ return st.st_size, st.st_mtime_ns
73
+
74
+
75
+ def measure(path: str) -> tuple[float, float] | None:
76
+ """Return (integrated loudness in LUFS, true peak in dBTP), or None."""
77
+ cmd = [
78
+ "ffmpeg",
79
+ "-nostdin",
80
+ "-hide_banner",
81
+ "-nostats",
82
+ "-i",
83
+ path,
84
+ "-map",
85
+ "0:a:0",
86
+ # framelog=verbose keeps the per-frame lines out of the info log,
87
+ # so stderr holds only the summary.
88
+ "-af",
89
+ "ebur128=peak=true:framelog=verbose",
90
+ "-f",
91
+ "null",
92
+ "-",
93
+ ]
94
+ try:
95
+ proc = subprocess.run(
96
+ cmd, capture_output=True, timeout=MEASURE_TIMEOUT, check=False
97
+ )
98
+ except subprocess.TimeoutExpired:
99
+ logger.warning("ReplayGain: measuring %s timed out", path)
100
+ return None
101
+ except OSError as e:
102
+ logger.warning("ReplayGain: could not run ffmpeg for %s: %s", path, e)
103
+ return None
104
+ stderr = proc.stderr.decode("utf-8", errors="ignore") if proc.stderr else ""
105
+ if proc.returncode != 0 or "Summary:" not in stderr:
106
+ last = (stderr.strip().splitlines() or [""])[-1]
107
+ logger.warning(
108
+ "ReplayGain: could not measure %s (rc=%s): %s", path, proc.returncode, last
109
+ )
110
+ return None
111
+ summary = stderr.rsplit("Summary:", 1)[1]
112
+ integrated = _INTEGRATED_RE.search(summary)
113
+ peak = _PEAK_RE.search(summary)
114
+ if not integrated or not peak:
115
+ logger.warning("ReplayGain: no loudness summary for %s", path)
116
+ return None
117
+ return float(integrated.group(1)), float(peak.group(1))
118
+
119
+
120
+ def track_values(integrated_lufs: float, peak_dbtp: float) -> dict[str, str] | None:
121
+ """The two tag values for a measurement, or None for silence."""
122
+ if not math.isfinite(integrated_lufs) or integrated_lufs <= SILENCE_LUFS:
123
+ return None
124
+ gain = REFERENCE_LUFS - integrated_lufs
125
+ peak = 10 ** (peak_dbtp / 20) if math.isfinite(peak_dbtp) else 0.0
126
+ return {GAIN_TAG: f"{gain:.2f} dB", PEAK_TAG: f"{peak:.6f}"}
127
+
128
+
129
+ def _writable(tags) -> bool:
130
+ return isinstance(tags, (ID3, MP4Tags, VCommentDict, APEv2))
131
+
132
+
133
+ def _read(tags) -> dict[str, str]:
134
+ """REPLAYGAIN_TRACK_GAIN and _PEAK from *tags*, whatever the format or case."""
135
+ found: dict[str, str] = {}
136
+ if isinstance(tags, ID3):
137
+ for frame in tags.getall("TXXX"):
138
+ name = frame.desc.upper()
139
+ if name in _TAGS and frame.text:
140
+ found[name] = str(frame.text[0])
141
+ elif isinstance(tags, MP4Tags):
142
+ for key, values in tags.items():
143
+ if not key.startswith("----:") or not values:
144
+ continue
145
+ name = key.rsplit(":", 1)[-1].upper()
146
+ if name in _TAGS:
147
+ value = values[0]
148
+ if isinstance(value, bytes):
149
+ value = value.decode("utf-8", "ignore")
150
+ found[name] = str(value)
151
+ else:
152
+ for key, value in tags.items():
153
+ name = str(key).upper()
154
+ if name in _TAGS:
155
+ if isinstance(value, list):
156
+ value = value[0] if value else ""
157
+ found[name] = str(value)
158
+ return {k: v.strip() for k, v in found.items() if v.strip()}
159
+
160
+
161
+ def read_track_tags(path: str) -> dict[str, str]:
162
+ """The ReplayGain track tags *path* already has (empty if none or unreadable)."""
163
+ audio = mutagen.File(path)
164
+ if audio is None or audio.tags is None:
165
+ return {}
166
+ return _read(audio.tags)
167
+
168
+
169
+ def _write(path: str, values: dict[str, str]) -> bool:
170
+ """Write *values* into *path* in its own tag format. False if unsupported."""
171
+ audio = mutagen.File(path)
172
+ if audio is None:
173
+ return False
174
+ if audio.tags is None:
175
+ try:
176
+ audio.add_tags()
177
+ except Exception: # noqa: BLE001 - the format takes no tags
178
+ return False
179
+ tags = audio.tags
180
+ if isinstance(tags, ID3):
181
+ for name, value in values.items():
182
+ for frame in tags.getall("TXXX"):
183
+ if frame.desc.upper() == name:
184
+ tags.delall(frame.HashKey)
185
+ tags.add(TXXX(encoding=Encoding.LATIN1, desc=name, text=[value]))
186
+ # Keep an ID3v2.3 file at 2.3: some car stereos read nothing newer.
187
+ audio.save(v2_version=3 if tags.version[:2] == (2, 3) else 4)
188
+ elif isinstance(tags, MP4Tags):
189
+ for name, value in values.items():
190
+ for key in [k for k in tags if k.startswith("----:")]:
191
+ if key.rsplit(":", 1)[-1].upper() == name:
192
+ del tags[key]
193
+ tags[_MP4_FREEFORM + name.lower()] = [MP4FreeForm(value.encode("utf-8"))]
194
+ audio.save()
195
+ elif isinstance(tags, VCommentDict):
196
+ for name, value in values.items():
197
+ tags[name] = [value]
198
+ audio.save()
199
+ elif isinstance(tags, APEv2):
200
+ for name, value in values.items():
201
+ tags[name] = value
202
+ audio.save()
203
+ else:
204
+ return False
205
+ return True
206
+
207
+
208
+ def write_track_tags(path: str, values: dict[str, str]) -> bool:
209
+ """Write *values* into *path*, remembered as our own edit. False if unsupported."""
210
+ path = nfc_path(path)
211
+ with _lock:
212
+ _own_writes[path] = None
213
+ ok = False
214
+ try:
215
+ ok = _write(path, values)
216
+ finally:
217
+ signature = _signature(path) if ok else None
218
+ with _lock:
219
+ if signature is None:
220
+ _own_writes.pop(path, None)
221
+ else:
222
+ _own_writes[path] = signature
223
+ return ok
224
+
225
+
226
+ def is_own_write(path: str) -> bool:
227
+ """True if *path* is as a tag write made here left it (or one is running)."""
228
+ path = nfc_path(path)
229
+ with _lock:
230
+ if path not in _own_writes:
231
+ return False
232
+ expected = _own_writes[path]
233
+ if expected is None:
234
+ return True
235
+ if _signature(path) == expected:
236
+ return True
237
+ with _lock:
238
+ if _own_writes.get(path) == expected:
239
+ del _own_writes[path]
240
+ return False
241
+
242
+
243
+ def tag_source(path: str) -> tuple[os.stat_result, os.stat_result] | None:
244
+ """
245
+ Measure *path* and write its track tags, unless it already has a gain.
246
+
247
+ Returns (stat before, stat after) when the file was written, else None.
248
+ A file that cannot be read, measured or tagged is logged and skipped.
249
+ """
250
+ try:
251
+ audio = mutagen.File(path)
252
+ except Exception as e: # noqa: BLE001 - unreadable means skip
253
+ logger.warning("ReplayGain: cannot read tags of %s: %s", path, e)
254
+ return None
255
+ if audio is None:
256
+ logger.debug("ReplayGain: unknown format, skipping %s", path)
257
+ return None
258
+ if audio.tags is not None and GAIN_TAG in _read(audio.tags):
259
+ return None
260
+ if audio.tags is None:
261
+ try:
262
+ audio.add_tags()
263
+ except Exception: # noqa: BLE001 - the format takes no tags
264
+ logger.debug("ReplayGain: %s cannot hold tags, skipping", path)
265
+ return None
266
+ if not _writable(audio.tags):
267
+ logger.debug("ReplayGain: tag format of %s is not supported", path)
268
+ return None
269
+
270
+ measured = measure(path)
271
+ if measured is None:
272
+ return None
273
+ values = track_values(*measured)
274
+ if values is None:
275
+ logger.info("ReplayGain: %s is silent, no tag written", path)
276
+ return None
277
+
278
+ try:
279
+ before = os.stat(path)
280
+ if not write_track_tags(path, values):
281
+ return None
282
+ after = os.stat(path)
283
+ except Exception as e: # noqa: BLE001 - a failed write is logged, never fatal
284
+ logger.warning("ReplayGain: could not tag %s: %s", path, e)
285
+ return None
286
+ logger.info(
287
+ "♫ ReplayGain %s: gain %s, peak %s", path, values[GAIN_TAG], values[PEAK_TAG]
288
+ )
289
+ return before, after
290
+
291
+
292
+ def is_checked(path: str) -> bool:
293
+ """True if *path* was checked and has not changed since."""
294
+ with _lock:
295
+ recorded = _checked.get(path)
296
+ return recorded is not None and recorded == _signature(path)
297
+
298
+
299
+ def mark_checked(path: str) -> None:
300
+ """Remember that *path* and its outputs carry their tags as of now."""
301
+ signature = _signature(path)
302
+ with _lock:
303
+ if signature is None:
304
+ _checked.pop(path, None)
305
+ else:
306
+ _checked[path] = signature
307
+
308
+
309
+ def forget(path: str) -> None:
310
+ """Check *path* and its outputs again on the next pass."""
311
+ with _lock:
312
+ _checked.pop(path, None)