Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
6104e8f
fix: preserve selected audio track levels and stereo image
liugedragon Nov 13, 2026
a07211a
fix: preserve requested sample peak after bank resampling
liugedragon Nov 13, 2026
ec876bc
fix: isolate named theme axes from preset state
liugedragon Nov 16, 2026
2eb7dc0
fix: retain the search index backing cached positions
liugedragon Nov 16, 2026
8d54879
fix: reject duplicate expanded set take names before rendering
liugedragon Nov 16, 2026
69f3ae5
fix: reserve sprite destinations before rendering sets
liugedragon Nov 16, 2026
811fbf5
fix: reject sprite names count mismatches before audio I/O
liugedragon Nov 16, 2026
1685b07
fix: keep media analysis usable when optional caches cannot be written
liugedragon Nov 16, 2026
e2df66d
refactor: isolate optional cache helper from selected-track changes
liugedragon Nov 16, 2026
800ccc7
fix: key timeline caches by the parsed cue snapshot
liugedragon Nov 16, 2026
63e2939
fix: bound timeline audio ranges by decoded samples
liugedragon Nov 16, 2026
d2efddb
fix: time picture differences at the selected decoder frame rate
liugedragon Nov 17, 2026
2900a6b
test: patch the shared tempfile writer after cache refactor
liugedragon Nov 17, 2026
8598a79
fix: reap picture decoder when stderr thread cannot start
liugedragon Nov 17, 2026
1cc6224
cli: read the command word past the value of --threads
fcy222fcy Nov 17, 2026
c8d8df9
fix: disambiguate local media paths for FFmpeg
liugedragon Nov 17, 2026
aaf789d
fix: use composed space for walking distance tilt
liugedragon Nov 18, 2026
9c4bfa7
merge #28: the selected audio track keeps its level and stereo image
Leonxlnx Nov 21, 2026
18f28bc
merge #33: a bank sound keeps its asked peak after resampling
Leonxlnx Nov 21, 2026
3b28ece
merge #34: a named theme's axes no longer share state with its preset
Leonxlnx Nov 21, 2026
d998949
merge #36: the search index stays alive behind its cached positions
Leonxlnx Nov 21, 2026
43814d5
merge #41: pack refuses a name count that differs from the file count
Leonxlnx Nov 21, 2026
ae2413e
merge #42: a failed write to an optional media cache is no longer an …
Leonxlnx Nov 21, 2026
e915231
merge #43: timeline caches are keyed by the parsed cues
Leonxlnx Nov 21, 2026
cac0cc8
merge #44: timeline ranges are bounded by the decoded samples
Leonxlnx Nov 21, 2026
607659f
merge #48: a walk's distance tilt uses the composed space
Leonxlnx Nov 21, 2026
ee05a21
merge #45: picture cut timing uses the rate of the decoded track
Leonxlnx Nov 21, 2026
ffadeca
merge #47: local media paths are unambiguous for ffmpeg (take:01.wav,…
Leonxlnx Nov 21, 2026
432a55b
merge #39: a set refuses take names and sprite paths that would overw…
Leonxlnx Nov 21, 2026
d995b2a
merge #46: the command word is read past the value of --threads
Leonxlnx Nov 21, 2026
ecb07df
make --listen hears the take it wrote, also in ogg, mp3, m4a and webm…
Leonxlnx Nov 22, 2026
69e3c7a
a recipe whose events would start after 120 s is refused before any b…
Leonxlnx Nov 22, 2026
6b28d19
build hears a sound file at its own sample rate
Leonxlnx Nov 22, 2026
712bd0d
the symlink tests of #47 are skipped on Windows, which resolves link/…
Leonxlnx Nov 22, 2026
1c6de2b
1.1.0, unreleased: the changelog thanks the community fixes, and TEST…
Leonxlnx Nov 22, 2026
abe09b1
three new test files import the timeline module itself, so they colle…
Leonxlnx Nov 22, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
43 changes: 43 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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 <command>` 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
Expand Down
2 changes: 1 addition & 1 deletion docs/MAKE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
4 changes: 2 additions & 2 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion earshot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'}
Expand Down
60 changes: 42 additions & 18 deletions earshot/audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down Expand Up @@ -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):
Expand All @@ -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)
Expand All @@ -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


Expand All @@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

8 changes: 4 additions & 4 deletions earshot/brief.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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', ()):
Expand Down
5 changes: 4 additions & 1 deletion earshot/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -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=()))}
Expand Down
17 changes: 16 additions & 1 deletion earshot/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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='<command>')
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
Expand Down
16 changes: 11 additions & 5 deletions earshot/forge/bank.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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


Expand Down
2 changes: 1 addition & 1 deletion earshot/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading