trueflac 0.1.0__py3-none-any.whl

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.
trueflac/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """Detect FLAC files made from a lossy source."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from .analysis import analyze
6
+ from .verdict import Cancelled, Clue, Status, Verdict, describe
7
+
8
+ try:
9
+ __version__ = version("trueflac")
10
+ except PackageNotFoundError: # running from a source tree that is not installed
11
+ __version__ = "0.0.0"
12
+
13
+ __all__ = ["Cancelled", "Clue", "Status", "Verdict", "__version__", "analyze", "describe"]
trueflac/analysis.py ADDED
@@ -0,0 +1,242 @@
1
+ """Spectral analysis of a lossless file (cutoff), then codec grid traces (grid.py).
2
+
3
+ v0: look for a sharp low-pass ("cliff") in the average spectrum, measured on a
4
+ few seconds taken at several points of the track. Lossy encoders cut the
5
+ highs (LAME 128k ~17 kHz, 192k ~19 kHz, 320k ~20 kHz); a CD master usually
6
+ goes on close to 22 kHz, or fades out slowly.
7
+
8
+ The answer is "suspect", never "fake": old recordings and filtered masters
9
+ can show a cutoff too.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Callable
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+ import soundfile as sf
19
+
20
+ from .grid import GridTrace, grid_trace
21
+ from .mp3grid import mp3_trace
22
+ from .verdict import Cancelled, Clue, Status, Verdict
23
+
24
+ NFFT = 8192
25
+ SEGMENTS = 8
26
+ SEGMENT_SECONDS = 4.0
27
+ SILENT_RMS = 1e-4
28
+
29
+ # A cliff: the level falls by at least CLIFF_DB within CLIFF_WIDTH_HZ and
30
+ # stays down up to Nyquist.
31
+ CLIFF_DB = 30.0
32
+ CLIFF_WIDTH_HZ = 600.0
33
+ FLOOR_FLATNESS_DB = 12.0
34
+ # Below this share of Nyquist, a cut is suspect (20.3 kHz at 44.1 kHz). Bench
35
+ # MP3 320 and Opus cut at 20.0-20.2 kHz; a real album (Tate McRae, THINK LATER)
36
+ # has mastering cliffs at 20.4-21 kHz: give those the benefit of the doubt.
37
+ SUSPECT_RATIO = 0.92
38
+ SEARCH_FROM_HZ = 8000.0
39
+ CD_NYQUIST = 22050.0
40
+ # Dead band: within DEAD_MARGIN_DB of the rounding noise floor, with content at
41
+ # least DEAD_CONTENT_DB above it just below.
42
+ DEAD_MARGIN_DB = 3.0
43
+ DEAD_CONTENT_DB = 8.0
44
+ # Same over a dithered floor: higher margin, but the last 500 Hz below must fall
45
+ # by DITHER_FALL_DB (genuine bench files: 1.5 dB at most; walls: 8 to 48 dB).
46
+ DITHER_MARGIN_DB = 6.5
47
+ DITHER_CONTENT_DB = 6.0
48
+ DITHER_FALL_DB = 6.0
49
+ # Grid trace: a contrast this high is suspect (genuine files of the bench and of
50
+ # real albums stay under 6).
51
+ GRID_CONTRAST = 10.0
52
+
53
+
54
+ BITS = {"PCM_S8": 8, "PCM_U8": 8, "PCM_16": 16, "PCM_24": 24}
55
+
56
+
57
+ def average_spectrum(path: str | Path) -> tuple[np.ndarray, np.ndarray, int, float | None]:
58
+ """Return (frequencies, level in dB, sample rate, quantization floor in dB).
59
+
60
+ The level is the power per frame averaged over channels and over the
61
+ non-silent frames of a few segments spread over the track. The floor is
62
+ the level of plain rounding noise at the file's bit depth (None when the
63
+ format has no fixed depth).
64
+ """
65
+ window = np.hanning(NFFT)
66
+ with sf.SoundFile(str(path)) as f:
67
+ rate = f.samplerate
68
+ total = f.frames
69
+ bits = BITS.get(f.subtype)
70
+ seg = int(SEGMENT_SECONDS * rate)
71
+ if total <= seg:
72
+ starts = [0]
73
+ else:
74
+ lo, hi = int(total * 0.05), max(int(total * 0.95) - seg, int(total * 0.05))
75
+ starts = np.linspace(lo, hi, SEGMENTS).astype(int).tolist()
76
+ acc = np.zeros(NFFT // 2 + 1)
77
+ count = 0
78
+ for start in starts:
79
+ f.seek(start)
80
+ chunk = f.read(seg, dtype="float64", always_2d=True)
81
+ if len(chunk) < NFFT:
82
+ continue
83
+ frames = np.lib.stride_tricks.sliding_window_view(chunk, NFFT, axis=0)[:: NFFT // 2]
84
+ # frames: (n, channels, NFFT)
85
+ rms = np.sqrt((frames**2).mean(axis=(1, 2)))
86
+ frames = frames[rms > SILENT_RMS]
87
+ if not len(frames):
88
+ continue
89
+ power = np.abs(np.fft.rfft(frames * window, axis=2)) ** 2
90
+ acc += power.mean(axis=1).sum(axis=0)
91
+ count += len(frames)
92
+ freqs = np.fft.rfftfreq(NFFT, 1.0 / rate)
93
+ floor = None
94
+ if bits:
95
+ step = 2.0 ** -(bits - 1)
96
+ floor = float(10 * np.log10(step**2 / 12 * (window**2).sum()))
97
+ if not count:
98
+ return freqs, np.full_like(freqs, -200.0), rate, floor
99
+ return freqs, 10 * np.log10(acc / count + 1e-30), rate, floor
100
+
101
+
102
+ def _smooth(values: np.ndarray, bins: int) -> np.ndarray:
103
+ kernel = np.ones(bins) / bins
104
+ return np.convolve(values, kernel, mode="same")
105
+
106
+
107
+ def find_cliff(freqs: np.ndarray, level: np.ndarray, rate: int) -> tuple[float, float] | None:
108
+ """Return (cutoff Hz, drop dB) of the sharpest low-pass, or None.
109
+
110
+ Only the CD band counts (up to 22.05 kHz): above it, a file resampled to
111
+ 96 kHz carries resampler images that are no music and no proof."""
112
+ nyquist = min(rate / 2, CD_NYQUIST)
113
+ hz_per_bin = freqs[1]
114
+ smooth = _smooth(level, max(3, int(100 / hz_per_bin)))
115
+ half = int(CLIFF_WIDTH_HZ / 2 / hz_per_bin)
116
+ # ignore the last 300 Hz (filter edge, smoothing)
117
+ top = min(len(freqs), int((nyquist - 300) / hz_per_bin))
118
+ best: tuple[float, float] | None = None
119
+ for i in range(int(SEARCH_FROM_HZ / hz_per_bin), top - half):
120
+ below = np.median(smooth[max(0, i - 3 * half) : i - half])
121
+ above_band = smooth[i + half : top]
122
+ if len(above_band) < 3:
123
+ break
124
+ above = np.median(above_band)
125
+ drop = below - above
126
+ if drop < CLIFF_DB:
127
+ continue
128
+ # The floor must stay down up to the top (no music coming back).
129
+ if np.percentile(above_band, 95) - above > FLOOR_FLATNESS_DB:
130
+ continue
131
+ if best is None or drop > best[1] + 1.0:
132
+ # Cutoff: last frequency still above halfway down the drop.
133
+ limit = above + drop / 2
134
+ j = i - half
135
+ while j < top and smooth[j] > limit:
136
+ j += 1
137
+ best = (float(freqs[j]), float(drop))
138
+ if best and best[0] >= nyquist - 400:
139
+ return None
140
+ return best
141
+
142
+
143
+ def _dead_band(
144
+ freqs: np.ndarray, smooth: np.ndarray, floor: float, margin: float, min_content: float, min_fall: float
145
+ ) -> tuple[float, float] | None:
146
+ hz_per_bin = freqs[1]
147
+ top = len(freqs) - int(300 / hz_per_bin)
148
+ live = np.nonzero(smooth[:top] > floor + margin)[0]
149
+ if not len(live):
150
+ return None
151
+ start = live[-1] + 1
152
+ if start >= top or freqs[start] < SEARCH_FROM_HZ:
153
+ return None
154
+ lo = max(0, start - int(1200 / hz_per_bin))
155
+ content = float(np.median(smooth[lo : start - int(200 / hz_per_bin)]) - floor)
156
+ fall = float(smooth[start - int(500 / hz_per_bin)] - smooth[start])
157
+ if content < min_content or fall < min_fall:
158
+ return None
159
+ return float(freqs[start]), content
160
+
161
+
162
+ def find_dead_band(freqs: np.ndarray, level: np.ndarray, floor: float | None) -> tuple[float, float] | None:
163
+ """Return (start Hz, content above floor dB) of a band of pure rounding noise
164
+ reaching up to Nyquist, right above real content, or None.
165
+
166
+ Lossy encoders throw away the highs (all of them above their low-pass, or
167
+ the quiet ones in VBR); decoded, that band holds nothing but the rounding
168
+ noise of the bit depth. A recording, even dull, keeps some noise of its own
169
+ above that floor.
170
+
171
+ A decoder that dithers raises that floor by ~5 dB (TPDF). A higher margin
172
+ alone would catch dull recordings that fade into their own dither, so it
173
+ also asks for a steep fall just below: an encoder's wall, not a fade.
174
+ """
175
+ if floor is None:
176
+ return None
177
+ smooth = _smooth(level, max(3, int(100 / freqs[1])))
178
+ return _dead_band(freqs, smooth, floor, DEAD_MARGIN_DB, DEAD_CONTENT_DB, -np.inf) or _dead_band(
179
+ freqs, smooth, floor, DITHER_MARGIN_DB, DITHER_CONTENT_DB, DITHER_FALL_DB
180
+ )
181
+
182
+
183
+ def _grid_suspect(trace: GridTrace | None) -> bool:
184
+ return trace is not None and trace.agree and trace.contrast >= GRID_CONTRAST
185
+
186
+
187
+ def analyze(path: str | Path, cancel: Callable[[], bool] | None = None) -> Verdict:
188
+ """Tell whether one file was made from a lossy source.
189
+
190
+ Looks first for highs cut like by an encoder, then, when the highs tell
191
+ nothing, for the block grid of an MP3, AAC or Vorbis encoder. Never prints,
192
+ never writes, and is safe to call from several threads at once.
193
+
194
+ Args:
195
+ path: A FLAC, WAV or AIFF file (any format libsndfile reads).
196
+ cancel: Checked between stages, each well under a second; when it returns
197
+ True, the analysis stops. `threading.Event().is_set` fits.
198
+
199
+ Returns:
200
+ The verdict. A file that cannot be read gives `Status.UNREADABLE`, not an
201
+ exception.
202
+
203
+ Raises:
204
+ Cancelled: When `cancel` returned True.
205
+ """
206
+
207
+ def check() -> None:
208
+ if cancel is not None and cancel():
209
+ raise Cancelled(str(path))
210
+
211
+ check()
212
+ try:
213
+ info = sf.info(str(path))
214
+ about = dict(
215
+ path=str(path),
216
+ sample_rate=info.samplerate,
217
+ bit_depth=BITS.get(info.subtype),
218
+ channels=info.channels,
219
+ seconds=info.duration,
220
+ )
221
+ freqs, level, rate, floor = average_spectrum(path)
222
+ found = [c for c in (find_cliff(freqs, level, rate), find_dead_band(freqs, level, floor)) if c]
223
+ cutoff = min(found)[0] if found else None
224
+ if cutoff is not None and cutoff < SUSPECT_RATIO * min(rate / 2, CD_NYQUIST):
225
+ return Verdict(status=Status.SUSPECT, clue=Clue.CUT, cutoff_hz=cutoff, **about)
226
+ # The grids cost more: only when the highs told nothing. MP3 first
227
+ # (commonest fake), the AAC/Vorbis grid only when MP3 found nothing.
228
+ check()
229
+ trace = mp3_trace(path)
230
+ if not _grid_suspect(trace):
231
+ check()
232
+ other = grid_trace(path)
233
+ if other and (trace is None or (other.agree, other.contrast) > (trace.agree, trace.contrast)):
234
+ trace = other
235
+ except (RuntimeError, sf.LibsndfileError) as exc:
236
+ return Verdict(str(path), Status.UNREADABLE, error=str(exc))
237
+ contrast = trace.contrast if trace else None
238
+ if trace is not None and _grid_suspect(trace):
239
+ return Verdict(
240
+ status=Status.SUSPECT, clue=Clue.GRID, codec=trace.codec, cutoff_hz=cutoff, grid_contrast=contrast, **about
241
+ )
242
+ return Verdict(status=Status.OK, cutoff_hz=cutoff, grid_contrast=contrast, **about)
trueflac/cli.py ADDED
@@ -0,0 +1,50 @@
1
+ """Command line: trueflac check <file or folder>..."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from dataclasses import asdict
9
+ from pathlib import Path
10
+
11
+ from . import __version__
12
+ from .analysis import analyze
13
+ from .verdict import describe
14
+
15
+ EXTENSIONS = {".flac", ".wav", ".aiff", ".aif"}
16
+
17
+
18
+ def _files(paths: list[str]) -> list[Path]:
19
+ found: list[Path] = []
20
+ for raw in paths:
21
+ p = Path(raw)
22
+ if p.is_dir():
23
+ found += sorted(x for x in p.rglob("*") if x.suffix.lower() in EXTENSIONS)
24
+ else:
25
+ found.append(p)
26
+ return found
27
+
28
+
29
+ def main(argv: list[str] | None = None) -> int:
30
+ parser = argparse.ArgumentParser(prog="trueflac")
31
+ parser.add_argument("--version", action="version", version=f"trueflac {__version__}")
32
+ sub = parser.add_subparsers(dest="command", required=True)
33
+ check = sub.add_parser("check", help="analyze files or folders")
34
+ check.add_argument("paths", nargs="+")
35
+ check.add_argument("--json", action="store_true", help="one JSON object per line")
36
+ args = parser.parse_args(argv)
37
+
38
+ suspects = 0
39
+ for path in _files(args.paths):
40
+ v = analyze(path)
41
+ suspects += v.suspect
42
+ if args.json:
43
+ print(json.dumps(asdict(v)))
44
+ else:
45
+ print(f"{v.status.value:10} {path.name} {describe(v)}")
46
+ return 1 if suspects else 0
47
+
48
+
49
+ if __name__ == "__main__":
50
+ sys.exit(main())
trueflac/grid.py ADDED
@@ -0,0 +1,201 @@
1
+ """Traces of a transform codec's block grid.
2
+
3
+ AAC and Vorbis code a track as blocks of an MDCT (2048 samples, hop 1024 for
4
+ long blocks) and set to zero every coefficient too weak to be heard. Decoded,
5
+ the track still holds those zeros, but only when it is analyzed with the same
6
+ transform, the same window and the same block start. So we compute the MDCT
7
+ at every possible start (0 to 1023 samples) and count the coefficients that sit
8
+ at the level of rounding noise:
9
+
10
+ - a file made from such a codec has one start far above all the others;
11
+ - a recording has no preferred start: all counts look alike.
12
+
13
+ The contrast is a robust z-score: (best - median) / MAD over the 1024 starts.
14
+ Idea after Derrien et al. (AES 2015, 2019) on MDCT-domain traces.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from collections.abc import Callable
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+ from typing import TypeVar
23
+
24
+ import numpy as np
25
+ import soundfile as sf
26
+
27
+ N = 2048
28
+ HOP = N // 2
29
+ FRAMES = 16 # blocks per measure (~0.4 s at 44.1 kHz)
30
+ PLACES = (0.35, 0.65) # where in the track the measures are taken
31
+ FROM_HZ = 3000.0 # count only above this: the highs are where codecs drop most
32
+ ZERO_NOISE_FACTOR = 2.0 # "zero" = below this many rounding-noise deviations
33
+ ZERO_LEVELS = (19, 17, 15) # further limits, as 2^-e of full scale (2^-13 raised genuine contrasts to 6.5)
34
+ MIN_MAD = 0.002
35
+ CONFIRM = 3 # candidates measured on the other chunks (see confirm)
36
+ BATCH = 64 # block starts per FFT batch (memory: BATCH * FRAMES * N complex)
37
+
38
+
39
+ def _kbd(alpha: float) -> np.ndarray:
40
+ """Kaiser-Bessel-derived window (AAC's other long-block window)."""
41
+ kaiser = np.kaiser(N // 2 + 1, np.pi * alpha)
42
+ half = np.sqrt(np.cumsum(kaiser[:-1]) / kaiser.sum())
43
+ return np.concatenate([half, half[::-1]])
44
+
45
+
46
+ def _windows() -> dict[str, np.ndarray]:
47
+ t = np.sin(np.pi * (np.arange(N) + 0.5) / N)
48
+ windows = {"AAC sine": t, "AAC KBD": _kbd(4.0), "Vorbis": np.sin(np.pi / 2 * t**2)}
49
+ return {name: w.astype(np.float32) for name, w in windows.items()}
50
+
51
+
52
+ # Window name -> codec it points at. ffmpeg's AAC answers best to KBD, Apple's
53
+ # to the sine window; without KBD, ffmpeg's AAC was often taken for Vorbis.
54
+ WINDOWS = _windows()
55
+ CODEC_OF_WINDOW = {name: name.split()[0] for name in WINDOWS}
56
+ _n0 = N // 2
57
+ _n4 = N // 4
58
+ _j = np.arange(_n0 // 2)
59
+ _PRE = np.exp(-1j * np.pi * (4 * _j + 1) / (4 * _n0)).astype(np.complex64)
60
+ _POST = np.exp(-1j * np.pi * _j / _n0).astype(np.complex64)
61
+
62
+
63
+ def mdct(frames: np.ndarray, window: np.ndarray) -> np.ndarray:
64
+ """MDCT of each row (length N): fold into a DCT-IV of length N/2, computed
65
+ through one complex FFT of length N/4."""
66
+ x = frames * window
67
+ a, b, c, d = (x[..., i * _n4 : (i + 1) * _n4] for i in range(4))
68
+ u = np.concatenate([-c[..., ::-1] - d, a - b[..., ::-1]], axis=-1)
69
+ t = (u[..., 0::2] + 1j * u[..., ::-1][..., 0::2]) * _PRE
70
+ y = np.fft.fft(t, axis=-1) * _POST
71
+ out = np.empty(u.shape, dtype=np.float32)
72
+ out[..., 0::2] = y.real
73
+ out[..., ::-1][..., 0::2] = -y.imag
74
+ return out
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class GridTrace:
79
+ contrast: float # robust z-score of the best block start
80
+ codec: str # "AAC", "Vorbis" or "MP3"
81
+ start: int
82
+ # Every chunk, measured alone, points at the same start. A codec's grid
83
+ # stays put along the track; chance peaks land anywhere.
84
+ agree: bool = True
85
+
86
+
87
+ def _zero_shares(signal: np.ndarray, window: np.ndarray, limits: np.ndarray, kmin: int) -> np.ndarray:
88
+ """Share of coefficients below each limit, for each block start: (limits, HOP)."""
89
+ blocks = np.lib.stride_tricks.sliding_window_view(signal.astype(np.float32), N)
90
+ # Row (start + HOP * m) of `blocks` is block m for that start.
91
+ index = np.arange(HOP)[:, None] + HOP * np.arange(FRAMES)[None, :]
92
+ shares = np.empty((len(limits), HOP))
93
+ for lo in range(0, HOP, BATCH):
94
+ frames = blocks[index[lo : lo + BATCH]] # (batch, FRAMES, N)
95
+ size = np.abs(mdct(frames, window)[..., kmin:])
96
+ for t, limit in enumerate(limits):
97
+ shares[t, lo : lo + BATCH] = (size < limit).mean(axis=(1, 2))
98
+ return shares
99
+
100
+
101
+ def _limits(bits: int, window: np.ndarray) -> np.ndarray:
102
+ """ "Zero" limits for MDCT coefficients, from the rounding noise of the bit
103
+ depth up to 2^-15 of full scale. A decoder computes in floating point, so
104
+ its zeros are not always at the rounding floor (24-bit output above all)."""
105
+ norm = np.sqrt((window**2).sum() / 2)
106
+ floor = ZERO_NOISE_FACTOR * 2.0 ** -(bits - 1) / np.sqrt(12)
107
+ levels = [floor] + [2.0**-e for e in ZERO_LEVELS if 2.0**-e > floor]
108
+ return np.array(levels) * norm
109
+
110
+
111
+ def read_chunks(path: str | Path, length: int) -> tuple[int, int, list[tuple[int, np.ndarray]]] | None:
112
+ """(sample rate, bit depth, [(start, samples)]) at each of PLACES, or None
113
+ when the format has no fixed bit depth or the track is too short."""
114
+ with sf.SoundFile(str(path)) as f:
115
+ rate, total = f.samplerate, f.frames
116
+ bits = {"PCM_16": 16, "PCM_24": 24}.get(f.subtype)
117
+ if bits is None:
118
+ return None
119
+ chunks = []
120
+ for place in PLACES:
121
+ start = int(total * place)
122
+ if start + length > total:
123
+ continue
124
+ f.seek(start)
125
+ chunks.append((start, f.read(length, dtype="float64", always_2d=True)))
126
+ return (rate, bits, chunks) if chunks else None
127
+
128
+
129
+ def best_contrast(shares: np.ndarray) -> tuple[float, int, int]:
130
+ """Robust z-score of the best start over all limits: (contrast, limit, start)."""
131
+ median = np.median(shares, axis=1, keepdims=True)
132
+ mad = np.maximum(np.median(np.abs(shares - median), axis=1) * 1.4826, MIN_MAD)
133
+ contrasts = (shares.max(axis=1) - median[:, 0]) / mad
134
+ t = int(contrasts.argmax())
135
+ return float(contrasts[t]), t, int(shares[t].argmax())
136
+
137
+
138
+ # Chunks must agree on the start modulo this step. MP3 granules and AAC frames
139
+ # never change size; Vorbis switches to short blocks (256) and its long-block
140
+ # grid then moves by multiples of 128.
141
+ AGREE_STEP = {"AAC": HOP, "MP3": 576, "Vorbis": 128}
142
+
143
+
144
+ def combine(codec: str, parts: list[np.ndarray]) -> GridTrace:
145
+ """Trace from the per-chunk shares (each already rolled to file positions)."""
146
+ contrast, limit, start = best_contrast(np.sum(parts, axis=0))
147
+ step = AGREE_STEP[codec]
148
+ agree = all((int(part[limit].argmax()) - start) % step == 0 for part in parts)
149
+ return GridTrace(contrast, codec, start, agree)
150
+
151
+
152
+ K = TypeVar("K") # a grid candidate: (window, channel) or channel
153
+
154
+
155
+ def confirm(
156
+ codec_of: dict[K, str],
157
+ shares_of: Callable[[K, np.ndarray], np.ndarray],
158
+ chunks: list[tuple[int, np.ndarray]],
159
+ step: int,
160
+ ) -> GridTrace | None:
161
+ """Measure the first chunk for every candidate (window, channel...), then
162
+ the other chunks only for the CONFIRM most promising ones: they only
163
+ confirm. Bench: with 4 candidates, confirming 1 lost 8 of ~370 detections and
164
+ 2 lost none; with the KBD window (6 candidates), 2 lost one Vorbis, 3 none.
165
+
166
+ `shares_of(candidate, samples)` returns the shares of one chunk;
167
+ `codec_of` maps each candidate to its codec name.
168
+ """
169
+ first_start, first = chunks[0]
170
+ firsts = {c: np.roll(shares_of(c, first), first_start % step, axis=1) for c in codec_of}
171
+ ranked = sorted(firsts, key=lambda c: best_contrast(firsts[c])[0], reverse=True)
172
+ best: GridTrace | None = None
173
+ for lead in ranked[:CONFIRM]:
174
+ parts = [firsts[lead]] + [np.roll(shares_of(lead, chunk), start % step, axis=1) for start, chunk in chunks[1:]]
175
+ best = better(best, combine(codec_of[lead], parts))
176
+ return best
177
+
178
+
179
+ def better(a: GridTrace | None, b: GridTrace) -> GridTrace:
180
+ """The stronger trace, agreeing ones first."""
181
+ if a is None:
182
+ return b
183
+ return max(a, b, key=lambda t: (t.agree, t.contrast))
184
+
185
+
186
+ def grid_trace(path: str | Path) -> GridTrace | None:
187
+ read = read_chunks(path, HOP * (FRAMES + 2))
188
+ if read is None:
189
+ return None
190
+ rate, bits, chunks = read
191
+ kmin = int(FROM_HZ / (rate / 2) * _n0)
192
+ limits = {name: _limits(bits, window) for name, window in WINDOWS.items()}
193
+ candidates = {(name, ch): CODEC_OF_WINDOW[name] for name in WINDOWS for ch in range(chunks[0][1].shape[1])}
194
+
195
+ def shares_of(candidate, samples):
196
+ name, channel = candidate
197
+ return _zero_shares(samples[:, channel], WINDOWS[name], limits[name], kmin)
198
+
199
+ # Block starts are the same along the whole track only modulo HOP, so each
200
+ # chunk is rolled to its own position in the file.
201
+ return confirm(candidates, shares_of, chunks, HOP)
trueflac/mp3grid.py ADDED
@@ -0,0 +1,135 @@
1
+ """Traces of an MP3 encoder's granule grid.
2
+
3
+ MP3 (layer III) codes each granule of 576 samples as 576 frequency lines:
4
+ a 32-band polyphase filter bank, then an 18-point MDCT in each band (36-sample
5
+ window, long blocks). Lines too weak to be heard are set to zero. A decoder
6
+ rebuilds the sound as a sum of 576 fixed shapes per granule; projecting a
7
+ decoded file on those shapes, at the right granule start, gives the zeros
8
+ back. A recording has no preferred start. Same contrast as grid.py.
9
+
10
+ The shapes are rebuilt here from the standard: IMDCT 36 with a sine window,
11
+ alias-reduction butterflies, frequency inversion of odd bands, then the
12
+ polyphase synthesis window D (ISO/IEC 11172-3, table 3-B.3). The 512 values of
13
+ D below were read back from the minimp3 decoder (public domain, CC0) and the
14
+ shapes checked against it (max relative error 3e-6). Eight entries are 0: the
15
+ synthesis cosine is zero there for every band, so they never count.
16
+ Idea after Derrien et al. (AES 2015, 2019).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from functools import lru_cache
22
+ from pathlib import Path
23
+
24
+ import numpy as np
25
+
26
+ from .grid import GridTrace, confirm, read_chunks
27
+
28
+ GRANULE = 576
29
+ GRANULES = 12 # granules per measure (~0.16 s at 44.1 kHz)
30
+ FROM_HZ = 3000.0
31
+ # "Zero" limits for a line, as 2^-e of full scale (unit-norm shapes).
32
+ ZERO_LEVELS = (18, 17, 16, 15, 14, 13)
33
+ BATCH = 96
34
+
35
+ # Polyphase synthesis window D, times 32768.
36
+ # fmt: off
37
+ _D = np.array([
38
+ 0, -1, -1, -1, -1, -1, -1, -2, -2, -2, -2, -3, -3, -4, -4, -5,
39
+ 0, -6, -7, -7, -8, -9, -10, -11, -13, -14, -16, -17, -19, -21, -24, -26,
40
+ -29, -31, -35, -38, -41, -45, -49, -53, -58, -63, -68, -73, -79, -85, -91, -97,
41
+ -104, -111, -117, -125, -132, -139, -147, -154, -161, -169, -176, -183, -190, -196, -202, -208,
42
+ -213, -218, -222, -225, -227, -228, -228, -227, -224, -221, -215, -208, -200, -189, -177, -163,
43
+ 0, -127, -106, -83, -57, -29, 2, 36, 72, 111, 153, 197, 244, 294, 347, 401,
44
+ 459, 519, 581, 645, 711, 779, 848, 919, 991, 1064, 1137, 1210, 1283, 1356, 1428, 1498,
45
+ 1567, 1634, 1698, 1759, 1817, 1870, 1919, 1962, 2001, 2032, 2057, 2075, 2085, 2087, 2080, 2063,
46
+ 2037, 2000, 1952, 1893, 1822, 1739, 1644, 1535, 1414, 1280, 1131, 970, 794, 605, 402, 185,
47
+ 0, -288, -545, -814, -1095, -1388, -1692, -2006, -2330, -2663, -3004, -3351, -3705, -4063, -4425, -4788,
48
+ -5153, -5517, -5879, -6237, -6589, -6935, -7271, -7597, -7910, -8209, -8491, -8755, -8998, -9219, -9416, -9585,
49
+ -9727, -9838, -9916, -9959, -9966, -9935, -9863, -9750, -9592, -9389, -9139, -8840, -8492, -8092, -7640, -7134,
50
+ -6574, -5959, -5288, -4561, -3776, -2935, -2037, -1082, -70, 998, 2122, 3300, 4533, 5818, 7154, 8540,
51
+ 0, 11455, 12980, 14548, 16155, 17799, 19478, 21189, 22929, 24694, 26482, 28289, 30112, 31947, 33791, 35640,
52
+ 37489, 39336, 41176, 43006, 44821, 46617, 48390, 50137, 51853, 53534, 55178, 56778, 58333, 59838, 61289, 62684,
53
+ 64019, 65290, 66494, 67629, 68692, 69679, 70590, 71420, 72169, 72835, 73415, 73908, 74313, 74630, 74856, 74992,
54
+ 75038, 74992, 74856, 74630, 74313, 73908, 73415, 72835, 72169, 71420, 70590, 69679, 68692, 67629, 66494, 65290,
55
+ 0, 62684, 61289, 59838, 58333, 56778, 55178, 53534, 51853, 50137, 48390, 46617, 44821, 43006, 41176, 39336,
56
+ 37489, 35640, 33791, 31947, 30112, 28289, 26482, 24694, 22929, 21189, 19478, 17799, 16155, 14548, 12980, 11455,
57
+ 9975, 8540, 7154, 5818, 4533, 3300, 2122, 998, -70, -1082, -2037, -2935, -3776, -4561, -5288, -5959,
58
+ -6574, -7134, -7640, -8092, -8492, -8840, -9139, -9389, -9592, -9750, -9863, -9935, -9966, -9959, -9916, -9838,
59
+ 0, -9585, -9416, -9219, -8998, -8755, -8491, -8209, -7910, -7597, -7271, -6935, -6589, -6237, -5879, -5517,
60
+ -5153, -4788, -4425, -4063, -3705, -3351, -3004, -2663, -2330, -2006, -1692, -1388, -1095, -814, -545, -288,
61
+ -45, 185, 402, 605, 794, 970, 1131, 1280, 1414, 1535, 1644, 1739, 1822, 1893, 1952, 2000,
62
+ 2037, 2063, 2080, 2087, 2085, 2075, 2057, 2032, 2001, 1962, 1919, 1870, 1817, 1759, 1698, 1634,
63
+ 0, 1498, 1428, 1356, 1283, 1210, 1137, 1064, 991, 919, 848, 779, 711, 645, 581, 519,
64
+ 459, 401, 347, 294, 244, 197, 153, 111, 72, 36, 2, -29, -57, -83, -106, -127,
65
+ -146, -163, -177, -189, -200, -208, -215, -221, -224, -227, -228, -228, -227, -225, -222, -218,
66
+ -213, -208, -202, -196, -190, -183, -176, -169, -161, -154, -147, -139, -132, -125, -117, -111,
67
+ 0, -97, -91, -85, -79, -73, -68, -63, -58, -53, -49, -45, -41, -38, -35, -31,
68
+ -29, -26, -24, -21, -19, -17, -16, -14, -13, -11, -10, -9, -8, -7, -7, -6,
69
+ -5, -5, -4, -4, -3, -3, -2, -2, -2, -2, -1, -1, -1, -1, -1, -1,
70
+ ]) / 32768.0
71
+ # fmt: on
72
+
73
+ # Alias-reduction coefficients (ISO/IEC 11172-3, table 3-B.9).
74
+ _CI = np.array([-0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037])
75
+ _CS = 1 / np.sqrt(1 + _CI**2)
76
+ _CA = _CI / np.sqrt(1 + _CI**2)
77
+
78
+
79
+ @lru_cache(maxsize=1)
80
+ def shapes() -> np.ndarray:
81
+ """The 576 line shapes of one granule, unit norm: (576, 1632) float32."""
82
+ # 1. lines -> band samples: alias reduction, IMDCT 36, window. Linear, so
83
+ # run it on the identity (one line per row).
84
+ lines = np.eye(GRANULE).reshape(GRANULE, 32, 18)
85
+ for sb in range(31):
86
+ for i in range(8):
87
+ a = lines[:, sb, 17 - i].copy()
88
+ b = lines[:, sb + 1, i].copy()
89
+ lines[:, sb, 17 - i] = a * _CS[i] - b * _CA[i]
90
+ lines[:, sb + 1, i] = b * _CS[i] + a * _CA[i]
91
+ n = np.arange(36)[:, None]
92
+ j = np.arange(18)[None, :]
93
+ imdct = np.cos(np.pi / 72 * (2 * n + 1 + 18) * (2 * j + 1)) # (36, 18)
94
+ window = np.sin(np.pi / 36 * (np.arange(36) + 0.5))
95
+ bands = np.einsum("lbj,nj->lbn", lines, imdct) * window # (576, 32, 36 slots)
96
+ bands[:, 1::2, 1::2] *= -1 # frequency inversion
97
+ # 2. band samples -> sound: polyphase synthesis, one slot every 32 samples.
98
+ k = np.arange(32)[:, None]
99
+ m = np.arange(512)[None, :]
100
+ synthesis = _D * np.cos((2 * k + 1) * (m + 16) * np.pi / 64) # (32, 512)
101
+ out = np.zeros((GRANULE, 32 * 36 + 512 - 32))
102
+ for slot in range(36):
103
+ out[:, 32 * slot : 32 * slot + 512] += bands[:, :, slot] @ synthesis
104
+ out /= np.linalg.norm(out, axis=1, keepdims=True)
105
+ return out.astype(np.float32)
106
+
107
+
108
+ def _zero_shares(signal: np.ndarray, basis: np.ndarray, limits: np.ndarray) -> np.ndarray:
109
+ """Share of line values below each limit, for each granule start: (limits, 576)."""
110
+ length = basis.shape[0]
111
+ frames = np.lib.stride_tricks.sliding_window_view(signal.astype(np.float32), length)
112
+ index = np.arange(GRANULE)[:, None] + GRANULE * np.arange(GRANULES)[None, :]
113
+ shares = np.empty((len(limits), GRANULE))
114
+ for lo in range(0, GRANULE, BATCH):
115
+ size = np.abs(frames[index[lo : lo + BATCH]] @ basis) # (batch, GRANULES, lines)
116
+ for t, limit in enumerate(limits):
117
+ shares[t, lo : lo + BATCH] = (size < limit).mean(axis=(1, 2))
118
+ return shares
119
+
120
+
121
+ def mp3_trace(path: str | Path) -> GridTrace | None:
122
+ full = shapes()
123
+ read = read_chunks(path, GRANULE * (GRANULES + 1) + full.shape[1])
124
+ if read is None:
125
+ return None
126
+ rate, _bits, chunks = read
127
+ kmin = int(FROM_HZ / (rate / 2) * GRANULE)
128
+ basis = np.ascontiguousarray(full[kmin:].T) # (length, lines)
129
+ limits = np.array([2.0**-e for e in ZERO_LEVELS])
130
+ candidates = {ch: "MP3" for ch in range(chunks[0][1].shape[1])}
131
+
132
+ def shares_of(channel: int, samples: np.ndarray) -> np.ndarray:
133
+ return _zero_shares(samples[:, channel], basis, limits)
134
+
135
+ return confirm(candidates, shares_of, chunks, GRANULE)
trueflac/py.typed ADDED
File without changes
trueflac/verdict.py ADDED
@@ -0,0 +1,102 @@
1
+ """What an analysis returns, as data an application can translate."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from enum import StrEnum
7
+
8
+
9
+ class Status(StrEnum):
10
+ """The answer for one file.
11
+
12
+ Attributes:
13
+ OK: No sign of a lossy source.
14
+ SUSPECT: A clue points at a lossy source. Never read it as "fake": an old
15
+ recording or a filtered master can look the same.
16
+ UNREADABLE: The file could not be decoded; `Verdict.error` says why.
17
+ """
18
+
19
+ OK = "ok"
20
+ SUSPECT = "suspect"
21
+ UNREADABLE = "unreadable"
22
+
23
+
24
+ class Clue(StrEnum):
25
+ """Why a file is suspect.
26
+
27
+ Attributes:
28
+ CUT: The highs stop like after a lossy encoder; `Verdict.cutoff_hz` says where.
29
+ GRID: The block grid of a lossy encoder is still in the sound; `Verdict.codec`
30
+ names the encoder.
31
+ """
32
+
33
+ CUT = "cut"
34
+ GRID = "grid"
35
+
36
+
37
+ class Cancelled(Exception):
38
+ """Raised by `analyze()` when its `cancel` check returns True.
39
+
40
+ Its message is the path of the file being analyzed.
41
+ """
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Verdict:
46
+ """What `analyze()` found in one file: data, not sentences, so that an
47
+ application can word it in its own language.
48
+
49
+ Attributes:
50
+ path: The file, as given to `analyze()`.
51
+ status: The answer.
52
+ clue: Why the file is suspect, or None.
53
+ codec: "MP3", "AAC" or "Vorbis", for a `Clue.GRID`; else None.
54
+ cutoff_hz: Where the highs end, in hertz, when they end sharply (also on a
55
+ genuine file, as on a CD); else None.
56
+ grid_contrast: Strength of the best block grid found (suspect from 10;
57
+ genuine tracks stay under 6), when the grids were measured; else None.
58
+ sample_rate: Samples per second of the file.
59
+ bit_depth: 16 or 24 for PCM files, None for float or unknown formats.
60
+ channels: Number of channels.
61
+ seconds: Duration of the file.
62
+ error: Why the file could not be read, for `Status.UNREADABLE`.
63
+ """
64
+
65
+ path: str
66
+ status: Status
67
+ clue: Clue | None = None
68
+ codec: str | None = None
69
+ cutoff_hz: float | None = None
70
+ grid_contrast: float | None = None
71
+ sample_rate: int | None = None
72
+ bit_depth: int | None = None
73
+ channels: int | None = None
74
+ seconds: float | None = None
75
+ error: str | None = None
76
+
77
+ @property
78
+ def suspect(self) -> bool:
79
+ """True when `status` is `Status.SUSPECT`."""
80
+ return self.status is Status.SUSPECT
81
+
82
+
83
+ def describe(verdict: Verdict) -> str:
84
+ """Word a verdict as the one English line the command line prints.
85
+
86
+ Applications build their own sentence from the verdict's fields instead.
87
+
88
+ Args:
89
+ verdict: A verdict returned by `analyze()`.
90
+
91
+ Returns:
92
+ A line such as "Highs cut at 16.6 kHz, like a lossy file".
93
+ """
94
+ if verdict.status is Status.UNREADABLE:
95
+ return f"Unreadable: {verdict.error}"
96
+ if verdict.clue is Clue.CUT and verdict.cutoff_hz is not None:
97
+ return f"Highs cut at {verdict.cutoff_hz / 1000:.1f} kHz, like a lossy file"
98
+ if verdict.clue is Clue.GRID:
99
+ return f"Block grid of a lossy encoder ({verdict.codec})"
100
+ if verdict.cutoff_hz:
101
+ return f"Highs end at {verdict.cutoff_hz / 1000:.1f} kHz, as on a CD"
102
+ return "No sign of a lossy source"
@@ -0,0 +1,286 @@
1
+ Metadata-Version: 2.5
2
+ Name: trueflac
3
+ Version: 0.1.0
4
+ Summary: Tells whether a FLAC (or WAV, AIFF) file was made from a lossy source: MP3, AAC, Opus, Vorbis.
5
+ Project-URL: Homepage, https://github.com/opalehq/trueflac
6
+ Project-URL: Issues, https://github.com/opalehq/trueflac/issues
7
+ Project-URL: Changelog, https://github.com/opalehq/trueflac/blob/main/CHANGELOG.md
8
+ Author: Opale
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: aac,audio,flac,lossless,mp3,music,spectrum,transcode
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: End Users/Desktop
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Analysis
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.11
24
+ Requires-Dist: numpy>=1.26
25
+ Requires-Dist: soundfile>=0.12
26
+ Description-Content-Type: text/markdown
27
+
28
+ <div align="center">
29
+
30
+ # trueflac
31
+
32
+ <picture>
33
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg">
34
+ <img src="docs/assets/logo-light.svg" alt="trueflac logo" height="72">
35
+ </picture>
36
+
37
+ **Tells whether a FLAC file was made from an MP3, an AAC, an Opus or a Vorbis file.**
38
+
39
+ [![CI](https://img.shields.io/github/actions/workflow/status/opalehq/trueflac/ci.yml?branch=main&label=CI&logo=github)](https://github.com/opalehq/trueflac/actions/workflows/ci.yml)
40
+ [![PyPI](https://img.shields.io/pypi/v/trueflac)](https://pypi.org/project/trueflac/)
41
+ ![Python](https://img.shields.io/badge/python-3.11+-3776AB?logo=python&logoColor=white)
42
+ ![License](https://img.shields.io/badge/license-MIT-blue)
43
+
44
+ [Why](#-why-trueflac) β€’ [Install](#-install) β€’ [Command line](#-command-line) β€’ [Python](#-python) β€’
45
+ [How it works](#-how-it-works) β€’ [Results](#-results) β€’ [References](#-references) β€’
46
+ [Documentation](https://opalehq.github.io/trueflac/)
47
+
48
+ </div>
49
+
50
+ ---
51
+
52
+ ## πŸ‘‹ Why trueflac?
53
+
54
+ A FLAC file promises the sound of the CD. Converting an MP3 to FLAC keeps that promise on the
55
+ label only: the file is bigger, the sound is the MP3's. Music shared online, old downloads and
56
+ "lossless" packs often hold such files, and nothing in their tags says so.
57
+
58
+ trueflac looks at the sound itself and answers **suspect** or **ok** for each file. It never says
59
+ "fake": an old recording or a filtered master can look like a lossy file. When in doubt it keeps
60
+ quiet, so a genuine file is never accused on its word: on its bench, no genuine file is flagged.
61
+
62
+ It is the engine of the fake FLAC check in [S.O.K](https://github.com/opalehq/S.O.K), and works on
63
+ its own as a command and a Python library.
64
+
65
+ ## ✨ Features
66
+
67
+ - **Two independent clues.** The highs cut like an encoder does, or the block grid of the encoder
68
+ still in the sound. The second one catches what the first cannot see: MP3 V0 and 320 kbit/s,
69
+ AAC 256, Vorbis.
70
+ - **Names the codec** when it finds its grid: MP3, AAC or Vorbis.
71
+ - **FLAC, WAV and AIFF**, 16 or 24 bits, 44.1 to 96 kHz, mono or stereo.
72
+ - **Read only.** It never writes, moves or deletes a file, and never goes on the network.
73
+ - **Light.** numpy and soundfile, nothing else. About 1.5 s for a genuine track on an Apple
74
+ Silicon Mac, half that on four threads.
75
+ - **Made for applications.** Verdicts are data that an app words in its own language,
76
+ analyses can be canceled, and it is safe to run on several threads.
77
+
78
+ ## πŸ“₯ Install
79
+
80
+ ```console
81
+ pip install trueflac
82
+ ```
83
+
84
+ Or as a command only, with [uv](https://docs.astral.sh/uv/): `uv tool install trueflac`.
85
+
86
+ Python 3.11 or later. soundfile ships its own libsndfile on Linux, macOS and Windows.
87
+
88
+ ## πŸ’» Command line
89
+
90
+ ```console
91
+ $ trueflac check Album/
92
+ ok 01 - Echoplex (CD).flac No sign of a lossy source
93
+ suspect 02 - Echoplex (from MP3 128).flac Highs cut at 16.6 kHz, like a lossy file
94
+ suspect 03 - Echoplex (from MP3 V0).flac Block grid of a lossy encoder (MP3)
95
+ suspect 04 - Echoplex (from AAC 256).flac Block grid of a lossy encoder (AAC)
96
+ suspect 05 - Echoplex (from Vorbis q6).flac Block grid of a lossy encoder (Vorbis)
97
+ ```
98
+
99
+ This is a real run on one clip of the bench (Nine Inch Nails, *The Slip*) and four fakes made
100
+ from it. Only the MP3 128 lost its highs; the three others keep them and are seen through their
101
+ grid.
102
+
103
+ ```console
104
+ trueflac check <file or folder>... [--json]
105
+ trueflac --version
106
+ ```
107
+
108
+ Folders are searched for `.flac`, `.wav`, `.aiff` and `.aif` files. `--json` prints one JSON object
109
+ per file:
110
+
111
+ ```console
112
+ $ trueflac check --json "Album/02 - Echoplex (from MP3 128).flac"
113
+ {"path": "Album/02 - Echoplex (from MP3 128).flac", "status": "suspect", "clue": "cut", "codec": null, "cutoff_hz": 16618.24951171875, "grid_contrast": null, "sample_rate": 44100, "bit_depth": 16, "channels": 2, "seconds": 60.0, "error": null}
114
+ ```
115
+
116
+ The exit code is 1 when a file is suspect, 0 otherwise.
117
+
118
+ ## 🐍 Python
119
+
120
+ ```python
121
+ from trueflac import Clue, Status, analyze
122
+
123
+ verdict = analyze("02 - Single.flac")
124
+ if verdict.status is Status.SUSPECT:
125
+ if verdict.clue is Clue.CUT:
126
+ print(f"highs cut at {verdict.cutoff_hz:.0f} Hz")
127
+ else: # Clue.GRID
128
+ print(f"made from {verdict.codec}") # "MP3", "AAC" or "Vorbis"
129
+ ```
130
+
131
+ A `Verdict` holds data, not sentences, so an application can word it in its own language:
132
+
133
+ | Field | Meaning |
134
+ | --- | --- |
135
+ | `status` | `Status.OK`, `Status.SUSPECT` or `Status.UNREADABLE` |
136
+ | `clue` | why it is suspect: `Clue.CUT` (the highs stop like after an encoder) or `Clue.GRID` (the encoder's block grid is still there) |
137
+ | `codec` | `"MP3"`, `"AAC"` or `"Vorbis"`, for a grid |
138
+ | `cutoff_hz` | where the highs end, when they end sharply |
139
+ | `grid_contrast` | strength of the best block grid (suspect from 10) |
140
+ | `sample_rate`, `bit_depth`, `channels`, `seconds` | the file |
141
+ | `error` | why the file could not be read |
142
+
143
+ `describe(verdict)` gives the English line the command line prints.
144
+
145
+ `analyze()` never prints, never raises on a broken file (the verdict is `unreadable`) and is safe
146
+ to call from several threads. It takes an optional `cancel` callable, checked between its stages;
147
+ when it returns `True`, `analyze()` raises `Cancelled`:
148
+
149
+ ```python
150
+ import threading
151
+ from trueflac import Cancelled, analyze
152
+
153
+ stop = threading.Event()
154
+ try:
155
+ verdict = analyze(path, cancel=stop.is_set)
156
+ except Cancelled:
157
+ ...
158
+ ```
159
+
160
+ ## πŸ”¬ How it works
161
+
162
+ **1. Cut highs.** trueflac averages the spectrum at eight points of the track. An encoder throws
163
+ away the highs it finds inaudible: above its low-pass, a decoded file holds nothing but the
164
+ rounding noise of its bit depth, while a recording, even a 78 rpm disc or a quiet piano, keeps a
165
+ little noise of its own. A sharp fall to that floor below 20.3 kHz is suspect.
166
+
167
+ **2. Codec grid**, when the highs tell nothing. An encoder cuts the sound into blocks, moves each
168
+ block to frequencies with a fixed transform and sets to zero what it finds inaudible. Analyzed
169
+ with the same transform, at the same block start, the decoded file shows those zeros again.
170
+ A recording has no preferred start: every start looks the same. This idea comes from the
171
+ "inverse decoder" of Herre and Schug and from the detectors of Derrien and his co-authors (see
172
+ [References](#-references)).
173
+
174
+ trueflac tries every start:
175
+
176
+ - **MP3**: its 576 lines per granule are rebuilt from the standard (polyphase filter bank, 18-point
177
+ MDCT, alias butterflies) and checked against the minimp3 decoder.
178
+ - **AAC and Vorbis**: a 2048-point MDCT with the windows their encoders use (sine and
179
+ Kaiser-Bessel derived for AAC, the Vorbis power window).
180
+
181
+ A grid counts only when it stands far above all other starts (a contrast of 10, where genuine
182
+ tracks stay under 6) and when two separate parts of the track agree on where it starts.
183
+
184
+ ## πŸ“Š Results
185
+
186
+ On a bench of 22 genuine clips (rock, solo piano, 78 rpm transfers) and the same clips encoded and
187
+ decoded back, with [flac-detective](https://github.com/Guillain-RDCDE/FLAC_Detective) 2.6.1 run on
188
+ the same files for reference:
189
+
190
+ | Files flagged (out of 22) | trueflac | flac-detective |
191
+ | --- | --- | --- |
192
+ | **Genuine** (false accusations) | **0** | 0 |
193
+ | MP3 128 / 192 / 256 / 320 kbit/s | **22 / 22 / 21 / 21** | 4 / 5 / 0 / 0 |
194
+ | MP3 V0 | **22** | 0 |
195
+ | AAC 256 (ffmpeg / Apple) | **19 / 18** | 12 / 0 |
196
+ | Opus 192 | **17** | 12 |
197
+ | Vorbis q6 | **22** | 21 |
198
+ | Time per file | **0.9 s** | 2.7 s |
199
+
200
+ Also measured, with no genuine file flagged: decodes with dither or to 24 bits, genuine clips
201
+ with dither, 48 and 96 kHz, mono, 3-second clips, WAV and AIFF. Times are on an Apple Silicon Mac
202
+ (average over the bench; a genuine track takes the longest, about 1.5 s, since every test runs).
203
+
204
+ **Known limits**
205
+
206
+ - **Opus** is only seen through its cut: it works at 48 kHz, and the resampling back to 44.1 kHz
207
+ blurs its grid.
208
+ - **Noise-shaped dither** fills the highs and can hide an AAC (Apple AAC: 11 of 22).
209
+ - **Very quiet highs** (solo piano) leave little to measure.
210
+ - **Lossy at the source**: a phone recording or a master made from MP3 is reported suspect, and
211
+ rightly so, even when the shop sells it as lossless.
212
+ - A bench of 22 clips is small. Report a wrong verdict: it is how the bench grows.
213
+
214
+ ## πŸ“– Documentation
215
+
216
+ The full guide, how the detection works in detail, every result, the sources and the Python API
217
+ reference are on **[opalehq.github.io/trueflac](https://opalehq.github.io/trueflac/)**.
218
+
219
+ ## πŸ§ͺ Bench
220
+
221
+ [`bench/`](bench/README.md) rebuilds every clip above from recordings freely available on the
222
+ Internet Archive and scores trueflac on them. No audio is committed.
223
+
224
+ ## πŸ§‘β€πŸ’» For developers
225
+
226
+ ```console
227
+ uv sync
228
+ uv run pytest
229
+ uv run ruff check src tests bench scripts
230
+ uv run mypy src
231
+ ```
232
+
233
+ [uv](https://docs.astral.sh/uv/) installs Python 3.13 and the development tools from `uv.lock`.
234
+ Rules, the bench and commit conventions are in [CONTRIBUTING.md](CONTRIBUTING.md).
235
+
236
+ ## πŸ› οΈ Roadmap
237
+
238
+ - More genuine music in the bench, from more styles and eras.
239
+ - Opus through its own grid, before resampling.
240
+ - Fake high resolution: a CD file blown up to 96 kHz or 24 bits.
241
+
242
+ ## πŸ“š References
243
+
244
+ Detection of lossy coding in decoded audio:
245
+
246
+ - J. Herre, M. Schug, *Analysis of Decompressed Audio: The "Inverse Decoder"*, AES 109th
247
+ Convention, paper 5256, 2000. [AES E-Library](https://aes.org/publications/elibrary-page/?id=9082)
248
+ - S. Moehrs, J. Herre, R. Geiger, *Analysing Decompressed Audio with the "Inverse Decoder":
249
+ Towards an Operative Algorithm*, AES 112th Convention, paper 5576, 2002.
250
+ [AES E-Library](https://aes.org/publications/elibrary-page/?id=11346)
251
+ - J. Lacroix, Y. Prime, A. Remy, O. Derrien, *Lossless Audio Checker: A Software for the
252
+ Detection of Upscaling, Upsampling, and Transcoding in Lossless Musical Tracks*, AES 139th
253
+ Convention, 2015. [AES E-Library](https://aes.org/publications/elibrary-page/?id=17972)
254
+ - O. Derrien, *Detection of Genuine Lossless Audio Files: Application to the MPEG-AAC Codec*,
255
+ Journal of the Audio Engineering Society, vol. 67, no. 3, pp. 116–123, 2019.
256
+ [AES E-Library](https://aes.org/publications/elibrary/elibrary-page/?id=19892)
257
+
258
+ trueflac follows the idea of these papers (look for the coder's transform grid in the decoded
259
+ sound); its code is written from the codec specifications below, not from theirs.
260
+
261
+ Codecs:
262
+
263
+ - ISO/IEC 11172-3:1993, *Coding of moving pictures and associated audio, Part 3: Audio* (MPEG-1
264
+ Layer III). The synthesis window was read back from [minimp3](https://github.com/lieff/minimp3)
265
+ (CC0), and the line shapes checked against it.
266
+ - ISO/IEC 13818-7, *Advanced Audio Coding (AAC)*: sine and Kaiser-Bessel derived windows. The
267
+ ffmpeg AAC encoder uses the KBD window with alpha 4 for long blocks
268
+ ([libavcodec/aactab.c](https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/aactab.c)).
269
+ - Xiph.Org, [*Vorbis I specification*](https://www.xiph.org/vorbis/doc/Vorbis_I_spec.html),
270
+ section 4.3.1: the window slope y = sin(Ο€/2 Β· sinΒ²((x + 0.5)/n Β· Ο€)).
271
+
272
+ Tools:
273
+
274
+ - [flac-detective](https://github.com/Guillain-RDCDE/FLAC_Detective), the reference in the
275
+ results above.
276
+ - [libsndfile](https://libsndfile.github.io/libsndfile/) through
277
+ [soundfile](https://github.com/bastibe/python-soundfile), to read the files.
278
+
279
+ ## 🀝 Contribution
280
+
281
+ Issues and pull requests are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md). A wrong verdict is
282
+ the most useful report. Security problems go through [SECURITY.md](SECURITY.md).
283
+
284
+ ## πŸ“„ License
285
+
286
+ MIT, see [LICENSE](LICENSE). trueflac is part of [Opale](https://github.com/opalehq).
@@ -0,0 +1,12 @@
1
+ trueflac/__init__.py,sha256=aV5EPHshSe7Hb7EdI1_Vkt7qR8bOD4bsM9jo3BfRpWA,450
2
+ trueflac/analysis.py,sha256=3SvTerklVPyyH__M7S-9Iii66LBGbh0aiytAWBVJRDw,9789
3
+ trueflac/cli.py,sha256=spjQjePNuicJK8TamORs8YEp54cJq9mOBmjyeVHf-L0,1438
4
+ trueflac/grid.py,sha256=uzNG5rxiY53TszW-dDrCIIEtzMJnrDXjvRmW44xpPAc,8608
5
+ trueflac/mp3grid.py,sha256=qtxJo-zo9bWtdIBjUu0DV9FwHk_c-HRlYtpJhRmlkgY,7537
6
+ trueflac/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ trueflac/verdict.py,sha256=UvUBFUMkUteWzT6WYG_oFHBXg2sJnRVC4G0nZIZwxm4,3319
8
+ trueflac-0.1.0.dist-info/METADATA,sha256=uUzNQVzIlDaiMwQgctvw-6WZ5D11izjzWbEJr8DC4L4,12671
9
+ trueflac-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ trueflac-0.1.0.dist-info/entry_points.txt,sha256=ieruU-r7hp3huEJ2v66ixOHr-PB03t7HbWdBt4FvQvE,47
11
+ trueflac-0.1.0.dist-info/licenses/LICENSE,sha256=FXHLtoIlrJmVkrJhWRY_-UPRUhCAiL6Y2g-68vZoV3c,1062
12
+ trueflac-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ trueflac = trueflac.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Opale
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.