diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index ed86379..dbe9aeb 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "earshot", - "version": "1.0.0", + "version": "1.1.0", "description": "Make sound effects from a request in words: interface sounds, everyday foley, ambience, game, film and motion sounds and drums, computed when asked (the realistic ones learned from public-domain recordings, no audio shipped), and build what the catalogue lacks from its parts. Listen to sound an agent cannot hear: describe, match, measure and critique it.", "author": { "name": "Leon Lin" diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fe5b43..9051aee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,48 @@ # Changelog +## 1.1.0 - unreleased + +Fixes from the community, thanks to @liugedragon and @fcy222fcy, and three found by an automated review of the 1.0 +release. + +### Fixed + +**Making sounds** + +- **`make --listen` hears the take it wrote.** For ogg, mp3, m4a and webm it rendered a new single event to listen + to, so the `heard` line of "footsteps" with `events=8` described one step. It now hears the samples it wrote. +- **A recipe cannot ask for an endless timeline.** Events whose gaps grow (`"faster": 2`) could start billions of + seconds in and allocate far more memory than any machine has before the recipe's length cut them; the last event + of a layer now starts within 120 s, or the recipe is refused with one sentence. +- **`build` hears a sound file at its own sample rate**: a 24 kHz file was measured half as long and twice as high. +- **A set refuses names and sprites that would overwrite each other** (#39): `tap` with two takes and another sound + named `tap_1`, two names with the same file name in different folders, or a sprite named like a take or + `manifest.json` stop with one sentence before anything is written. +- **`pack` refuses a name count that differs from the file count** (#41), before it reads any audio. +- **A bank sound keeps its asked peak after resampling** (#33). +- **A named theme's axes no longer share state with its preset** (#34): changing one no longer changed the other. +- **A walk's distance tilt uses the composed space** (#48). + +**Listening and video** + +- **The selected audio track keeps its level and stereo image** (#28). In a file with several audio tracks, the + stereo decode read the channel count of the first track while ffmpeg decoded another: a stereo track could become + dual mono, a mono track 3 dB too quiet. The decode version is 3, so the decode caches fill again once. +- **Picture cut timing uses the frame rate of the decoded track** (#45), not the first video track's: cuts in a + file with two video tracks of different rates landed at the wrong times. +- **Local media names are unambiguous for ffmpeg** (#47): a file named `take:01.wav` or starting with `-` is read + and written as a file, not as a protocol or an option. +- **A failed write to an optional media cache is no longer an error** (#42): the analysis goes on without the cache. +- **Timeline caches are keyed by the parsed cues** (#43), and **timeline ranges are bounded by the decoded + samples** (#44). +- **The search index stays alive behind its cached positions** (#36). +- **`earshot --threads 2 ` loads only that command** (#46): the value of `--threads` was read as the + command word, so every command module was loaded and the start took about three times as long. + +### Changed + +- `docs/TESTING.md` says that torch and transformers come with the `listen` extra. + ## 1.0.0 - 2026-11-20 earshot now makes sounds as well as listening to them. An agent asks for a sound in words and earshot renders a new diff --git a/docs/MAKE.md b/docs/MAKE.md index 4dc393b..29211a3 100644 --- a/docs/MAKE.md +++ b/docs/MAKE.md @@ -594,7 +594,7 @@ cookbook recipe (`"recipe": "thunder_far"`, one level deep: a storm can hold a b | `at` | seconds: where the layer starts | | `fade_in`, `fade_out` | seconds: fades at its ends; when not said, an ambience gets 0.1 and 0.3 s and a source 0.01 and 0.02 s | | `swell`, `decay` | seconds: a slow rise from 30 dB down at its start, a slow fall to nothing at its end | -| `events` | `{"count", "gap", "faster", "softer", "loose"}`: the layer 2 to 64 times, each a new take, `gap` seconds apart; each gap `faster` times the one before (under 1: faster and faster); each event `softer` dB against the one before; `loose` 0 to 1 moves each up to half its gap early or late | +| `events` | `{"count", "gap", "faster", "softer", "loose"}`: the layer 2 to 64 times, each a new take, `gap` seconds apart; each gap `faster` times the one before (under 1: faster and faster); each event `softer` dB against the one before; `loose` 0 to 1 moves each up to half its gap early or late; the last event starts within 120 s | | `scatter` | `{"rate", "rate_to", "dur", "pitch", "gain", "pan", "grain"}`: the layer many times at random moments, `rate` events a second (0.5 to 400) moving to `rate_to` by the end, over `dur` seconds; each event up to `pitch` semitones (0 to 12) higher or lower, up to `gain` dB (0 to 40) softer, up to `pan` (0 to 1) to either side; with `grain` (0.005 to 2 s) each event is a random piece of that length of the take. Every event another take where the design has several recordings. Rain from drops, applause from claps, hail, gravel, a crowd, a swarm | | `level` | `[[time, dB], ...]`: the layer's loudness over time, from its start, straight in dB between the points (-60 to 12) | | `bend` | `[[time, semitones], ...]`: the layer's pitch over the heard time as a tape does it (-24 to 12): a moo bent into a whale's song | diff --git a/docs/TESTING.md b/docs/TESTING.md index a5d97d2..6e4c4c4 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -15,8 +15,8 @@ python3.12 -m venv .venv-fast EARSHOT_OFFLINE=1 HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 MPLBACKEND=Agg OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 .venv-fast/bin/python -m pytest -q -p no:cacheprovider -rs tests ``` -This intentionally leaves out Torch and Transformers, which remain required by -the normal package metadata. It is **not** a full installation or a packaging +This intentionally leaves out Torch and Transformers, which come with the +`listen` extra; the tests that need them skip without them. It is **not** a full installation or a packaging dependency check. Follow the README's installation instructions when running model-dependent features. Do not run `doctor --load` in this reduced environment. diff --git a/earshot/__init__.py b/earshot/__init__.py index fc31dd2..584929c 100644 --- a/earshot/__init__.py +++ b/earshot/__init__.py @@ -15,7 +15,7 @@ """ import importlib -__version__ = '1.0.0' +__version__ = '1.1.0' # modules that are callable as their main function (see _callable.py) _CALLABLE = {'describe', 'match', 'compare', 'realness', 'timeline', 'sheet', 'critique', 'profile'} diff --git a/earshot/audio.py b/earshot/audio.py index f406725..476b573 100644 --- a/earshot/audio.py +++ b/earshot/audio.py @@ -8,6 +8,9 @@ m = load('kick.ogg', mono=True) # (n,) seg = load('long.wav', start=1.2, end=1.8, mono=True) +Track selection stays with ffmpeg (including default-track preferences); probe() reports the first audio track, +which may not be the selected track in a multi-track file. + Levels: the stereo decode keeps true sample levels (a mono file is duplicated to both channels at unity gain), so measure peaks and loudness on it (features.measure does). mono=True is ffmpeg's downmix, which sums a stereo source at -3 dB per channel: correlated stereo reads up to +3 dB hotter than mean(L, R). It is the models' input convention @@ -33,7 +36,7 @@ class AudioError(RuntimeError): pass -DECODE_VERSION = 2 # bump when decoded samples change (derived caches may key on it) +DECODE_VERSION = 3 # bump when decoded samples change (derived caches may key on it) def _sample_hash(path, size, blocks=16, block=4096): @@ -76,13 +79,11 @@ def replace_quietly(tmp, dst, tries=5): return False -def _src_channels(path): - try: - out = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=channels', - '-of', 'csv=p=0', path], capture_output=True, text=True, timeout=60).stdout.strip() - return int(out.splitlines()[0]) if out else 0 - except Exception: # noqa: BLE001 - return 0 +def _ffmpeg_input(path): + """Disambiguate existing local files without rewriting URLs or other FFmpeg inputs.""" + path = os.fsdecode(path) + # Do not normalize away symlink/.. components or change native drive-relative paths. + return os.path.join(os.curdir, path) if os.path.exists(path) else path def file_id(path): @@ -104,9 +105,14 @@ def _ffmpeg_reason(err): def _decode(path, sr, ch): - up = ch == 2 and _src_channels(path) == 1 # ffmpeg would upmix mono at -3 dB; duplicate at unity instead - p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', path, '-vn', '-f', 'f32le', '-acodec', 'pcm_f32le', - '-ac', '1' if up else str(ch), '-ar', str(sr), '-'], capture_output=True) + cmd = ['ffmpeg', '-v', 'error', '-nostdin', '-i', _ffmpeg_input(path), '-vn'] + if ch == 2: + # Inspect the actually selected input layout, not the first audio stream: ffmpeg may select a later track. + # Keep mono at unity; stereo and surround retain ffmpeg's usual stereo downmix. + cmd += ['-af', "aformat=channel_layouts=mono|stereo," + "aeval=exprs='val(0)|val(if(eq(nb_in_channels,1),0,1))':channel_layout=stereo"] + cmd += ['-f', 'f32le', '-acodec', 'pcm_f32le', '-ac', str(ch), '-ar', str(sr), '-'] + p = subprocess.run(cmd, capture_output=True) err = p.stderr.decode(errors='replace') if p.returncode != 0 or not p.stdout: pr = probe(path) @@ -116,8 +122,6 @@ def _decode(path, sr, ch): raise AudioError(f'{path}: no audio stream') raise AudioError(f'cannot decode {path}: {_ffmpeg_reason(err)}') x = np.frombuffer(p.stdout, np.float32).copy() - if up: - return np.repeat(x[:, None], 2, axis=1) return x.reshape(-1, ch) if ch > 1 else x @@ -129,7 +133,6 @@ def load(path, sr=SR, mono=False, start=None, end=None, cache=True): x = None npy = None if cache: - config.ensure_dirs() npy = os.path.join(config.DEC_CACHE, _key(path, sr, ch) + '.npy') if os.path.exists(npy): try: @@ -139,9 +142,7 @@ def load(path, sr=SR, mono=False, start=None, end=None, cache=True): if x is None: x = _decode(path, sr, ch) if npy: - tmp = f'{npy}.{os.getpid()}.tmp.npy' - np.save(tmp, x) - replace_quietly(tmp, npy) + write_cache(npy, lambda tmp: np.save(tmp, x)) bad = ~np.isfinite(x) if bad.any(): # one NaN / Inf sample breaks every analysis downstream (#12) bad = bad.any(axis=-1) if x.ndim == 2 else bad @@ -175,7 +176,7 @@ def probe(path): out = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'stream=codec_type,codec_name,sample_rate,channels,bit_rate,width,height,r_frame_rate:' 'stream_disposition=attached_pic:' - 'format=duration,bit_rate', '-of', 'json', path], + 'format=duration,bit_rate', '-of', 'json', _ffmpeg_input(path)], capture_output=True, text=True, timeout=60).stdout j = json.loads(out or '{}') except Exception as e: # noqa: BLE001 @@ -251,3 +252,26 @@ def check_paths(paths, what='paths'): def db(v, floor=1e-12): return float(20 * np.log10(max(float(v), floor))) + + +def write_cache(path, write): + """Best-effort cache write; only filesystem errors are optional, not errors in the producer.""" + import tempfile + tmp = None + try: + folder = os.path.dirname(path) or '.' + os.makedirs(folder, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=folder, prefix=os.path.basename(path) + '.', + suffix=os.path.splitext(path)[1], delete=False) as fh: + tmp = fh.name + write(tmp) + return replace_quietly(tmp, path) + except OSError: + return False + finally: + if tmp is not None: + try: + os.remove(tmp) + except OSError: + pass + diff --git a/earshot/brief.py b/earshot/brief.py index 8b9535d..570b7df 100644 --- a/earshot/brief.py +++ b/earshot/brief.py @@ -2203,8 +2203,8 @@ def _twin(sid, out, idx): family that is that job, not one that merely lists it: kick/deep is a drum, not a deep impact), or None""" if not idx: return None - if _cache.get('pos_key') != id(idx): - _cache['pos_key'], _cache['pos'] = id(idx), {r['id']: k for k, r in enumerate(idx[0])} + if _cache.get('pos_idx') is not idx: + _cache['pos_idx'], _cache['pos'] = idx, {r['id']: k for k, r in enumerate(idx[0])} pos, terms = _cache['pos'], idx[1] fam, name, jobs = sid.split('/')[0], _name_words(sid), terms[pos[sid]]['family'] for r in out: @@ -2234,8 +2234,8 @@ def _preferred(b, sid, out, idx, twins=True): and _key(name_.split('_') + fam_.split('_')) not in _reverse()['c']): return None rows, terms = idx[0], idx[1] - if _cache.get('pos_key') != id(idx): - _cache['pos_key'], _cache['pos'] = id(idx), {r['id']: k for k, r in enumerate(rows)} + if _cache.get('pos_idx') is not idx: + _cache['pos_idx'], _cache['pos'] = idx, {r['id']: k for k, r in enumerate(rows)} pos = _cache['pos'] fam, prior = sid.split('/')[0], rows[pos[sid]].get('prior', 1.0) if 'real' in rows[pos[sid]].get('tags', ()): diff --git a/earshot/build.py b/earshot/build.py index 1035a7e..d30ed04 100644 --- a/earshot/build.py +++ b/earshot/build.py @@ -1450,8 +1450,11 @@ def hear(recipe, words=None, without=(), seed=SEED, ears=None, near=None, layers y, meta = take[:2] elif isinstance(recipe, str) and os.path.isfile(recipe) and not recipe.lower().endswith('.json'): import soundfile as sf - y, _ = sf.read(recipe, always_2d=True) + y, rate = sf.read(recipe, always_2d=True) y = np.asarray(y, np.float64) + if rate != 48000: # every measure, the audit and the ears read 48 kHz samples + import soxr + y = np.asarray(soxr.resample(y, rate, 48000, quality='HQ'), np.float64) from .sounds import registry from types import SimpleNamespace meta = {'checks': registry.audit(y, SimpleNamespace(kind='object', pitch=None, loop=False, allows=()))} diff --git a/earshot/cli.py b/earshot/cli.py index bb3a6cc..28184f9 100644 --- a/earshot/cli.py +++ b/earshot/cli.py @@ -126,12 +126,27 @@ def _missing_line(cmd, said): return 1 +def _command(argv): + """the command word in argv: its first argument that is not a flag, skipping the value of a global option that + takes one, so `--threads 4 describe x.wav` names `describe` (its value `4` is not a command, and reading it as one + registered every module, which is what `--threads=4` avoids)""" + value_next = False + for a in argv: + if value_next: + value_next = False + elif a == '--threads': + value_next = True + elif not a.startswith('-'): + return a + return None + + def main(argv=None): argv = sys.argv[1:] if argv is None else list(argv) _hold_blas(argv) ap = _parser() sub = ap.add_subparsers(dest='command', metavar='') - cmd = next((a for a in argv if not a.startswith('-')), None) + cmd = _command(argv) if '--version' in (argv[:argv.index(cmd)] if cmd in argv else argv): # no command module needs to load print(_version()) return 0 diff --git a/earshot/forge/bank.py b/earshot/forge/bank.py index ce0e9d4..99cad02 100644 --- a/earshot/forge/bank.py +++ b/earshot/forge/bank.py @@ -313,6 +313,7 @@ def render(sound_id, seed=None, dur=None, apex=None, pitch=None, peak_db=PEAK_DB final); dur / apex (s), pitch ('E5' or Hz) aim it through the recipe's own parameters (earshot.forge.knobs); peak_db = its sample peak (0 dBFS or less); weight scales that by 6 dB per doubling (1 = peak_db, 0.5 = 6 dB down; a level over 0 dBFS is refused: level()). sr (one of SRS) != 48000 resamples the finished take (soxr). + The sample peak is set after conversion. Loudness and the audit use a 48 kHz analysis copy. checks=False skips the model-free audit (meta['checks'] None).""" lv = level(peak_db, weight) sr = check_sr(sr) @@ -330,14 +331,19 @@ def render(sound_id, seed=None, dur=None, apex=None, pitch=None, peak_db=PEAK_DB y = normalize(x, level_db).astype(np.float32) meta = {'id': sid, 'seed': int(e['seed'] if seed is None else seed), 'sr': int(sr), **measure(y), 'edits': edits, 'checks': None} + if int(sr) != SR: + import soxr + from .polish import lufs_max + # The final sample rate can introduce new peaks; set the requested level after conversion. + y = normalize(soxr.resample(y, SR, int(sr)), level_db).astype(np.float32) + meta.update(times(y, sr)) + meta['peak_db'] = round(float(20 * np.log10(np.abs(y).max() + 1e-12)), 2) + # Loudness and the artifact audit use a 48 kHz analysis copy, not a mislabelled final array. + meta['lufs_m_max'] = round(float(lufs_max(soxr.resample(y.astype(np.float64), sr, SR))), 2) if checks: from . import sfx - meta['checks'] = sfx.check(y, category=e.get('category'), sound=sid) + meta['checks'] = sfx.check(y, sr=sr, category=e.get('category'), sound=sid) add_warning(meta['checks'], knobs.pitch_warning(edits)) - if int(sr) != SR: - import soxr - y = np.asarray(soxr.resample(y, SR, int(sr)), np.float32) - meta['dur_s'] = round(len(y) / int(sr), 4) return y, meta diff --git a/earshot/llm.py b/earshot/llm.py index 1a39991..47ade4a 100644 --- a/earshot/llm.py +++ b/earshot/llm.py @@ -256,7 +256,7 @@ def encode(path, start=None, end=None, max_seconds=600.0, kbps=KBPS): trimmed = b - a > max_seconds if trimmed: b = a + max_seconds - cmd = ['ffmpeg', '-v', 'error', '-nostdin', '-ss', f'{a:.3f}', '-i', path, '-t', f'{b - a:.3f}', '-vn', '-ac', '1', + cmd = ['ffmpeg', '-v', 'error', '-nostdin', '-ss', f'{a:.3f}', '-i', audio._ffmpeg_input(path), '-t', f'{b - a:.3f}', '-vn', '-ac', '1', '-ar', '44100', '-c:a', 'libmp3lame', '-b:a', f'{kbps}k', '-f', 'mp3', '-'] p = subprocess.run(cmd, capture_output=True) if p.returncode != 0 or not p.stdout: diff --git a/earshot/make.py b/earshot/make.py index 12cbefd..85de610 100644 --- a/earshot/make.py +++ b/earshot/make.py @@ -758,14 +758,22 @@ def make(want=None, out=None, sound=None, n=1, seed=0, theme=None, listen=False, req['dur'] = round(0.02 + (int(perf[1]) - 1) * float(b['gap']) + ring, 3) n = takes_asked(b, pick['why'], perf, n) paths = _paths(out or pick['id'].replace('/', '_') + '.' + (fmt or 'wav'), n, fmt) - takes = [] + takes, first = [], None for i, p in enumerate(paths): y, meta = take(pick['id'], seed + i, req, lufs, perform=perf) + first = y if first is None else first master.write(p, y, sr=sr, mono=mono, bits=bits) takes.append({**meta, 'file': p}) if listen and heard is None: - heard = _heard(paths[0] if paths[0].lower().endswith(('.wav', '.flac')) else _tmp_wav(pick['id'], seed, req), - ([want] if want else []) + list(registry.get(pick['id']).says)) + # the first take as it was delivered (its performance and level): a wav or flac is heard as written, any + # other format from the same samples in a wav, so that what is heard is what was handed over + queries = ([want] if want else []) + list(registry.get(pick['id']).says) + if paths[0].lower().endswith(('.wav', '.flac')): + heard = _heard(paths[0], queries) + else: + import tempfile + with tempfile.TemporaryDirectory() as tmp: + heard = _heard(master.write(os.path.join(tmp, 'heard.wav'), first, sr=sr, mono=mono), queries) why = brief.shown(b, pick['why']) lines = [_line(t, t['file'], ', '.join(why) if i == 0 else '') for i, t in enumerate(takes)] played = takes[0].get('performance') @@ -818,13 +826,6 @@ def make(want=None, out=None, sound=None, n=1, seed=0, theme=None, listen=False, return res -def _tmp_wav(sound, seed, req): - import tempfile - from .synth import master - y, _ = take(sound, seed, req) - return master.write(os.path.join(tempfile.mkdtemp(), 'heard.wav'), y) - - def found_by(why, sound=None): """the words the catalogue's first design was found by, a phrase ("ph:launch rocket") as its words: when they hold every word of a cookbook thing the catalogue has that sound itself, and its design answers, not the recipe. With @@ -971,6 +972,10 @@ def make_set(spec, out=None, theme=None, fmt=None, seed=0, mono=None, lufs=None, "lufs": -18, "sprite": "sprite.webm", "sounds": [{"name": "tap", "want": "a soft tap for buttons"}, {"name": "success", "want": "a quick success sound", "axes": {"bright": 0.2}}]} + Expanded take names must be unique ("tap" with n=2 would conflict with "tap_1"); a conflict is refused before + that name is rendered and before anything is written. Names also identify manifest rows, so directory prefixes + do not distinguish two takes with the same basename. Sprite audio and map paths must not overwrite takes or + manifest.json; such a collision is refused before anything is written. "set" starts from a ready-made list; "sounds" adds to it, or changes the sound of the same name. Each sound takes name (the file name) and want (words) and / or sound (a design id), plus pitch, dur, voice, material, seed, n, axes, lufs, events (a thing done in a row, as in `make`) and loop (false: once); or name and recipe (a @@ -1026,9 +1031,24 @@ def make_set(spec, out=None, theme=None, fmt=None, seed=0, mono=None, lufs=None, fmts = _formats(fmt or spec.get('format') or 'wav') mono = spec.get('mono', False) if mono is None else mono top = lufs if lufs is not None else spec.get('lufs') + sprite = sprite or spec.get('sprite') + outs = [] + if sprite: + stem, ext = os.path.splitext(os.path.join(out, os.path.basename(sprite))) + ext = ext.lower().lstrip('.') + outs = [f'{stem}.{f}' for f in fmts] if not ext or ext in fmts else [f'{stem}.{ext}'] + seen = set() # take names: each names one manifest row and one sprite region, so one name is one file + + def claim(p): + key = os.path.normcase(os.path.splitext(os.path.basename(p))[0]) + if key in seen: + raise ValueError(f'take name {os.path.basename(p)!r} is used more than once: rename a sound of the set') + seen.add(key) + rows, lines, ys, alts, missed, first, played, pending, takes = [], [], [], {}, {}, {}, {}, [], {} for it in items: if it.get('recipe') is not None: # a sound built from parts (earshot.recipe), levelled with the set + claim(os.path.join(out, f'{it["name"]}.{fmts[0]}')) lines.append(None) pending.append({**_set_recipe(it, seed, top, out, fmts[0]), 'line': len(lines) - 1}) lines += [f' {note}' for note in pending[-1]['meta'].get('notes', ())] @@ -1058,8 +1078,11 @@ def make_set(spec, out=None, theme=None, fmt=None, seed=0, mono=None, lufs=None, alone = it.get('lufs') is None and top is None and not d.loop and d.kind not in registry.LOUDEST level = None if alone else it.get('lufs', (TOP if top is None else top) + WEIGHT.get(d.kind, -4.0)) k = int(it.get('n') or b['n'] or 1) + paths = _paths(os.path.join(out, f'{it["name"]}.{fmts[0]}'), k, fmts[0]) + for p in paths: + claim(p) mine = {} # the recordings this name played: {n: meta['member']} - for j, p in enumerate(_paths(os.path.join(out, f'{it["name"]}.{fmts[0]}'), k, fmts[0])): + for j, p in enumerate(paths): s = int(it['seed']) + j if it.get('seed') is not None else seed + takes.get(d.id, 0) takes[d.id] = takes.get(d.id, 0) + 1 y, meta = take(d.id, s, _request(b, theme), lufs=level, perform=perf) @@ -1103,6 +1126,18 @@ def make_set(spec, out=None, theme=None, fmt=None, seed=0, mono=None, lufs=None, lines.append(' ' + (guess(b, cands, alts[it['name']]) or 'also: ' + ', '.join(alts[it['name']]))) if unknown: lines.append(f" not understood: {', '.join(unknown)}") + man = os.path.join(out, 'manifest.json') + if outs: # the sprite and its map must not land on a take or the manifest: checked before any write + taken = {os.path.normcase(os.path.abspath(man))} + for q in pending: + stem = os.path.splitext(q['p'])[0] + own = _loop_formats(fmts) if q['meta'].get('loop') else fmts + taken.update(os.path.normcase(os.path.abspath(f'{stem}.{f}')) for f in own) + for p in outs + [os.path.splitext(outs[0])[0] + '.json']: + key = os.path.normcase(os.path.abspath(p)) + if key in taken: + raise ValueError(f'sprite output {p!r} would overwrite a set file: rename the sprite') + taken.add(key) balance(pending, quiet) for q in pending: y, meta, d, p = q['y'], q['meta'], q['d'], q['p'] @@ -1119,19 +1154,14 @@ def make_set(spec, out=None, theme=None, fmt=None, seed=0, mono=None, lufs=None, **({'member': meta['member']} if meta.get('member') else {})}) shown = p if len(own) == 1 else f'{stem}.{{{",".join(own)}}}' lines[q['line']] = _line(meta, shown, q['why']) - man = os.path.join(out, 'manifest.json') with open(man, 'w', encoding='utf-8', newline='\n') as fh: json.dump({'theme': theme, 'format': fmts[0], 'formats': fmts, 'sounds': rows}, fh, indent=1) fh.write('\n') head = f'{len(rows)} sounds in {out} ({", ".join(fmts)}), manifest.json' res = {'files': [os.path.join(out, f) for r in rows for f in r['files']], 'manifest': man, 'sounds': rows, 'also': alts, 'not_in_sound': missed} - sprite = sprite or spec.get('sprite') - if sprite: + if outs: from .pack import pack - stem, ext = os.path.splitext(os.path.join(out, os.path.basename(sprite))) - ext = ext.lower().lstrip('.') - outs = [f'{stem}.{f}' for f in fmts] if not ext or ext in fmts else [f'{stem}.{ext}'] sp = pack([os.path.join(out, r['file']) for r in rows], outs, mono=mono, loops=[r['name'] for r in rows if r['loop']], ys=ys) lines.append(sp['summary']) diff --git a/earshot/pack.py b/earshot/pack.py index 5b2414b..2f41563 100644 --- a/earshot/pack.py +++ b/earshot/pack.py @@ -56,6 +56,8 @@ def pack(files, out, gap=GAP_S, mono=False, names=None, loops=(), ys=None): if not files: raise ValueError('nothing to pack: no audio files') names = list(names) if names else [os.path.splitext(os.path.basename(f))[0] for f in files] + if len(names) != len(files): + raise ValueError('a sprite needs one name per audio file') if len(set(names)) != len(names): raise ValueError('two sounds of a sprite share a name') parts, sprite, t = [], {}, 0.0 diff --git a/earshot/recipe.py b/earshot/recipe.py index 14a182a..22878eb 100644 --- a/earshot/recipe.py +++ b/earshot/recipe.py @@ -49,8 +49,8 @@ events {"count", "gap", "faster", "softer", "loose"}: the layer several times, each a new take: `gap` s from one to the next, each gap `faster` times the one before (under 1: faster and faster), each event `softer` dB against the one before, each up to `loose` (0 .. 1) of half its gap - early or late (drops, crackles, clicks that come as they come) - scatter {"rate", "rate_to", "dur", "pitch", "gain", "pan", "grain"}: the layer many times at random + early or late (drops, crackles, clicks that come as they come); the last starts within 120 s + scatter {"rate", "rate_to", "dur", "pitch", "gain", "pan", "grain"}: the layer many times at random moments (a Poisson process): `rate` events a second (0.5 .. 400) moving to `rate_to` by the end, over `dur` s; each event up to `pitch` semitones (0 .. 12) higher or lower, up to `gain` dB (0 .. 40) softer and up to `pan` (0 .. 1) to either side; with `grain` (0.005 .. 2 s) each is a @@ -144,6 +144,7 @@ 'hz': (20.0, 150.0, 'a frequency in Hz'), 'to': (20.0, 150.0, 'a frequency in Hz'), **{a: (-1.0, 1.0, 'an amount') for a in AXES}} CUTOFF = (20.0, 20000.0) +LATEST = 120.0 # s: the last event of a layer starts by then, as `at` does (a layer is mixed whole first) EVENT_RANGE = {'count': (2, 64, 'a whole number'), 'gap': (0.02, 30.0, 'a time in seconds'), 'faster': (0.5, 2.0, 'a factor'), 'softer': (-12.0, 12.0, 'a level in dB'), 'loose': (0.0, 1.0, 'an amount')} @@ -381,6 +382,17 @@ def check(recipe): if 'follow' in lay and lay['follow']['layer'] >= len(layers): raise RecipeError(f'layers[{i}].follow.layer is {lay["follow"]["layer"]}, but the recipe has ' f'{len(layers)} layers (0 to {len(layers) - 1})') + if 'events' in lay: # each gap `faster` times the one before: the last start can run far past any sound + ev, last = lay['events'], lay.get('at', 0.0) + gap = ev['gap'] + for _ in range(int(ev['count']) - 1): + last += gap + gap *= ev.get('faster', 1.0) + if last > LATEST: + break + if last > LATEST: + raise RecipeError(f'layers[{i}].events: its last event would start after {LATEST:.0f} s; events ' + f'start within {LATEST:.0f} s (fewer events, a shorter gap or a smaller "faster")') if 'says' in recipe and not (isinstance(recipe['says'], str) and recipe['says'].strip()): raise RecipeError(f'says is what the sound is, in words ("a dragon roaring"), not {recipe["says"]!r}') if 'built' in recipe and not isinstance(recipe['built'], str): diff --git a/earshot/sounds/learned.py b/earshot/sounds/learned.py index 99aa3d8..3a919fb 100644 --- a/earshot/sounds/learned.py +++ b/earshot/sounds/learned.py @@ -358,8 +358,8 @@ def perform(sid, seed=0, events=None, peak_db=-1.0, lufs=None, check=True, **req pat = e.get('pattern') or {} # a walk is heard from standing height: the pattern's `far` tilts every step (dB per octave around 1 kHz); a # request that asks for a close or dry sound (space under 0) hears the recording's own closeness - near = (request.get('space') or 0.0) < 0 - far = {'bright': float(pat['far'])} if pat.get('name') == 'walk' and pat.get('far') and not near else None + far = ({'bright': float(pat['far'])} + if pat.get('name') == 'walk' and pat.get('far') and c.space >= 0 else None) whole = wholes(e) walk = order(sid) play, p, cut, long = None, {}, None, False diff --git a/earshot/sounds/theme.py b/earshot/sounds/theme.py index 31cc564..bdb08e6 100644 --- a/earshot/sounds/theme.py +++ b/earshot/sounds/theme.py @@ -48,7 +48,7 @@ def get(theme=None): if isinstance(theme, str): if theme not in THEMES: raise ValueError(f'unknown theme {theme!r}: one of {", ".join(THEMES)}') - return dict(THEMES[theme], name=theme) + return dict(THEMES[theme], name=theme, axes=dict(THEMES[theme]['axes'])) t = dict(theme) base = t.pop('base', None) if base is not None and base not in THEMES: diff --git a/earshot/synth/master.py b/earshot/synth/master.py index c85b275..7549c2b 100644 --- a/earshot/synth/master.py +++ b/earshot/synth/master.py @@ -208,7 +208,7 @@ def write(path, y, sr=SR, mono=False, bits=24, bitrate=None): cmd = [ff, '-v', 'error', '-y', '-i', tmp, '-c:a', CODEC[ext], '-b:a', bitrate or BITRATE[ext]] if ext == 'webm' and sr not in (8000, 12000, 16000, 24000, 48000): cmd += ['-ar', '48000'] # Opus has no 44.1 kHz - p = subprocess.run(cmd + [path], capture_output=True, text=True) + p = subprocess.run(cmd + [os.path.join(os.curdir, path)], capture_output=True, text=True) if p.returncode != 0: raise RuntimeError(f'ffmpeg could not write {path}: {p.stderr.strip()[:300]}') finally: diff --git a/earshot/timeline.py b/earshot/timeline.py index 7f9bc6d..1508234 100644 --- a/earshot/timeline.py +++ b/earshot/timeline.py @@ -777,15 +777,13 @@ def _cached(model, fid, spans, kind, compute, reuse=True): res = compute([spans[i] for i in todo]) for i, v in zip(todo, res): out[i] = v - tmp = f'{files[i]}.{os.getpid()}.tmp.npy' - np.save(tmp, v) - audio.replace_quietly(tmp, files[i]) + audio.write_cache(files[i], lambda tmp: np.save(tmp, v)) return np.stack(out) if out else None def span_id(path): - """file id for the per-span model cache; mono sources decode at unity gain since core decode v2""" - return audio.file_id(path) + ('|mono2' if audio.probe(path).get('channels') == 1 else '') + """per-span models consume the stereo decode averaged to mono, so follow its decode version""" + return audio.file_id(path) + f'|decode{audio.DECODE_VERSION}' def _seg(x, a, b): @@ -1208,7 +1206,9 @@ def timeline(path, video=None, cues=None, start=None, end=None, detail='normal', if not pr.get('codec') and not video: raise ValueError(f'{os.path.basename(path)} has no audio stream') cue_list, cue_fps = read_cues(cues) - key = hashlib.sha1(f'{audio.file_id(path)}|{audio.file_id(video) if video else None}|{_cue_key(cues)}|{start}|' + # Key the same cue snapshot that is analysed, not the raw spelling or a second read of its file. + cue_key = _cue_key({'events': cue_list, 'fps': cue_fps}) + key = hashlib.sha1(f'{audio.file_id(path)}|{audio.file_id(video) if video else None}|{cue_key}|{start}|' f'{end}|{detail}|{CODE_ID}|{CORE_ID}'.encode()).hexdigest()[:24] cfile = os.path.join(config.EMB_CACHE, 'timeline', f'{key}.json') if cache and not fresh and os.path.exists(cfile): @@ -1222,11 +1222,10 @@ def timeline(path, video=None, cues=None, start=None, end=None, detail='normal', r['summary'] = _summary(r) r['text'] = transcript(r) if cache or fresh: - os.makedirs(os.path.dirname(cfile), exist_ok=True) - tmp = f'{cfile}.{os.getpid()}.tmp' - with open(tmp, 'w', encoding='utf-8') as fh: - fh.write(to_json(r)) - audio.replace_quietly(tmp, cfile) + def save(tmp): + with open(tmp, 'w', encoding='utf-8') as fh: + fh.write(to_json(r)) + audio.write_cache(cfile, save) return dict(r, cached=False) @@ -1241,20 +1240,21 @@ def _load_range(path, pr, start, end, reuse=True): raise ValueError(f"nothing to analyse between {t0:g} s and {'the end' if end is None else f'{end:g} s'}: " f'{name} is {fdur:.2f} s long') return np.zeros((int(round(fdur * SR)), 2), np.float32), 0.0, t0, t1, fdur + # The container can outlast its selected audio stream. load already decodes the + # whole track before slicing, so use those samples to bound every audio window. + x = audio.load(path, cache=reuse) + fdur = len(x) / SR if start is None and end is None: - x = audio.load(path, cache=reuse) - fdur = len(x) / SR if fdur < 0.1: raise ValueError(f'{name} is {fdur:.2f} s long: too short for a timeline (>= 0.1 s); for a one-shot use ' 'earshot measure / describe') return x, 0.0, 0.0, fdur, fdur - fdur = float(pr.get('duration') or 0) or len(audio.load(path, mono=True, cache=reuse)) / SR t0, t1 = max(0.0, float(start or 0)), min(fdur, float(end)) if end is not None else fdur if t1 - t0 < 0.1: raise ValueError(f"nothing to analyse between {t0:g} s and {'the end' if end is None else f'{end:g} s'}: " f'{name} is {fdur:.2f} s long') c0, c1 = max(0.0, t0 - CONTEXT_S), min(fdur, t1 + CONTEXT_S) - return audio.load(path, start=c0, end=c1, cache=reuse), c0, t0, t1, fdur + return x[int(round(c0 * SR)):int(round(c1 * SR))], c0, t0, t1, fdur def _analyse(path, pr, video, cue_list, cue_fps, start, end, cfg, reuse): diff --git a/earshot/video.py b/earshot/video.py index 2f4e9c0..f17d1cc 100644 --- a/earshot/video.py +++ b/earshot/video.py @@ -11,11 +11,12 @@ missed or found late; treat the result as "big visual change" markers, not an edit decision list. """ import hashlib +from fractions import Fraction import json import os import re import subprocess -import tempfile +import threading import numpy as np @@ -36,33 +37,155 @@ def info(path): def _cache(name): - config.ensure_dirs() - d = os.path.join(config.EMB_CACHE, 'video') - os.makedirs(d, exist_ok=True) - return os.path.join(d, name) + return os.path.join(config.EMB_CACHE, 'video', name) def frame_diff(path, cache=True): - """(fps, d): mean absolute difference (0..1) between consecutive 96x54 grey frames (d[0] = 0), cached""" - f = _cache('diff_' + hashlib.sha1(f'{audio.file_id(path)}|{FRAME_W}x{FRAME_H}|v1'.encode()).hexdigest()[:20] + '.npz') + """(decoded fps, d): consecutive 96x54 grey-frame differences (d[0] = 0), cached. + + The rate belongs to FFmpeg's selected decode, not necessarily probe()'s first stream. + """ + f = _cache('diff_' + hashlib.sha1(f'{audio.file_id(path)}|{FRAME_W}x{FRAME_H}|v2'.encode()).hexdigest()[:20] + '.npz') if cache and os.path.exists(f): try: with np.load(f, allow_pickle=False) as z: return float(z['fps']), np.array(z['d']) except Exception: pass - fps = (audio.probe(path).get('video') or {}).get('fps') or 30.0 - p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', path, '-an', '-vf', - f'scale={FRAME_W}:{FRAME_H}:flags=area,format=gray', '-f', 'rawvideo', '-'], capture_output=True) - if p.returncode != 0 or not p.stdout: - raise audio.AudioError(f'cannot decode the picture of {path}: {p.stderr.decode(errors="replace")[:200]}') - d = _frame_differences(p.stdout) - tmp = f + f'.{os.getpid()}.tmp.npz' - np.savez(tmp, fps=fps, d=d) - audio.replace_quietly(tmp, f) + raw, log, returncode = _decode_picture(path) + if returncode != 0 or not raw: + reason = audio._ffmpeg_reason(log.tail.decode(errors='replace')) + raise audio.AudioError(f'cannot decode the picture of {path}: {reason}') + fps = log.rate(path) + d = _frame_differences(raw) + audio.write_cache(f, lambda tmp: np.savez(tmp, fps=fps, d=d)) return float(fps), d +class _PictureLog: + """Drain verbose FFmpeg output without retaining per-frame logs or long metadata.""" + LIMIT = 4096 + + def __init__(self): + self.tail = self.pending = b'' + self.dropping = self.invalid = False + self.fps = None + + @staticmethod + def _is_config(line): + return re.match(rb'^\[showinfo@earshot_rate @ [^\]]+\] config in ', line) is not None + + def _line(self, line): + if not self._is_config(line): + return + try: + fps = _decoded_rate(line, 'FFmpeg output') + if self.fps is not None and self.fps != fps: + self.invalid = True + self.fps = fps + except audio.AudioError: + self.invalid = True + + def feed(self, chunk): + self.tail = (self.tail + chunk)[-self.LIMIT:] + if self.dropping: + end = chunk.find(b'\n') + if end < 0: + return + chunk = chunk[end + 1:] + self.dropping = False + data = self.pending + chunk + lines = data.split(b'\n') + for line in lines[:-1]: + if len(line) <= self.LIMIT: + self._line(line) + elif self._is_config(line): + self.invalid = True + self.pending = lines[-1] + if len(self.pending) > self.LIMIT: + if self._is_config(self.pending): + self.invalid = True + self.pending = b'' + self.dropping = True + + def finish(self): + if self.pending: + self._line(self.pending) + self.pending = b'' + + def rate(self, path): + if self.invalid or self.fps is None: + raise audio.AudioError(f'cannot determine decoded picture frame rate of {path}') + return float(self.fps) + + +def _decode_picture(path): + """The original raw-frame decode, with a bounded concurrent stderr consumer.""" + args = ['ffmpeg', '-hide_banner', '-v', 'info', '-nostats', '-nostdin', '-i', audio._ffmpeg_input(path), '-an', + '-vf', + f'scale={FRAME_W}:{FRAME_H}:flags=area,format=gray,showinfo@earshot_rate=checksum=0', + '-f', 'rawvideo', '-'] + log = _PictureLog() + with subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc: + def drain(): + try: + while True: + chunk = proc.stderr.read(8192) + if not chunk: + break + log.feed(chunk) + log.finish() + except Exception: + log.invalid = True + proc.stderr.close() + + reader = threading.Thread(target=drain) + try: + reader.start() + raw = proc.stdout.read() + returncode = proc.wait() + finally: + if proc.poll() is None: + proc.kill() + proc.wait() + proc.stdout.close() + if reader.ident is not None: + reader.join() + return raw, log, returncode + + +def _decoded_fps(stderr, path): + return float(_decoded_rate(stderr, path)) + + +def _decoded_rate(stderr, path): + """Read the rate of the actual selected decode, not ffprobe's first picture stream. + + showinfo observes the existing filter graph without changing its frames or + FFmpeg's automatic stream selection / output synchronization. + """ + entries = re.findall(rb'^\[showinfo@earshot_rate @ [^\]]+\] config in (.*)$', + stderr, re.MULTILINE) + try: + rates = set() + for entry in entries: + match = re.fullmatch(rb'time_base: (\d+)/(\d+), frame_rate: (\d+)/(\d+)', entry.strip()) + if match is None: + raise ValueError('malformed rate configuration') + tn, td, n, d = map(int, match.groups()) + if Fraction(tn, td) <= 0 or Fraction(n, d) <= 0: + raise ValueError('nonpositive timing') + rates.add(Fraction(n, d)) + if len(rates) != 1: + raise ValueError('missing or changing rate') + rate = rates.pop() + if not np.isfinite(float(rate)) or float(rate) <= 0: + raise ValueError('invalid rate') + except (ValueError, ZeroDivisionError, OverflowError) as exc: + raise audio.AudioError(f'cannot determine decoded picture frame rate of {path}') from exc + return rate + + def _frame_differences(raw): """Mean differences of complete raw grey frames, with bounded float32 intermediates.""" fr = np.frombuffer(raw, np.uint8) @@ -109,7 +232,7 @@ def cuts(path, method='diff', threshold=0.3, min_gap=0.2, cache=True): return json.load(saved) except (OSError, UnicodeDecodeError, json.JSONDecodeError): pass # a missing, unreadable or interrupted cache is not a failed scan - p = subprocess.run(['ffmpeg', '-hide_banner', '-nostdin', '-i', path, '-an', '-vf', + p = subprocess.run(['ffmpeg', '-hide_banner', '-nostdin', '-i', audio._ffmpeg_input(path), '-an', '-vf', f"scale=320:-2,select='gt(scene,{threshold})',showinfo", '-f', 'null', '-'], capture_output=True, text=True, errors='replace') if p.returncode != 0: @@ -119,21 +242,10 @@ def cuts(path, method='diff', threshold=0.3, min_gap=0.2, cache=True): for t in ts: if not out or t - out[-1] >= min_gap: out.append(round(t, 3)) - tmp = None - try: - with tempfile.NamedTemporaryFile(mode='w', dir=os.path.dirname(f), - prefix=os.path.basename(f) + '.', suffix='.tmp', delete=False) as saved: - tmp = saved.name + def save(tmp): + with open(tmp, 'w') as saved: json.dump(out, saved) - audio.replace_quietly(tmp, f) - except OSError: - pass # caching is optional; the scan itself succeeded - finally: - if tmp is not None: - try: - os.remove(tmp) - except OSError: - pass + audio.write_cache(f, save) return out @@ -141,7 +253,7 @@ def frame(path, t, width=320): """one frame at time t as a PIL image""" from PIL import Image import io - p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-ss', f'{max(0.0, t):.3f}', '-i', path, '-frames:v', '1', + p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-ss', f'{max(0.0, t):.3f}', '-i', audio._ffmpeg_input(path), '-frames:v', '1', '-vf', f'scale={width}:-2', '-f', 'image2pipe', '-vcodec', 'png', '-'], capture_output=True) if p.returncode != 0 or not p.stdout: return None diff --git a/pyproject.toml b/pyproject.toml index 07ab7fe..9e227c3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "earshot" -version = "1.0.0" +version = "1.1.0" description = "Make sound effects for interfaces, motion videos, games and films, everyday foley, drums and ambience from a request in words (computed at request time; the realistic ones from models learned from public-domain recordings, no audio shipped), build what the catalogue lacks from recorded parts named in words, and describe, match, measure and critique sound an agent cannot hear." readme = "README.md" requires-python = ">=3.10" diff --git a/tests/test_audio_multitrack.py b/tests/test_audio_multitrack.py new file mode 100644 index 0000000..fe8510a --- /dev/null +++ b/tests/test_audio_multitrack.py @@ -0,0 +1,67 @@ +"""Real synthetic media: preserve FFmpeg's selected track, stereo image and mono unity gain.""" +import hashlib +import subprocess + +import numpy as np +import pytest +import soundfile as sf + +import earshot.timeline as timeline # the module itself: `from earshot import timeline` asks for the listen extra +from earshot import audio + + +def _wav(tmp_path, channels, sr=48000): + t = np.arange(sr) / sr + x = np.column_stack([0.1 * np.sin(2 * np.pi * (220 + i * 110) * t) for i in range(channels)]) + p = tmp_path / f'{channels}_{sr}.wav' + sf.write(p, x, sr, subtype='FLOAT') + return str(p) + + +def _reference(path, channels, sr=48000): + p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', path, '-vn', '-f', 'f32le', + '-acodec', 'pcm_f32le', '-ac', str(channels), '-ar', str(sr), '-'], + capture_output=True, check=True) + x = np.frombuffer(p.stdout, np.float32) + return x if channels == 1 else x.reshape(-1, channels) + + +@pytest.mark.parametrize('first_channels,second_channels,default', [ + (1, 2, None), (1, 2, 0), (1, 2, 1), (2, 1, 1), (2, 1, None), (1, 2, 'both'), +]) +def test_multitrack_stereo_and_mono(tmp_path, first_channels, second_channels, default): + sources = [_wav(tmp_path, first_channels), _wav(tmp_path, second_channels)] + path = str(tmp_path / 'tracks.mkv') + subprocess.run(['ffmpeg', '-v', 'error', '-y', '-i', sources[0], '-i', sources[1], + '-map', '0:a', '-map', '1:a', '-c:a', 'pcm_f32le', + '-disposition:a:0', 'default' if default in (0, 'both') else '0', + '-disposition:a:1', 'default' if default in (1, 'both') else '0', path], check=True) + # With these populated streams, FFmpeg prioritizes default, then channel count. + selected = default if isinstance(default, int) else (0 if first_channels > second_channels else 1) + count = [first_channels, second_channels][selected] + expected = _reference(sources[selected], 1 if count == 1 else 2) + if count == 1: + expected = np.repeat(expected[:, None], 2, axis=1) + actual = audio.load(path, cache=False) + np.testing.assert_allclose(actual, expected, atol=1e-7) + # Model input convention must remain byte-for-byte the original FFmpeg mono downmix. + np.testing.assert_array_equal(audio.load(path, mono=True, cache=False), _reference(path, 1)) + + +@pytest.mark.parametrize('channels', [1, 2, 6]) +@pytest.mark.parametrize('sr', [44100, 48000]) +def test_single_track_and_resampling(tmp_path, channels, sr): + path = _wav(tmp_path, channels, sr) + expected = _reference(path, 1 if channels == 1 else 2) + if channels == 1: + expected = np.repeat(expected[:, None], 2, axis=1) + np.testing.assert_allclose(audio.load(path, cache=False), expected, atol=1e-7) + np.testing.assert_array_equal(audio.load(path, mono=True, cache=False), _reference(path, 1)) + + +def test_decode_and_span_keys_cannot_reuse_v2_samples(tmp_path): + path = _wav(tmp_path, 1) + old_decode = hashlib.sha1(f'{audio._state(path)}|48000|2|v2'.encode()).hexdigest()[:20] + assert audio._key(path, 48000, 2) != old_decode + assert timeline.span_id(path) != audio.file_id(path) + '|mono2' + assert timeline.span_id(path).endswith(f'|decode{audio.DECODE_VERSION}') diff --git a/tests/test_brief_index_lifetime.py b/tests/test_brief_index_lifetime.py new file mode 100644 index 0000000..b0fa1ae --- /dev/null +++ b/tests/test_brief_index_lifetime.py @@ -0,0 +1,43 @@ +from earshot import brief + + +def _rows(family): + return [dict(id=family + '/pop', uses=[family], says=['a ' + family + ' pop'], + tags=[], kind='pop', prior=1.0), + dict(id=family + '/wine', uses=[family], says=['a ' + family + ' with a hollow pop'], + tags=['real'], kind='pop', prior=1.0)] + + +def test_position_cache_retains_the_index_it_describes(): + previous = dict(brief._cache) + try: + brief._cache.clear() + idx = brief.index(_rows('cork')) + brief.rank(brief.read('a cork pop'), idx=idx) + assert brief._cache.get('pos_idx') is idx + other = brief.index(list(reversed(_rows('bottle')))) + brief.rank(brief.read('a bottle pop'), idx=other) + assert brief._cache.get('pos_idx') is other + assert brief._cache['pos'] == {r['id']: i for i, r in enumerate(other[0])} + finally: + brief._cache.clear() + brief._cache.update(previous) + + +def test_temporary_catalogues_match_cold_rankings(): + previous = dict(brief._cache) + try: + catalogues = [_rows('cork'), list(reversed(_rows('bottle')))] + queries = [brief.read('a cork pop'), brief.read('a bottle pop')] + for semantic in (None, {'cork/pop': 0.3, 'cork/wine': 0.6, 'bottle/pop': 0.3, 'bottle/wine': 0.6}): + cold = [] + for query, rows in zip(queries, catalogues): + brief._cache.clear() + cold.append(brief.rank(query, rows=rows, semantic=semantic)) + brief._cache.clear() + for i in range(100): + k = i % 2 + assert brief.rank(queries[k], rows=catalogues[k], semantic=semantic) == cold[k] + finally: + brief._cache.clear() + brief._cache.update(previous) diff --git a/tests/test_build.py b/tests/test_build.py index 9794fdf..34c3af2 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -277,6 +277,21 @@ def test_hear_without_ears_names_fields(tmp_path): assert any('`dur`' in x for x in h['off']) +def test_hear_reads_a_sound_file_at_its_own_rate(tmp_path): + # a file at 24 kHz is the same sound as at 48 kHz: the same length and brightness, not half as long and twice as high + import soundfile as sf + t = np.arange(int(1.0 * 24000)) / 24000 + y = 0.3 * np.sin(2 * np.pi * 1000 * t) * np.exp(-3 * t) + p24, p48 = str(tmp_path / 'tone24.wav'), str(tmp_path / 'tone48.wav') + sf.write(p24, np.stack([y, y], axis=1), 24000) + t = np.arange(int(1.0 * 48000)) / 48000 + y = 0.3 * np.sin(2 * np.pi * 1000 * t) * np.exp(-3 * t) + sf.write(p48, np.stack([y, y], axis=1), 48000) + a, b = B.hear(p24, 'a tone', listen=False), B.hear(p48, 'a tone', listen=False) + assert a['dur'] == pytest.approx(1.0, abs=0.01) and a['dur'] == pytest.approx(b['dur'], abs=0.01) + assert a['bright'] == pytest.approx(b['bright'], rel=0.05) + + def test_the_command_line_builds(tmp_path, capsys): from earshot import cli out = str(tmp_path / 'cli.wav') diff --git a/tests/test_core.py b/tests/test_core.py index d95fc58..7ca8c8c 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -160,6 +160,40 @@ def test_profile_summary_survives_unmeasured_metrics(): assert 'LRA n.a.' in profile.profile_summary(p) +@pytest.mark.parametrize('argv, want', [ + (['describe', 'x.wav'], 'describe'), + (['--threads', '2', 'describe', 'x.wav'], 'describe'), # the value of the global option is not a command + (['--threads=2', 'describe', 'x.wav'], 'describe'), + (['describe', 'x.wav', '--threads', '2'], 'describe'), + (['--threads', '2'], None), # no command: -h and a bad call read as none + (['-h'], None), +]) +def test_the_command_word_skips_a_global_option_value(argv, want): + assert cli._command(argv) == want + + +# Only a fresh process shows what the command word decided to import: the global --threads takes a value, and reading +# that value as the command registered every command module instead of the one asked for (`measure`: 26 modules and +# `doctor` 2.32 s to start, against 5 modules and 0.73 s in the `--threads=2` / `--threads 2` forms that read as the +# command; Windows, Python 3.13, warm cache) +_LAZY = '''import sys +from earshot import cli +cli.main(sys.argv[1:]) +print(len([m for m in sys.modules if m.startswith('earshot.')])) +''' + + +def test_global_threads_before_the_command_imports_one_command_module(wav, sine): + p = wav(sine) + counted = {} + for args in (['measure', p, '--light'], ['--threads', '2', 'measure', p, '--light']): + r = subprocess.run([sys.executable, '-c', _LAZY, *args], capture_output=True, text=True, cwd=REPO) + assert r.returncode == 0, r.stderr + counted[args[0] == '--threads'] = int(r.stdout.strip().splitlines()[-1]) + assert counted[True] == counted[False], counted + assert counted[True] < len(cli.COMMANDS), counted + + def test_sheet_ticks_at_quarter_seconds_are_exact(): assert sheet._tick_label(0.25, 0.25) == '0:00.25' and sheet._tick_label(0.75, 0.25) == '0:00.75' assert sheet._tick_label(0.5, 0.5) == '0:00.5' and sheet._tick_label(61.0, 1) == '1:01' @@ -234,4 +268,4 @@ def test_one_version_everywhere(): top = re.search(r'^## (\S+)', fh.read(), re.M).group(1) with open(os.path.join(root, '.claude-plugin', 'plugin.json'), encoding='utf-8') as fh: plugin = json.load(fh)['version'] - assert earshot.__version__ == pyproject == top == plugin == '1.0.0' + assert earshot.__version__ == pyproject == top == plugin == '1.1.0' diff --git a/tests/test_local_media_names.py b/tests/test_local_media_names.py new file mode 100644 index 0000000..9cc1198 --- /dev/null +++ b/tests/test_local_media_names.py @@ -0,0 +1,99 @@ +"""Local filename punctuation must not become an FFmpeg protocol or option.""" +import functools +import http.server +import os +from pathlib import Path +import subprocess +import threading + +import numpy as np +import pytest +import soundfile as sf + +from earshot import audio, config, video +from earshot.llm import encode +from earshot.synth import master + + +@pytest.fixture(params=['take:01', '-take', 'ordinary']) +def media(tmp_path, monkeypatch, request): + monkeypatch.chdir(tmp_path) + monkeypatch.setattr(config, 'DEC_CACHE', str(tmp_path / 'decoded')) + monkeypatch.setattr(config, 'EMB_CACHE', str(tmp_path / 'emb')) + wav = tmp_path / f'{request.param}.wav' + # ':' is not a legal native Windows filename. Ordinary names still test URI behavior there. + if os.name == 'nt' and ':' in request.param: + pytest.skip('colon is not a legal Windows filename') + x = (.2 * np.sin(2 * np.pi * 440 * np.arange(48000) / 48000)).astype(np.float32) + sf.write(wav, x, 48000, subtype='FLOAT') + film = wav.with_suffix('.mp4') + subprocess.run(['ffmpeg', '-y', '-v', 'error', '-f', 'lavfi', '-i', + 'color=c=black:s=160x90:r=25:d=1', '-c:v', 'mpeg4', str(film)], + check=True, capture_output=True) + return wav, film, x + + +@pytest.mark.parametrize('spelling', ['bare', 'dot', 'absolute', 'pathlib']) +def test_local_audio_name(media, spelling): + wav, _, x = media + name = {'bare': wav.name, 'dot': './' + wav.name, 'absolute': str(wav), 'pathlib': Path(wav.name)}[spelling] + assert audio.probe(name)['channels'] == 1 + decoded = audio.load(name, cache=False) + np.testing.assert_array_equal(decoded[:, 0], x) + np.testing.assert_array_equal(decoded[:, 1], x) + np.testing.assert_array_equal(audio.load(name), decoded) + np.testing.assert_array_equal(audio.load(name), decoded) + assert audio._key(name, 48000, 2) == audio._key(str(wav), 48000, 2) + encoded, mime, info = encode(name) + assert encoded and mime == 'audio/mp3' and info['seconds'] == 1 + + +@pytest.mark.parametrize('spelling', ['bare', 'dot', 'absolute', 'pathlib']) +def test_local_video_name(media, spelling): + _, film, _ = media + name = {'bare': film.name, 'dot': './' + film.name, 'absolute': str(film), 'pathlib': Path(film.name)}[spelling] + assert audio.probe(name)['has_video'] is True + assert video.cuts(name, cache=False) == [] + assert video.cuts(name, method='scene', cache=False) == [] + assert video.frame(name, .5) is not None + + +@pytest.mark.parametrize('name', ['export:01', '-export', 'ordinary']) +@pytest.mark.parametrize('ext', ['wav', 'flac', 'mp3', 'ogg', 'm4a', 'webm']) +def test_local_export_name(tmp_path, monkeypatch, name, ext): + if os.name == 'nt' and ':' in name: + pytest.skip('colon is not a legal Windows filename') + monkeypatch.chdir(tmp_path) + path = Path(f'{name}.{ext}') + output = master.write(path, np.zeros((4800, 2), np.float32)) + assert output == path and path.is_file() + assert audio.probe(str(path.resolve()))['codec'] + + +def test_existing_file_uri_and_http_inputs(media): + wav, film, _ = media + assert audio.probe('file:' + str(wav))['channels'] == 1 + assert video.frame('file:' + str(film), .5) is not None + handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(wav.parent)) + server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), handler) + thread = threading.Thread(target=server.serve_forever) + thread.start() + try: + from urllib.parse import quote + base = f'http://127.0.0.1:{server.server_port}/' + assert audio.probe(base + quote(wav.name))['channels'] == 1 + assert video.frame(base + quote(film.name), .5) is not None + finally: + server.shutdown() + server.server_close() + thread.join() + + +def test_timeline_preserves_public_path_spelling(media): + from earshot.timeline import timeline + _, film, _ = media + first = timeline(film.name) + second = timeline(film.name) + assert first['cached'] is False and second['cached'] is True + for result in (first, second): + assert result['file'] == result['video'] == film.name diff --git a/tests/test_local_media_symlinks.py b/tests/test_local_media_symlinks.py new file mode 100644 index 0000000..88abb88 --- /dev/null +++ b/tests/test_local_media_symlinks.py @@ -0,0 +1,53 @@ +"""FFmpeg filename disambiguation must preserve symlink/.. traversal.""" +import os +from pathlib import Path +import subprocess + +import numpy as np +import pytest +import soundfile as sf + +from earshot import audio, video +from earshot.synth import master + + +@pytest.fixture +def linked(tmp_path, monkeypatch): + if os.name == 'nt': + pytest.skip('Windows resolves "link/.." by the name before it follows the link: there is no such path') + target = tmp_path / 'target' + nested = target / 'nested' + nested.mkdir(parents=True) + try: + (tmp_path / 'link').symlink_to(nested, target_is_directory=True) + except (OSError, NotImplementedError) as e: + pytest.skip(f'directory symlinks unavailable: {e}') + monkeypatch.chdir(tmp_path) + return tmp_path, target + + +def test_audio_symlink_parent_components(linked): + root, target = linked + for folder, level in [(root, .1), (target, .3)]: + sf.write(folder / 'clip.wav', np.full(4800, level, np.float32), 48000, subtype='FLOAT') + expected = audio.load(str(target / 'clip.wav'), cache=False) + np.testing.assert_array_equal(audio.load('link/../clip.wav', cache=False), expected) + + +def test_video_symlink_parent_components(linked): + root, target = linked + for folder, color in [(root, 'white'), (target, 'black')]: + subprocess.run(['ffmpeg', '-y', '-v', 'error', '-f', 'lavfi', '-i', + f'color=c={color}:s=160x90:r=25:d=1', '-c:v', 'mpeg4', str(folder / 'clip.mp4')], + check=True, capture_output=True) + assert np.mean(video.frame('link/../clip.mp4', .5)) < 1 + + +def test_export_symlink_parent_components(linked): + root, target = linked + sentinel = root / 'out.mp3' + sentinel.write_bytes(b'keep the unrelated normalized-path file') + requested = Path('link/../out.mp3') + assert master.write(requested, np.zeros((4800, 2), np.float32)) == requested + assert sentinel.read_bytes() == b'keep the unrelated normalized-path file' + assert audio.probe(str(target / 'out.mp3'))['codec'] == 'mp3' diff --git a/tests/test_make.py b/tests/test_make.py index f081f39..682c43a 100644 --- a/tests/test_make.py +++ b/tests/test_make.py @@ -841,3 +841,23 @@ def test_a_length_within_a_tenth_of_a_second_says_nothing(tmp_path): assert _note(t, 8.0) is None t = {'dur_s': 5.0, 'note': '5.00 s, shorter than the 8 s asked: the longest this sound is made'} assert _note(t, 8.0) == '5.00 s, shorter than the 8 s asked' + + +def test_listening_hears_the_take_that_was_written_in_any_format(tmp_path, monkeypatch): + # an ogg is heard from the samples written into it: the walk of eight steps, not a new single step + if not shutil.which('ffmpeg'): + pytest.skip('ogg needs ffmpeg') + from earshot import extras, make as M + heard = [] + + def ear(path, queries): + y, sr = sf.read(path) + heard.append(len(y) / sr) + return {'query': queries[0], 'z': 0.0, 'verdict': 'no match'} + + monkeypatch.setattr(extras, 'need', lambda *a, **k: None) + monkeypatch.setattr(M, 'semantic', lambda want, listen=None: (None, None)) + monkeypatch.setattr(M, '_heard', ear) + r = make('footsteps on gravel', str(tmp_path / 'walk.ogg'), events=8, listen=True) + assert r['takes'][0]['performance']['events'] == 8 + assert heard and heard[0] == pytest.approx(r['takes'][0]['dur_s'], abs=0.01) diff --git a/tests/test_make_set_names.py b/tests/test_make_set_names.py new file mode 100644 index 0000000..934b585 --- /dev/null +++ b/tests/test_make_set_names.py @@ -0,0 +1,145 @@ +"""Expanded set names must not overwrite another take or duplicate manifest identities.""" +import json +import shutil +from pathlib import Path + +import numpy as np +import pytest +import soundfile as sf + +from earshot.make import make_set +from earshot.sounds import registry + + +@pytest.fixture +def tone_catalogue(monkeypatch): + # A controlled catalogue; the real renderer, mastering, audit and file writer still run. + monkeypatch.setattr(registry, '_designs', {}) + monkeypatch.setattr(registry, '_loaded', True) + + @registry.design('test/tone', kind='note', says=('a test tone', 'a short note'), dur=0.2, pitch='A4') + def tone(c, r): + t = np.arange(round(c.seconds() * 48000)) / 48000 + return np.sin(2 * np.pi * 440 * t) * np.sin(np.linspace(0, np.pi, len(t))) ** 2 + + +@pytest.mark.parametrize('reverse', [False, True]) +@pytest.mark.parametrize('fmt', ['wav', ['wav', 'flac']]) +@pytest.mark.parametrize('count', [{'n': 2}, {'want': 'two variations of a note'}]) +def test_expanded_take_names_are_rejected_before_writes(tmp_path, tone_catalogue, reverse, fmt, count): + items = [{'name': 'tap', 'sound': 'test/tone', 'dur': 0.2, **count}, + {'name': 'tap_1', 'sound': 'test/tone', 'dur': 0.4}] + if reverse: + items.reverse() + # Existing output must survive, including its manifest and the colliding filename. + sentinel = tmp_path / 'tap_1.wav' + sentinel.write_bytes(b'existing take') + manifest = tmp_path / 'manifest.json' + manifest.write_text('{"existing": true}', encoding='utf-8') + before = {p.name: p.read_bytes() for p in tmp_path.iterdir()} + with pytest.raises(ValueError, match='take name'): + make_set({'sounds': items, 'format': fmt}, out=str(tmp_path)) + assert {p.name: p.read_bytes() for p in tmp_path.iterdir()} == before + + +def test_duplicate_manifest_basenames_are_rejected(tmp_path, tone_catalogue): + items = [{'name': 'first/tap', 'sound': 'test/tone'}, + {'name': 'second/tap', 'sound': 'test/tone'}] + with pytest.raises(ValueError, match='take name'): + make_set({'sounds': items}, out=str(tmp_path)) + assert not list(tmp_path.iterdir()) + + +@pytest.mark.parametrize('fmt', ['wav', ['wav', 'flac']]) +def test_distinct_expanded_names_keep_files_and_metadata(tmp_path, tone_catalogue, fmt): + result = make_set({'sounds': [{'name': 'tap', 'sound': 'test/tone', 'n': 2, 'dur': 0.2}, + {'name': 'other', 'sound': 'test/tone', 'dur': 0.4}], + 'format': fmt}, out=str(tmp_path)) + assert [r['name'] for r in result['sounds']] == ['tap_1', 'tap_2', 'other'] + assert len(set(result['files'])) == len(result['files']) + assert json.loads((tmp_path / 'manifest.json').read_text())['sounds'] == result['sounds'] + for row in result['sounds']: + for path in row['files']: + data, sr = sf.read(tmp_path / path) + assert len(data) / sr == pytest.approx(row['dur_s'], abs=0.002) + assert np.isfinite(data).all() and np.max(np.abs(data)) > 0 + + +def test_explicit_take_count_overrides_words(tmp_path, tone_catalogue): + result = make_set({'sounds': [{'name': 'tap', 'sound': 'test/tone', 'want': 'two variations of a note', 'n': 1}, + {'name': 'tap_1', 'sound': 'test/tone'}]}, out=str(tmp_path)) + assert [r['name'] for r in result['sounds']] == ['tap', 'tap_1'] + assert len(set(result['files'])) == 2 + + +def test_loop_format_replacement_is_unchanged(tmp_path, tone_catalogue): + d = registry.get('test/tone') + registry.design('test/loop', kind='note', says=('a looping tone', 'a sustained note'), dur=0.2, + pitch='A4', loop=True)(d.fn) + result = make_set({'sounds': [{'name': 'loop', 'sound': 'test/loop', 'n': 2}], + 'format': ['mp3', 'flac']}, out=str(tmp_path)) + assert [r['files'] for r in result['sounds']] == [['loop_1.flac'], ['loop_2.flac']] + assert all(r['loop'] for r in result['sounds']) + assert sorted(p.name for p in tmp_path.iterdir()) == ['loop_1.flac', 'loop_2.flac', 'manifest.json'] + + +@pytest.mark.parametrize('sprite,fmt', [ + ('tap.wav', 'wav'), ('tap', 'wav'), ('tap.flac', ['wav', 'flac']), + ('nested/tap.wav', 'wav'), ('manifest.wav', 'wav'), ('manifest', ['wav', 'flac']), +]) +@pytest.mark.parametrize('argument', [False, True]) +def test_sprite_destinations_cannot_overwrite_set_files(tmp_path, tone_catalogue, sprite, fmt, argument): + items = [{'name': 'tap', 'sound': 'test/tone'}, {'name': 'other', 'sound': 'test/tone'}] + spec = {'sounds': items, 'format': fmt} + kwargs = {'sprite': sprite} if argument else {} + if not argument: + spec['sprite'] = sprite + (tmp_path / 'tap.wav').write_bytes(b'existing take') + (tmp_path / 'manifest.json').write_bytes(b'existing manifest') + before = {p.name: p.read_bytes() for p in tmp_path.iterdir()} + with pytest.raises(ValueError, match='sprite output'): + make_set(spec, out=str(tmp_path), **kwargs) + assert {p.name: p.read_bytes() for p in tmp_path.iterdir()} == before + + +def test_sprite_checks_the_loop_replacement_format(tmp_path, tone_catalogue): + registry.design('test/loop', kind='note', says=('a looping tone', 'a sustained note'), dur=0.2, + pitch='A4', loop=True)(registry.get('test/tone').fn) + with pytest.raises(ValueError, match='sprite output'): + make_set({'sounds': [{'name': 'tap', 'sound': 'test/loop'}], 'format': 'mp3', + 'sprite': 'tap.flac'}, out=str(tmp_path)) + assert not list(tmp_path.iterdir()) + + +@pytest.mark.parametrize('sprite,fmt', [('sprite', ['wav', 'flac']), ('tap.flac', 'wav')]) +def test_nonconflicting_sprite_keeps_takes_manifest_and_map(tmp_path, tone_catalogue, sprite, fmt): + result = make_set({'sounds': [{'name': 'tap', 'sound': 'test/tone', 'dur': 0.2}, + {'name': 'other', 'sound': 'test/tone', 'dur': 0.4}], + 'format': fmt, 'sprite': sprite}, out=str(tmp_path)) + assert json.loads((tmp_path / 'manifest.json').read_text())['sounds'] == result['sounds'] + for row in result['sounds']: + assert sf.info(tmp_path / row['file']).duration == pytest.approx(row['dur_s'], abs=0.002) + sprite_path = result['sprite'] + doc = json.loads(Path(sprite_path).with_suffix('.json').read_text()) + assert set(doc['sprite']) == {'tap', 'other'} + assert doc['src'] == [Path(p).name for p in result['sprites']] + for p in result['sprites']: + assert sf.info(p).duration > 0.8 + + +def test_sprite_override_takes_precedence_over_spec(tmp_path, tone_catalogue): + result = make_set({'sounds': [{'name': 'tap', 'sound': 'test/tone'}], 'sprite': 'manifest.wav'}, + out=str(tmp_path), sprite='safe.wav') + assert result['sprite'] == str(tmp_path / 'safe.wav') + assert 'sounds' in json.loads((tmp_path / 'manifest.json').read_text()) + + +@pytest.mark.skipif(shutil.which('ffmpeg') is None, reason='mp3 writing needs ffmpeg') +def test_loop_rendered_once_reserves_its_requested_format(tmp_path, tone_catalogue): + registry.design('test/loop', kind='note', says=('a looping tone', 'a sustained note'), dur=0.2, + pitch='A4', loop=True)(registry.get('test/tone').fn) + result = make_set({'sounds': [{'name': 'tap', 'sound': 'test/loop', 'want': 'one-shot'}], + 'format': 'mp3', 'sprite': 'tap.flac'}, out=str(tmp_path)) + assert result['sounds'][0]['loop'] is False + assert result['sounds'][0]['files'] == ['tap.mp3'] + assert (tmp_path / 'tap.mp3').is_file() and (tmp_path / 'tap.flac').is_file() diff --git a/tests/test_optional_media_cache.py b/tests/test_optional_media_cache.py new file mode 100644 index 0000000..5d4ac19 --- /dev/null +++ b/tests/test_optional_media_cache.py @@ -0,0 +1,133 @@ +"""Cache filesystem failures must not turn successful media work into failed calls.""" +from contextlib import contextmanager +from pathlib import Path +from types import SimpleNamespace +import os +import subprocess +import wave + +import numpy as np +import pytest + +import earshot.timeline as tl # the module itself: `from earshot import timeline` asks for the listen extra +from earshot import audio, config, video + + +@pytest.fixture +def media(tmp_path, monkeypatch): + home = tmp_path / 'cache' + for key, value in [('HOME', home), ('HF_CACHE', home/'hf'), ('EMB_CACHE', home/'emb'), + ('DEC_CACHE', home/'decoded')]: + monkeypatch.setattr(config, key, str(value)) + sound = tmp_path / 'silence.wav' + with wave.open(str(sound), 'wb') as f: + f.setnchannels(2) + f.setsampwidth(2) + f.setframerate(audio.SR) + f.writeframes(bytes(2 * audio.SR * 4)) + film = tmp_path / 'film.mp4' + subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'color=c=black:s=96x54:r=25:d=1', + '-f', 'lavfi', '-i', 'color=c=white:s=96x54:r=25:d=1', '-filter_complex', + '[0:v][1:v]concat=n=2:v=1:a=0[v]', '-map', '[v]', '-c:v', 'mpeg4', str(film)], + check=True, capture_output=True) + return home, str(sound), str(film) + + +@contextmanager +def readonly(home): + folders = [home] + [p for p in home.rglob('*') if p.is_dir()] + modes = [(p, p.stat().st_mode & 0o777) for p in folders] + try: + for p, _ in modes: + p.chmod(0o555) + if os.access(home, os.W_OK): + pytest.skip('host does not enforce directory write permissions for this user') + yield + finally: + for p, mode in modes: + p.chmod(mode) + + +def run(action, sound, film): + if action == 'audio': + assert audio.load(sound).shape == (2 * audio.SR, 2) + elif action in ('diff', 'scene'): + assert video.cuts(film, method=action) == [1.0] + else: + r = tl.timeline(sound if action == 'timeline_audio' else film) + assert r['duration'] == 2 and r['loudness']['digital_silence'] + assert all(v == 0 for v in r['model_calls'].values()) + + +@pytest.mark.parametrize('existing', [False, True]) +@pytest.mark.parametrize('action', ['audio', 'diff', 'scene', 'timeline_audio', 'timeline_video']) +def test_readonly_cache_does_not_fail_media(media, existing, action): + home, sound, film = media + home.mkdir() + if existing: + config.ensure_dirs() + (home/'emb'/'video').mkdir() + (home/'emb'/'timeline').mkdir() + with readonly(home): + run(action, sound, film) + assert not [p for p in home.rglob('*') if p.is_file()] + + +@pytest.mark.parametrize('action', ['audio', 'diff', 'scene', 'timeline_audio', 'timeline_video']) +def test_readonly_populated_cache_is_still_reused(media, monkeypatch, action): + home, sound, film = media + run(action, sound, film) + assert any(p.is_file() for p in home.rglob('*')) + def unexpected(*args, **kwargs): + raise AssertionError('cache hit must not recompute') + if action == 'audio': + monkeypatch.setattr(audio, '_decode', unexpected) + elif action in ('diff', 'scene'): + monkeypatch.setattr(subprocess, 'run', unexpected) + else: + monkeypatch.setattr(tl, '_analyse', unexpected) + with readonly(home): + run(action, sound, film) + + +def test_span_cache_write_is_optional(tmp_path): + model = SimpleNamespace(dir=str(tmp_path)) + with readonly(tmp_path): + result = tl._cached(model, 'test', [(0., 1.)], 'test', lambda spans: [np.array([1., 2.])]) + np.testing.assert_array_equal(result, [[1., 2.]]) + assert not list(tmp_path.iterdir()) + + +@pytest.mark.parametrize('error', [OSError('disk full'), ValueError('invalid value')]) +def test_partial_cache_write_preserves_old_cache_and_cleans_up(tmp_path, error): + path = tmp_path/'cached.npy' + path.write_bytes(b'previous cache') + def fail(tmp): + Path(tmp).write_bytes(b'partial') + raise error + if isinstance(error, OSError): + assert audio.write_cache(str(path), fail) is False + else: + with pytest.raises(ValueError, match='invalid value'): + audio.write_cache(str(path), fail) + assert path.read_bytes() == b'previous cache' + assert list(tmp_path.iterdir()) == [path] + + +def test_cache_writer_keeps_numpy_extension_and_replaces_atomically(tmp_path): + path = tmp_path/'new'/'cached.npz' + assert audio.write_cache(str(path), lambda tmp: np.savez(tmp, values=[1, 2])) is True + with np.load(path) as data: + np.testing.assert_array_equal(data['values'], [1, 2]) + assert list(path.parent.iterdir()) == [path] + + +def test_decode_failure_is_not_hidden_by_readonly_cache(media): + home, _, film = media + home.mkdir() + Path(film).write_bytes(b'not media') + with readonly(home): + with pytest.raises(audio.AudioError): + audio.load(film) + with pytest.raises(audio.AudioError): + video.cuts(film) diff --git a/tests/test_pack_names.py b/tests/test_pack_names.py new file mode 100644 index 0000000..c13f3d4 --- /dev/null +++ b/tests/test_pack_names.py @@ -0,0 +1,66 @@ +"""Names must not silently truncate an audio sprite's inputs.""" +import json + +import numpy as np +import pytest +import soundfile as sf + +from earshot.pack import pack +from earshot.synth import master + + +@pytest.fixture +def inputs(tmp_path): + paths = [] + for name, frequency in [('first', 440), ('second', 880)]: + path = tmp_path / f'{name}.wav' + t = np.arange(4800) / master.SR + sf.write(path, .2 * np.sin(2 * np.pi * frequency * t), master.SR) + paths.append(str(path)) + return paths + + +@pytest.mark.parametrize('names', [['only'], ['a', 'b', 'c']]) +@pytest.mark.parametrize('source', ['paths', 'folder', 'arrays']) +def test_mismatched_names_leave_existing_outputs_untouched(tmp_path, inputs, names, source): + out = tmp_path / 'sprite.wav' + mapping = tmp_path / 'sprite.json' + out.write_bytes(b'existing audio') + mapping.write_bytes(b'existing map') + files = str(tmp_path) if source == 'folder' else inputs + kwargs = {'ys': [np.zeros(4800), np.ones(4800) * .1]} if source == 'arrays' else {} + with pytest.raises(ValueError, match='one name per audio file'): + pack(files, str(out), names=names, **kwargs) + assert out.read_bytes() == b'existing audio' + assert mapping.read_bytes() == b'existing map' + + +@pytest.mark.parametrize('names', [['only'], ['a', 'b', 'c'], iter(())]) +def test_count_checked_before_loading_missing_inputs(tmp_path, names): + out = tmp_path / 'sprite.wav' + with pytest.raises(ValueError, match='one name per audio file'): + pack(['missing-a.wav', 'missing-b.wav'], str(out), names=names) + assert not out.exists() + assert not out.with_suffix('.json').exists() + + +@pytest.mark.parametrize('kind', ['list', 'tuple', 'generator', 'default', 'empty']) +def test_matching_and_default_names_keep_all_audio(tmp_path, inputs, kind): + names = {'list': ['first', 'second'], 'tuple': ('first', 'second'), + 'generator': iter(['first', 'second']), 'default': None, 'empty': []}[kind] + out = tmp_path / 'sprite.wav' + result = pack(inputs, str(out), names=names, gap=.05) + assert list(result['sprite']) == ['first', 'second'] + assert result['sprite'] == {'first': [0, 100], 'second': [150, 100]} + assert result['summary'].startswith('2 sounds in ') + assert sf.info(out).frames == 12000 + doc = json.loads(out.with_suffix('.json').read_text()) + assert doc['sprite'] == result['sprite'] + control = tmp_path / 'control.wav' + pack(inputs, str(control), gap=.05) + assert out.read_bytes() == control.read_bytes() + + +def test_duplicate_names_still_rejected(tmp_path, inputs): + with pytest.raises(ValueError, match='share a name'): + pack(inputs, str(tmp_path / 'sprite.wav'), names=['same', 'same']) diff --git a/tests/test_recipe.py b/tests/test_recipe.py index c5e365f..1e2c8e2 100644 --- a/tests/test_recipe.py +++ b/tests/test_recipe.py @@ -227,6 +227,16 @@ def test_events_repeat_a_layer_faster_and_softer(): assert 0.75 < meta['dur_s'] < 1.6 and meta['source'] == 'recipe' +def test_events_that_would_start_past_two_minutes_are_refused_before_any_buffer(): + # each gap twice the one before: the 32nd event would start about 2 billion seconds in (about 1.6 PB of samples) + with pytest.raises(R.RecipeError, match=r'layers\[0\]\.events: its last event would start after 120 s'): + R.check(rec({**TAP, 'events': {'count': 32, 'gap': 1, 'faster': 2}})) + with pytest.raises(R.RecipeError, match=r'layers\[0\]\.events'): + R.check(rec({**TAP, 'at': 100, 'events': {'count': 3, 'gap': 15}})) + assert R.check(rec({**TAP, 'at': 10, 'events': {'count': 64, 'gap': 1.5, 'faster': 1}})) # the last at 104.5 s + assert R.check(rec({**TAP, 'events': {'count': 64, 'gap': 30, 'faster': 0.5}})) # under a minute + + def test_follow_gives_a_layer_the_loudness_of_another_or_makes_it_give_way(): lead = np.zeros((dsp.n_of(1.0), 2)) lead[dsp.n_of(0.2):dsp.n_of(0.4)] = 0.5 diff --git a/tests/test_resampled_level.py b/tests/test_resampled_level.py new file mode 100644 index 0000000..76e549d --- /dev/null +++ b/tests/test_resampled_level.py @@ -0,0 +1,44 @@ +import numpy as np +import pytest +import soundfile as sf +import soxr +from earshot.forge import bank, sfx +from earshot.forge.polish import lufs_max + +@pytest.mark.parametrize('sr', bank.SRS) +@pytest.mark.parametrize('peak_db,weight', [(0, None), (-1, None), (-1, 0.5)]) +def test_final_sample_peak_and_metadata(sr, peak_db, weight): + y, meta = bank.render('click/tink', sr=sr, peak_db=peak_db, weight=weight, checks=False) + target = bank.level(peak_db, weight) + assert y.dtype == np.float32 and y.ndim == 2 and y.shape[1] == 2 + assert float(np.max(np.abs(y))) == pytest.approx(10 ** (target / 20), abs=1e-7) + assert np.max(np.abs(y)) <= 1 + assert meta['peak_db'] == round(target, 2) + assert all(meta[k] == v for k, v in bank.times(y, sr).items()) + analysis = y.astype(np.float64) if sr == bank.SR else soxr.resample(y.astype(np.float64), sr, bank.SR) + assert meta['lufs_m_max'] == round(float(lufs_max(analysis)), 2) + assert meta['checks'] is None + +@pytest.mark.parametrize('sr', [44100, 88200, 96000]) +def test_official_pcm24_writer_preserves_the_take_within_quantization(tmp_path, sr): + y, meta = bank.render('click/tink', sr=sr, peak_db=0) + result = sfx.sfx_render('click/tink', out=str(tmp_path / 'take.wav'), sr=sr, peak_db=0) + saved, read_sr = sf.read(result['file'], dtype='float32') + assert read_sr == sr and sf.info(result['file']).subtype == 'PCM_24' + np.testing.assert_allclose(saved, y, atol=2**-23, rtol=0) + assert meta == result['meta'] + assert meta['checks'] == sfx.check(y, sr=sr, category='click', sound='click/tink') + +@pytest.mark.parametrize('sound,options', [ + ('tap/finger', {'dur': 0.12}), + ('whoosh_fast/crisp', {'dur': 0.4, 'apex': 0.2}), + ('pluck/kalimba', {'pitch': 'E5', 'dur': 0.3}), +]) +def test_other_shapes_and_knobs_keep_output_level(sound, options): + native, _ = bank.render(sound, checks=False, **options) + y, meta = bank.render(sound, sr=44100, peak_db=-1, checks=False, **options) + assert y.ndim == native.ndim and y.shape[1:] == native.shape[1:] + assert abs(len(y) - round(len(native) * 44100 / 48000)) <= 1 + assert np.max(np.abs(y)) == pytest.approx(10 ** (-1 / 20), abs=1e-7) + assert all(meta[k] == v for k, v in bank.times(y, 44100).items()) + assert all(k in meta['edits'] for k in options) diff --git a/tests/test_theme_isolation.py b/tests/test_theme_isolation.py new file mode 100644 index 0000000..9fc5ff2 --- /dev/null +++ b/tests/test_theme_isolation.py @@ -0,0 +1,45 @@ +"""Theme edits must not change presets or other rendering requests.""" +from copy import deepcopy + +from earshot.sounds import theme + + +def test_named_theme_axes_do_not_alias_presets_or_other_requests(): + for name in theme.THEMES: + saved = deepcopy(theme.THEMES[name]) + try: + edited = theme.get(name) + other = theme.get(name) + edited['axes']['bright'] = 0.99 + assert other['axes'] == saved['axes'], name + assert theme.get(name)['axes'] == saved['axes'], name + assert theme.THEMES[name] == saved, name + assert edited['axes']['bright'] == 0.99 + finally: + # Keep the suite isolated even when run against the broken baseline. + theme.THEMES[name] = saved + + +def test_named_theme_axes_can_be_cleared_without_resetting_the_preset(): + for name in theme.THEMES: + saved = deepcopy(theme.THEMES[name]) + try: + edited = theme.get(name) + edited['axes'].clear() + assert theme.get(name)['axes'] == saved['axes'], name + assert theme.THEMES[name] == saved, name + finally: + theme.THEMES[name] = saved + + +def test_dict_theme_overrides_are_independent_and_preserve_values(): + override = {'base': 'wood', 'key': 'D', 'axes': {'hard': 0.2}} + saved = deepcopy(override) + result = theme.get(override) + assert result['axes'] == {'bright': -0.1, 'ring': -0.2, 'hard': 0.2} + assert result['key'] == 'D' + assert result['voice'] == 'marimba' + result['axes']['hard'] = -0.8 + assert override == saved + assert theme.get(None) is None + assert theme.get({'key': 'E'}) == {'key': 'E', 'axes': {}} diff --git a/tests/test_timeline_cue_cache.py b/tests/test_timeline_cue_cache.py new file mode 100644 index 0000000..176e41b --- /dev/null +++ b/tests/test_timeline_cue_cache.py @@ -0,0 +1,70 @@ +"""Timeline cache identity follows parsed cues, not a second file observation.""" +import json +import numpy as np +import soundfile as sf +import pytest +import earshot.timeline as tl # the module itself: `from earshot import timeline` asks for the listen extra +from earshot import config + +@pytest.fixture +def setup(tmp_path, monkeypatch): + monkeypatch.setattr(config, 'EMB_CACHE', str(tmp_path / 'emb')) + p = tmp_path / 'silent.wav' + sf.write(p, np.zeros(96000), 48000) + cues = tmp_path / 'cues.json' + cues.write_text('[0.5]') + return (str(p), cues) + +def times(r): + return [v['t'] for v in r['sync']['cues']['items']] + +def test_whitespace_path_edit(setup): + p, cues = setup + arg = ' ' + str(cues) + ' ' + assert times(tl.timeline(p, cues=arg)) == [0.5] + cues.write_text('[1.5]') + r = tl.timeline(p, cues=arg) + assert not r['cached'] and times(r) == [1.5] + assert tl.timeline(p, cues=arg)['cached'] + +def test_snapshot_read_before_change(setup, monkeypatch): + p, cues = setup + original = tl.read_cues + + def changing(arg): + result = original(arg) + cues.write_text('[1.5]') + return result + with monkeypatch.context() as m: + m.setattr(tl, 'read_cues', changing) + assert times(tl.timeline(p, cues=str(cues))) == [0.5] + r = tl.timeline(p, cues=str(cues)) + assert not r['cached'] and times(r) == [1.5] + +def test_equivalent_inputs(setup): + p, cues = setup + first = tl.timeline(p, cues=str(cues)) + for value in ([0.5], '[0.5]', '0.5', {'events': [{'time': 0.5}]}): + r = tl.timeline(p, cues=value) + assert r['cached'] and times(r) == times(first) + +def test_fps_is_part_of_effective_input(setup): + p, _ = setup + first = tl.timeline(p, cues={'fps': 30, 'events': [{'f': 30}]}) + r = tl.timeline(p, cues={'fps': 60, 'events': [{'f': 30}]}) + assert not r['cached'] and times(first) == [1] and (times(r) == [0.5]) + +def test_invalid_file_never_hidden_by_cache(setup): + p, cues = setup + tl.timeline(p, cues=str(cues)) + cues.write_text('broken') + with pytest.raises(json.JSONDecodeError): + tl.timeline(p, cues=str(cues)) + +def test_same_time_different_fps_preserves_tolerance(setup): + p, _ = setup + first = tl.timeline(p, cues={'fps': 30, 'events': [{'t': 1}]}) + second = tl.timeline(p, cues={'fps': 60, 'events': [{'t': 1}]}) + assert times(first) == times(second) == [1] + assert not second['cached'] + assert first['sync']['cues']['stats']['frame_ms'] != second['sync']['cues']['stats']['frame_ms'] diff --git a/tests/test_timeline_decoded_range.py b/tests/test_timeline_decoded_range.py new file mode 100644 index 0000000..b7fdaef --- /dev/null +++ b/tests/test_timeline_decoded_range.py @@ -0,0 +1,105 @@ +"""Audio ranges follow decoded duration, not a longer container's duration.""" +import subprocess +import tempfile +import unittest +import wave +from pathlib import Path + +import numpy as np +from earshot import audio, config +from earshot.timeline import timeline, _load_range + + +class DecodedRangeTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.old = (config.HOME, config.HF_CACHE, config.EMB_CACHE, config.DEC_CACHE) + config.HOME, config.HF_CACHE, config.EMB_CACHE, config.DEC_CACHE = ( + str(self.root / s) for s in ('cache', 'cache/hf', 'cache/emb', 'cache/decoded')) + self.wav = str(self.root / 'audio.wav') + with wave.open(self.wav, 'wb') as f: + f.setparams((2, 2, 48000, 0, 'NONE', 'not compressed')) + f.writeframes(bytes(48000 * 4)) + self.media = str(self.root / 'long-picture.mkv') + subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-f', 'lavfi', '-i', + 'color=c=black:s=32x32:r=10:d=3', '-i', self.wav, + '-c:v', 'ffv1', '-c:a', 'copy', self.media], check=True, capture_output=True) + self.assertEqual(audio.probe(self.media)['duration'], 3) + + def tearDown(self): + config.HOME, config.HF_CACHE, config.EMB_CACHE, config.DEC_CACHE = self.old + self.tmp.cleanup() + + def test_past_audio_end_rejected_not_cached(self): + for bounds in ({'start': 2, 'end': 3}, {'start': 1}, {'start': 1, 'end': 2}): + with self.subTest(bounds=bounds): + for _ in range(2): + with self.assertRaisesRegex(ValueError, 'nothing to analyse'): + timeline(self.media, detail='low', **bounds) + self.assertFalse(list(Path(config.EMB_CACHE).rglob('*.json'))) + + def test_actual_short_window_rejected(self): + for bounds in ({'start': .95, 'end': 2}, {'start': .95}, {'start': .95, 'end': 1}): + with self.subTest(bounds=bounds): + with self.assertRaisesRegex(ValueError, 'nothing to analyse'): + timeline(self.media, cache=False, detail='low', **bounds) + + def test_valid_window_matches_full_duration_and_cache(self): + full = timeline(self.media, cache=False, detail='low') + for bounds, expected in (({'start': 0, 'end': 3}, (0, 1)), + ({'start': .5, 'end': 3}, (.5, 1)), + ({'start': -.5, 'end': .5}, (0, .5)), + ({'start': .5}, (.5, 1))): + with self.subTest(bounds=bounds): + first = timeline(self.media, detail='low', **bounds) + second = timeline(self.media, detail='low', **bounds) + self.assertEqual((first['start'], first['end']), expected) + self.assertEqual(first['file_duration'], full['file_duration']) + self.assertEqual(first['file_duration'], 1) + self.assertEqual(first['duration'], expected[1] - expected[0]) + self.assertFalse(first['cached']) + self.assertTrue(second['cached']) + self.assertEqual(second['context'], first['context']) + self.assertTrue(all(v == 0 for v in first['model_calls'].values())) + + def test_unknown_or_underreported_probe_duration_uses_samples(self): + for duration in (0, .5, 3): + with self.subTest(duration=duration): + pr = dict(audio.probe(self.wav), duration=duration) + x, c0, t0, t1, fdur = _load_range(self.wav, pr, .5, 2, reuse=False) + self.assertEqual((len(x), c0, t0, t1, fdur), (48000, 0, .5, 1, 1)) + + def test_context_slice_matches_public_audio_load(self): + # Nonzero stereo data proves sample equality, not only zero-array shape. + long_path = str(self.root / 'long.wav') + n = 65 * audio.SR + samples = np.zeros((n, 2), dtype='