loopcutter 0.3.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.
- loopcutter/__init__.py +13 -0
- loopcutter/analyse.py +153 -0
- loopcutter/audio_io.py +46 -0
- loopcutter/cli.py +768 -0
- loopcutter/cut.py +197 -0
- loopcutter/grid.py +205 -0
- loopcutter/keydetect.py +77 -0
- loopcutter/keyreport.py +236 -0
- loopcutter/keys.py +346 -0
- loopcutter/manifest.py +245 -0
- loopcutter/markers.py +175 -0
- loopcutter/model.py +114 -0
- loopcutter/naming.py +95 -0
- loopcutter/onsets.py +117 -0
- loopcutter/prep.py +188 -0
- loopcutter/provenance.py +64 -0
- loopcutter/snap.py +215 -0
- loopcutter/stems.py +197 -0
- loopcutter/tags.py +135 -0
- loopcutter/timing.py +144 -0
- loopcutter/trackdb.py +77 -0
- loopcutter/verify.py +200 -0
- loopcutter/workspace.py +119 -0
- loopcutter-0.3.0.dist-info/METADATA +664 -0
- loopcutter-0.3.0.dist-info/RECORD +29 -0
- loopcutter-0.3.0.dist-info/WHEEL +5 -0
- loopcutter-0.3.0.dist-info/entry_points.txt +2 -0
- loopcutter-0.3.0.dist-info/licenses/LICENSE +21 -0
- loopcutter-0.3.0.dist-info/top_level.txt +1 -0
loopcutter/stems.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Stem separation before cutting.
|
|
2
|
+
|
|
3
|
+
audio-separator runs Demucs and the RoFormer models behind one API; the Demucs
|
|
4
|
+
command line stays as a fallback. Separators work at 44.1 kHz, so stems are
|
|
5
|
+
resampled to the master's rate and proven to line up with it and match its level
|
|
6
|
+
before any loop is cut from them. Raw output is cached per track.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Callable
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
import soundfile as sf
|
|
20
|
+
import soxr
|
|
21
|
+
|
|
22
|
+
from .audio_io import read_audio
|
|
23
|
+
|
|
24
|
+
DEFAULT_ENGINE = "audio-separator"
|
|
25
|
+
DEFAULT_MODEL = "htdemucs_6s.yaml"
|
|
26
|
+
STEM_NAMES = ("drums", "bass", "other", "vocals", "guitar", "piano", "instrumental")
|
|
27
|
+
ALIGN_SECONDS = 20.0
|
|
28
|
+
GAIN_TOLERANCE_DB = 1.0
|
|
29
|
+
MIN_STEM_SHARE = 0.01 # a stem under -20 dB of the master is too faint to align on its own
|
|
30
|
+
STEM_LAG_S = 0.001 # one stem against the full mix: band-limited stems (bass) correlate a few
|
|
31
|
+
# samples off with no timing error; the sum is held to one sample
|
|
32
|
+
COMPLETE_MARKER = "complete.json"
|
|
33
|
+
_STEM_IN_NAME = re.compile(r"\((\w+)\)")
|
|
34
|
+
|
|
35
|
+
Runner = Callable[[Path, Path, str], list[Path]]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ConformedStems(dict):
|
|
39
|
+
"""{stem: AIFF path}, plus what the proof measured: gain_db is the level of the
|
|
40
|
+
stems' sum against the master (least squares, 0 means matched) and clipped counts
|
|
41
|
+
the samples per stem that exceeded full scale and were clipped when written."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, paths: dict[str, Path], gain_db: float, clipped: dict[str, int]):
|
|
44
|
+
super().__init__(paths)
|
|
45
|
+
self.gain_db = gain_db
|
|
46
|
+
self.clipped = clipped
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _audio_separator(source: Path, out_dir: Path, model: str) -> list[Path]:
|
|
50
|
+
from audio_separator.separator import Separator
|
|
51
|
+
|
|
52
|
+
# 1.0 is the loosest threshold it accepts: stems are scaled only if they peak above
|
|
53
|
+
# full scale. soundfile writes the float result at the source's own bit depth.
|
|
54
|
+
separator = Separator(output_dir=str(out_dir), output_format="WAV",
|
|
55
|
+
normalization_threshold=1.0, use_soundfile=True)
|
|
56
|
+
separator.load_model(model_filename=model)
|
|
57
|
+
return [out_dir / Path(name).name for name in separator.separate(str(source))]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _demucs(source: Path, out_dir: Path, model: str) -> list[Path]:
|
|
61
|
+
subprocess.run(["demucs", "-n", model, "--float32", "--clip-mode", "none",
|
|
62
|
+
"-o", str(out_dir), str(source)], check=True)
|
|
63
|
+
return sorted((out_dir / model / source.stem).glob("*.wav"))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
ENGINES: dict[str, Runner] = {"audio-separator": _audio_separator, "demucs": _demucs}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def collect_stems(files) -> dict[str, Path]:
|
|
70
|
+
"""{stem: file} from separator output named 'Song_(Bass)_model.wav' or 'bass.wav'."""
|
|
71
|
+
found: dict[str, Path] = {}
|
|
72
|
+
for file in map(Path, files):
|
|
73
|
+
tags = _STEM_IN_NAME.findall(file.name)
|
|
74
|
+
name = (tags[-1] if tags else file.stem).lower()
|
|
75
|
+
if name in STEM_NAMES:
|
|
76
|
+
found[name] = file
|
|
77
|
+
return found
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def separate(source, out_dir, engine: str = DEFAULT_ENGINE, model: str = DEFAULT_MODEL,
|
|
81
|
+
runner: Runner | None = None) -> dict[str, Path]:
|
|
82
|
+
"""Raw separator output for one source, cached in
|
|
83
|
+
out_dir/<source name>/raw/<engine>-<model>. The cache counts only once a finished
|
|
84
|
+
run has marked it, and only for the source file it was made from."""
|
|
85
|
+
source = Path(source)
|
|
86
|
+
raw = Path(out_dir) / source.stem / "raw" / f"{engine}-{model}"
|
|
87
|
+
marker = raw / COMPLETE_MARKER
|
|
88
|
+
stat = source.stat()
|
|
89
|
+
stamp = {"size": stat.st_size, "mtime_ns": stat.st_mtime_ns}
|
|
90
|
+
try:
|
|
91
|
+
finished = json.loads(marker.read_text()) == stamp
|
|
92
|
+
except (OSError, ValueError):
|
|
93
|
+
finished = False
|
|
94
|
+
cached = collect_stems(sorted(raw.rglob("*.wav"))) if finished else {}
|
|
95
|
+
if cached:
|
|
96
|
+
return cached
|
|
97
|
+
shutil.rmtree(raw, ignore_errors=True)
|
|
98
|
+
raw.mkdir(parents=True)
|
|
99
|
+
found = collect_stems((runner or ENGINES[engine])(source, raw, model))
|
|
100
|
+
if not found:
|
|
101
|
+
raise RuntimeError(f"{engine} produced no stems for {source.name}")
|
|
102
|
+
marker.write_text(json.dumps(stamp))
|
|
103
|
+
return found
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def conform_stems(stems: dict[str, Path], master, out_dir) -> ConformedStems:
|
|
107
|
+
"""Resample each stem to the master's rate and prove the stems' sum lines up with
|
|
108
|
+
the master to the sample and matches its level, all in memory; only then swap the
|
|
109
|
+
set in as out_dir/<stem>.aiff (24-bit). Any failure leaves out_dir with no stems."""
|
|
110
|
+
out_dir = Path(out_dir)
|
|
111
|
+
partial = out_dir.with_name(out_dir.name + ".partial")
|
|
112
|
+
shutil.rmtree(partial, ignore_errors=True)
|
|
113
|
+
try:
|
|
114
|
+
master_audio, rate = read_audio(master)
|
|
115
|
+
audio = {name: _at_rate(path, rate) for name, path in sorted(stems.items())}
|
|
116
|
+
gain_db = _prove(audio, master_audio, rate, Path(master).name)
|
|
117
|
+
partial.mkdir(parents=True)
|
|
118
|
+
clipped = {}
|
|
119
|
+
for name, x in audio.items():
|
|
120
|
+
clipped[name] = int(np.count_nonzero(np.abs(x) > 1.0))
|
|
121
|
+
sf.write(str(partial / f"{name}.aiff"), np.clip(x, -1.0, 1.0), rate,
|
|
122
|
+
format="AIFF", subtype="PCM_24")
|
|
123
|
+
_swap_in(partial, out_dir)
|
|
124
|
+
except Exception:
|
|
125
|
+
shutil.rmtree(partial, ignore_errors=True)
|
|
126
|
+
for stale in out_dir.glob("*.aiff"):
|
|
127
|
+
stale.unlink()
|
|
128
|
+
raise
|
|
129
|
+
return ConformedStems({name: out_dir / f"{name}.aiff" for name in audio}, gain_db, clipped)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _at_rate(path: Path, rate: int) -> np.ndarray:
|
|
133
|
+
audio, sr = read_audio(path)
|
|
134
|
+
return audio if sr == rate else soxr.resample(audio, sr, rate, quality="VHQ")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _prove(audio: dict[str, np.ndarray], master: np.ndarray, rate: int, label: str) -> float:
|
|
138
|
+
"""Raise unless the stems' sum, and each stem loud enough to judge, line up with the
|
|
139
|
+
master over its loudest stretch, and the sum matches its level; return that level
|
|
140
|
+
in dB."""
|
|
141
|
+
total = None
|
|
142
|
+
for x in audio.values():
|
|
143
|
+
total = x if total is None else total[: len(x)] + x[: len(total)]
|
|
144
|
+
length = min(len(total), len(master))
|
|
145
|
+
span = min(length, int(ALIGN_SECONDS * rate))
|
|
146
|
+
window = _loudest(master[:length].mean(axis=1), span, hop=max(1, rate // 10))
|
|
147
|
+
ref = master[window].mean(axis=1)
|
|
148
|
+
energy = float(np.dot(ref, ref))
|
|
149
|
+
if energy == 0.0:
|
|
150
|
+
raise RuntimeError(f"{label} is silent")
|
|
151
|
+
lag, corr = _lag(total[window].mean(axis=1), ref)
|
|
152
|
+
if abs(lag) > 1:
|
|
153
|
+
raise RuntimeError(f"stems don't line up with {label}: {lag} samples out")
|
|
154
|
+
for name, x in audio.items():
|
|
155
|
+
part = x[window].mean(axis=1)
|
|
156
|
+
if np.dot(part, part) < MIN_STEM_SHARE * energy:
|
|
157
|
+
continue
|
|
158
|
+
stem_lag, _ = _lag(part, ref)
|
|
159
|
+
if abs(stem_lag) > STEM_LAG_S * rate:
|
|
160
|
+
raise RuntimeError(f"{name} doesn't line up with {label}: {stem_lag} samples out")
|
|
161
|
+
# least squares: the k that best fits mix = k * master at the aligned lag
|
|
162
|
+
gain = corr[lag] / energy
|
|
163
|
+
gain_db = 20 * np.log10(gain) if gain > 0 else float("-inf")
|
|
164
|
+
if not abs(gain_db) <= GAIN_TOLERANCE_DB:
|
|
165
|
+
raise RuntimeError(f"the stems' level doesn't match the master: {gain_db:+.1f} dB"
|
|
166
|
+
" - was the separator normalising?")
|
|
167
|
+
return float(gain_db)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _loudest(mono: np.ndarray, span: int, hop: int) -> slice:
|
|
171
|
+
"""The loudest span samples of mono, found to within hop samples."""
|
|
172
|
+
blocks = np.add.reduceat(np.square(mono), np.arange(0, len(mono), hop), dtype=np.float64)
|
|
173
|
+
sums = np.convolve(blocks, np.ones(max(1, span // hop)), "valid")
|
|
174
|
+
start = min(int(np.argmax(sums)) * hop, len(mono) - span)
|
|
175
|
+
return slice(start, start + span)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _lag(x: np.ndarray, ref: np.ndarray) -> tuple[int, np.ndarray]:
|
|
179
|
+
"""Samples by which x trails ref, with the cross-correlation it was read from."""
|
|
180
|
+
n = 2 * len(ref)
|
|
181
|
+
corr = np.fft.irfft(np.fft.rfft(x, n) * np.conj(np.fft.rfft(ref, n)), n)
|
|
182
|
+
lag = int(np.argmax(corr))
|
|
183
|
+
return (lag - n if lag > len(ref) else lag), corr
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _swap_in(new: Path, dest: Path) -> None:
|
|
187
|
+
"""Replace dest with new, carrying over what isn't a stem (the separator's raw cache
|
|
188
|
+
lives in dest when the track id is the master's name)."""
|
|
189
|
+
old = dest.with_name(dest.name + ".old")
|
|
190
|
+
shutil.rmtree(old, ignore_errors=True)
|
|
191
|
+
if dest.exists():
|
|
192
|
+
dest.rename(old)
|
|
193
|
+
for child in old.iterdir():
|
|
194
|
+
if child.suffix != ".aiff":
|
|
195
|
+
child.rename(new / child.name)
|
|
196
|
+
new.rename(dest)
|
|
197
|
+
shutil.rmtree(old, ignore_errors=True)
|
loopcutter/tags.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""ID3v2.3 tags on AIFF and WAV loops, so Sononym, Live and DJ apps see BPM, key and stem.
|
|
2
|
+
|
|
3
|
+
Tag AIFF by default. On WAV the tags go in an 'id3 ' chunk that some hardware
|
|
4
|
+
samplers reject.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import mutagen
|
|
12
|
+
from mutagen.aiff import AIFF
|
|
13
|
+
from mutagen.id3 import COMM, TBPM, TIT1, TIT2, TKEY, TPE1, TXXX
|
|
14
|
+
from mutagen.mp4 import MP4
|
|
15
|
+
from mutagen.wave import WAVE
|
|
16
|
+
|
|
17
|
+
from .keys import PC_NAMES, Key
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def id3_key(key: Key) -> str:
|
|
21
|
+
return PC_NAMES[key.pitch_class] + ("m" if key.mode == "minor" else "")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _open(path):
|
|
25
|
+
suffix = Path(path).suffix.lower()
|
|
26
|
+
if suffix in (".aif", ".aiff"):
|
|
27
|
+
return AIFF(str(path))
|
|
28
|
+
if suffix == ".wav":
|
|
29
|
+
return WAVE(str(path))
|
|
30
|
+
raise ValueError(f"can't tag {suffix} files; loops are AIFF or WAV")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _set(tags, frame, text: str) -> None:
|
|
34
|
+
tags.setall(frame.__name__, [frame(encoding=3, text=[text])])
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def write_loop_tags(path, *, bpm: float | None, key: Key | None = None, stem: str | None = None,
|
|
38
|
+
title: str | None = None, artist: str | None = None,
|
|
39
|
+
comment: str | None = None, extra: dict[str, str] | None = None) -> None:
|
|
40
|
+
audio = _open(path)
|
|
41
|
+
if audio.tags is None:
|
|
42
|
+
audio.add_tags()
|
|
43
|
+
tags = audio.tags
|
|
44
|
+
if bpm:
|
|
45
|
+
_set(tags, TBPM, str(int(round(bpm))) if abs(bpm - round(bpm)) < 1e-6 else f"{bpm:.2f}")
|
|
46
|
+
if key is not None:
|
|
47
|
+
_set(tags, TKEY, id3_key(key))
|
|
48
|
+
for frame, value in ((TIT1, stem), (TIT2, title), (TPE1, artist)):
|
|
49
|
+
if value:
|
|
50
|
+
_set(tags, frame, value)
|
|
51
|
+
notes = " ".join(n for n in (key.camelot if key else None, comment) if n)
|
|
52
|
+
if notes:
|
|
53
|
+
tags.setall("COMM", [COMM(encoding=3, lang="eng", desc="", text=[notes])])
|
|
54
|
+
for desc, value in (extra or {}).items(): # user-defined text frames, e.g. PROVENANCE_CODE, SOURCE
|
|
55
|
+
tags.setall(f"TXXX:{desc}", [TXXX(encoding=3, desc=desc, text=[value])])
|
|
56
|
+
audio.save(v2_version=3)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def write_extra_tags(path, extra: dict[str, str]) -> None:
|
|
60
|
+
"""Only the TXXX frames, on a loop that is already tagged."""
|
|
61
|
+
audio = _open(path)
|
|
62
|
+
if audio.tags is None:
|
|
63
|
+
audio.add_tags()
|
|
64
|
+
for desc, value in extra.items():
|
|
65
|
+
audio.tags.setall(f"TXXX:{desc}", [TXXX(encoding=3, desc=desc, text=[value])])
|
|
66
|
+
audio.save(v2_version=3)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def read_tag(path, frame: str) -> str | None:
|
|
70
|
+
tags = _open(path).tags
|
|
71
|
+
found = tags.getall(frame) if tags is not None else []
|
|
72
|
+
return str(found[0].text[0]) if found and found[0].text else None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _basic_tags(source) -> dict[str, str]:
|
|
76
|
+
audio = mutagen.File(str(source))
|
|
77
|
+
tags = getattr(audio, "tags", None)
|
|
78
|
+
if not tags:
|
|
79
|
+
return {}
|
|
80
|
+
found: dict[str, str] = {}
|
|
81
|
+
if hasattr(tags, "getall"):
|
|
82
|
+
for frame, name in (("TPE1", "artist"), ("TIT2", "title"), ("TKEY", "key"), ("TBPM", "bpm")):
|
|
83
|
+
values = tags.getall(frame)
|
|
84
|
+
if values and values[0].text:
|
|
85
|
+
found[name] = str(values[0].text[0])
|
|
86
|
+
elif isinstance(audio, MP4):
|
|
87
|
+
for atom, name in (("\xa9ART", "artist"), ("\xa9nam", "title")):
|
|
88
|
+
if atom in tags:
|
|
89
|
+
found[name] = str(tags[atom][0])
|
|
90
|
+
if "tmpo" in tags:
|
|
91
|
+
found["bpm"] = str(tags["tmpo"][0])
|
|
92
|
+
else:
|
|
93
|
+
for field, name in (("artist", "artist"), ("title", "title"), ("initialkey", "key"), ("bpm", "bpm")):
|
|
94
|
+
if field in tags:
|
|
95
|
+
found[name] = str(tags[field][0])
|
|
96
|
+
return found
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def copy_all_tags(source, dest) -> None:
|
|
100
|
+
"""Every ID3 frame of one AIFF or WAV onto another, over what's there, except DJ-app cue
|
|
101
|
+
data. Used when a master is rebuilt, so tags other apps wrote to it (a Mixed In Key key,
|
|
102
|
+
say) survive."""
|
|
103
|
+
tags = _open(source).tags
|
|
104
|
+
if not tags:
|
|
105
|
+
return
|
|
106
|
+
audio = _open(dest)
|
|
107
|
+
if audio.tags is None:
|
|
108
|
+
audio.add_tags()
|
|
109
|
+
for frame in tags.values():
|
|
110
|
+
if not _app_data(frame):
|
|
111
|
+
audio.tags.add(frame)
|
|
112
|
+
audio.save(v2_version=3)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _app_data(frame) -> bool:
|
|
116
|
+
"""DJ-app cue and grid data (and a stale length), which belong to the old audio."""
|
|
117
|
+
if frame.FrameID == "GEOB":
|
|
118
|
+
return str(frame.desc).startswith("Serato")
|
|
119
|
+
if frame.FrameID == "PRIV":
|
|
120
|
+
return str(frame.owner).upper().startswith("TRAKTOR")
|
|
121
|
+
return frame.FrameID == "TLEN"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def copy_basic_tags(source, dest) -> None:
|
|
125
|
+
"""Carry artist, title, key and BPM (never DJ-app cue data) onto a master."""
|
|
126
|
+
found = _basic_tags(source)
|
|
127
|
+
if not found:
|
|
128
|
+
return
|
|
129
|
+
audio = _open(dest)
|
|
130
|
+
if audio.tags is None:
|
|
131
|
+
audio.add_tags()
|
|
132
|
+
for name, frame in (("artist", TPE1), ("title", TIT2), ("key", TKEY), ("bpm", TBPM)):
|
|
133
|
+
if name in found:
|
|
134
|
+
_set(audio.tags, frame, found[name])
|
|
135
|
+
audio.save(v2_version=3)
|
loopcutter/timing.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Sample-accurate timing arithmetic.
|
|
2
|
+
|
|
3
|
+
Everything downstream depends on this module being exactly right. The rule
|
|
4
|
+
that matters: a loop's length is always derived from BPM and bar count, never
|
|
5
|
+
from a second timecode. Two timecodes rounded to milliseconds drift by a few
|
|
6
|
+
samples per loop, which is inaudible alone and catastrophic once eight loops
|
|
7
|
+
are stacked and left to run.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
_TIMECODE = re.compile(
|
|
16
|
+
r"^(?:(?P<h>\d+):)?(?P<m>\d+):(?P<s>\d{1,2}(?:\.\d+)?)$"
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def parse_position(value: str | float | int) -> float:
|
|
21
|
+
"""Parse a position into seconds.
|
|
22
|
+
|
|
23
|
+
Accepts bare seconds ("12.5"), M:SS.mmm ("1:23.456") and H:MM:SS.mmm.
|
|
24
|
+
"""
|
|
25
|
+
if isinstance(value, (int, float)):
|
|
26
|
+
return float(value)
|
|
27
|
+
|
|
28
|
+
text = str(value).strip()
|
|
29
|
+
if not text:
|
|
30
|
+
raise ValueError("empty position")
|
|
31
|
+
|
|
32
|
+
match = _TIMECODE.match(text)
|
|
33
|
+
if match:
|
|
34
|
+
hours = int(match.group("h") or 0)
|
|
35
|
+
minutes = int(match.group("m"))
|
|
36
|
+
seconds = float(match.group("s"))
|
|
37
|
+
if minutes >= 60 or seconds >= 60:
|
|
38
|
+
raise ValueError(f"invalid timecode {text!r}")
|
|
39
|
+
return hours * 3600 + minutes * 60 + seconds
|
|
40
|
+
|
|
41
|
+
try:
|
|
42
|
+
return float(text)
|
|
43
|
+
except ValueError as exc:
|
|
44
|
+
raise ValueError(f"cannot parse position {text!r}") from exc
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def samples_per_beat(bpm: float, sample_rate: int) -> float:
|
|
48
|
+
if bpm <= 0:
|
|
49
|
+
raise ValueError(f"bpm must be positive, got {bpm}")
|
|
50
|
+
return sample_rate * 60.0 / bpm
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def loop_length_samples(
|
|
54
|
+
bars: float, bpm: float, sample_rate: int, beats_per_bar: int = 4
|
|
55
|
+
) -> int:
|
|
56
|
+
"""Exact integer sample count for a loop of `bars` bars at `bpm`.
|
|
57
|
+
|
|
58
|
+
Rounds once, at the end. Never round per-beat and multiply.
|
|
59
|
+
"""
|
|
60
|
+
if bars <= 0:
|
|
61
|
+
raise ValueError(f"bars must be positive, got {bars}")
|
|
62
|
+
beats = bars * beats_per_bar
|
|
63
|
+
return int(round(beats * samples_per_beat(bpm, sample_rate)))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def bar_start_seconds(
|
|
67
|
+
downbeat: float, bar_index: int, bpm: float, beats_per_bar: int = 4
|
|
68
|
+
) -> float:
|
|
69
|
+
"""Seconds at which `bar_index` begins, counting the downbeat as bar 1."""
|
|
70
|
+
if bar_index < 1:
|
|
71
|
+
raise ValueError(f"bar_index is 1-based, got {bar_index}")
|
|
72
|
+
seconds_per_bar = beats_per_bar * 60.0 / bpm
|
|
73
|
+
return downbeat + (bar_index - 1) * seconds_per_bar
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class CutWindow:
|
|
78
|
+
"""A resolved, sample-accurate extraction window."""
|
|
79
|
+
|
|
80
|
+
start_sample: int
|
|
81
|
+
length_samples: int
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def end_sample(self) -> int:
|
|
85
|
+
return self.start_sample + self.length_samples
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def resolve_window(
|
|
89
|
+
start_seconds: float,
|
|
90
|
+
bars: float,
|
|
91
|
+
bpm: float,
|
|
92
|
+
sample_rate: int,
|
|
93
|
+
beats_per_bar: int = 4,
|
|
94
|
+
) -> CutWindow:
|
|
95
|
+
if start_seconds < 0:
|
|
96
|
+
raise ValueError(f"start must be >= 0, got {start_seconds}")
|
|
97
|
+
return CutWindow(
|
|
98
|
+
start_sample=int(round(start_seconds * sample_rate)),
|
|
99
|
+
length_samples=loop_length_samples(bars, bpm, sample_rate, beats_per_bar),
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def tiling_error_samples(
|
|
104
|
+
long_bars: float,
|
|
105
|
+
short_bars: float,
|
|
106
|
+
bpm: float,
|
|
107
|
+
sample_rate: int,
|
|
108
|
+
beats_per_bar: int = 4,
|
|
109
|
+
) -> int:
|
|
110
|
+
"""How far a short loop drifts against a long one over the long one's span.
|
|
111
|
+
|
|
112
|
+
Zero means they tile exactly. Non-zero means the short loop's rounded
|
|
113
|
+
sample count does not divide the long one, so repeated playback slowly
|
|
114
|
+
slips. This is arithmetic, not a bug: at 128 BPM and 44.1kHz a bar is
|
|
115
|
+
82687.5 samples, and you cannot have half a sample.
|
|
116
|
+
|
|
117
|
+
Which rate tiles depends on the tempo. At 48 kHz half bars come out exact
|
|
118
|
+
at 120, 125, 128, 144, 150 and 160 BPM; at 44.1 kHz at 120, 125, 126, 135,
|
|
119
|
+
140, 144, 147, 150 and 160. `rates_that_tile` answers it for any tempo.
|
|
120
|
+
"""
|
|
121
|
+
long_len = loop_length_samples(long_bars, bpm, sample_rate, beats_per_bar)
|
|
122
|
+
short_len = loop_length_samples(short_bars, bpm, sample_rate, beats_per_bar)
|
|
123
|
+
if short_len <= 0 or short_len > long_len:
|
|
124
|
+
return 0
|
|
125
|
+
repeats = round(long_bars / short_bars)
|
|
126
|
+
return abs(short_len * repeats - long_len)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def tiling_error_ms(long_bars: float, short_bars: float, bpm: float, sample_rate: int,
|
|
130
|
+
beats_per_bar: int = 4) -> float:
|
|
131
|
+
"""tiling_error_samples expressed in milliseconds."""
|
|
132
|
+
return tiling_error_samples(long_bars, short_bars, bpm, sample_rate, beats_per_bar) \
|
|
133
|
+
/ sample_rate * 1000
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def rates_that_tile(bars: float, bpm: float, beats_per_bar: int = 4,
|
|
137
|
+
rates: tuple[int, ...] = (44100, 48000)) -> list[int]:
|
|
138
|
+
"""Sample rates at which `bars` at `bpm` is a whole number of samples."""
|
|
139
|
+
exact = []
|
|
140
|
+
for rate in rates:
|
|
141
|
+
samples = bars * beats_per_bar * rate * 60 / bpm
|
|
142
|
+
if abs(samples - round(samples)) < 1e-6:
|
|
143
|
+
exact.append(rate)
|
|
144
|
+
return exact
|
loopcutter/trackdb.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""tracks.csv: one row of analysis per source track.
|
|
2
|
+
|
|
3
|
+
scan proposes these values; the override_* columns are yours and scan never
|
|
4
|
+
touches them. The cut path never reads a model, only the manifest.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import csv
|
|
10
|
+
from dataclasses import asdict, fields
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from .model import TrackRecord
|
|
14
|
+
|
|
15
|
+
FIELDS = [f.name for f in fields(TrackRecord)]
|
|
16
|
+
_TYPES = {f.name: f.type for f in fields(TrackRecord)} # strings, e.g. "float | None"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _parse(kind: str, raw: str | None):
|
|
20
|
+
if kind == "str":
|
|
21
|
+
return raw or ""
|
|
22
|
+
if raw in ("", None):
|
|
23
|
+
return None if "None" in kind else (0 if kind == "int" else 0.0)
|
|
24
|
+
return int(float(raw)) if kind == "int" else float(raw)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _format(value):
|
|
28
|
+
if value is None:
|
|
29
|
+
return ""
|
|
30
|
+
return f"{value:.6f}" if isinstance(value, float) else value
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def track_id_for(master) -> str:
|
|
34
|
+
return Path(master).stem
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def load_tracks(path) -> dict[str, TrackRecord]:
|
|
38
|
+
path = Path(path)
|
|
39
|
+
if not path.exists():
|
|
40
|
+
return {}
|
|
41
|
+
records: dict[str, TrackRecord] = {}
|
|
42
|
+
with path.open(newline="", encoding="utf-8-sig") as handle:
|
|
43
|
+
for row_number, row in enumerate(csv.DictReader(handle), start=2):
|
|
44
|
+
values = {}
|
|
45
|
+
for name in FIELDS:
|
|
46
|
+
try:
|
|
47
|
+
values[name] = _parse(_TYPES[name], row.get(name))
|
|
48
|
+
except ValueError as exc:
|
|
49
|
+
raise ValueError(f"row {row_number}, column {name!r}: {exc}") from None
|
|
50
|
+
track_id = values["track_id"]
|
|
51
|
+
if not track_id:
|
|
52
|
+
raise ValueError(f"row {row_number}: track_id is empty")
|
|
53
|
+
if track_id in records:
|
|
54
|
+
raise ValueError(f"row {row_number}: track_id {track_id!r} is a duplicate")
|
|
55
|
+
records[track_id] = TrackRecord(**values)
|
|
56
|
+
return records
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def save_tracks(path, records: dict[str, TrackRecord]) -> None:
|
|
60
|
+
path = Path(path)
|
|
61
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
62
|
+
temp = path.with_suffix(".partial.csv")
|
|
63
|
+
with temp.open("w", newline="", encoding="utf-8") as handle:
|
|
64
|
+
writer = csv.DictWriter(handle, fieldnames=FIELDS)
|
|
65
|
+
writer.writeheader()
|
|
66
|
+
for record in sorted(records.values(), key=lambda r: r.track_id):
|
|
67
|
+
writer.writerow({k: _format(v) for k, v in asdict(record).items()})
|
|
68
|
+
temp.replace(path)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def find_record(records: dict[str, TrackRecord], path) -> TrackRecord | None:
|
|
72
|
+
target = Path(path).expanduser().resolve()
|
|
73
|
+
for record in records.values():
|
|
74
|
+
if target in (Path(record.source).expanduser().resolve(),
|
|
75
|
+
Path(record.master).expanduser().resolve()):
|
|
76
|
+
return record
|
|
77
|
+
return None
|