From 67c689b7cd7ca196bab6de47686b57c7dcdbf056 Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Wed, 14 Oct 2026 21:51:51 +1100 Subject: [PATCH 1/6] Record tapes, and hear them while they play MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a Mac, Record… transfers a tape through any sound input and makes the master: a 24-bit, 48 kHz stereo WAV written into the session's recordings folder as /.wav, then transcribed without being asked. - Press Record with the deck stopped, wait for ARMED, press Play. The master begins a second before the tape's first sound; a click is not the tape. - The side ends by itself once the deck has been stopped for 30 seconds, three seconds after its last sound. The stop level is learned from the lead-in, or set by hand on a slider and moved while a side runs. A target-max slider and "loudest so far" are there for setting the gain. - Stop asks twice while sound is still coming; once the deck has stopped it reads "End side now". A name already used can be recorded again; the old master goes to the bin. - Monitor plays the input through to a chosen output, as recorded or with one track in both ears. It is a program apart from the recorder and takes no part in the master. The recorder is `app.py --record`, a program of its own. Sound comes from the sound system through sounddevice/PortAudio, every buffer queued. An earlier version read ffmpeg's Mac input, which keeps only the newest buffer: on the interface this was built with it lost one buffer in nine. The recorder now reports any sound lost, from PortAudio's overflow flag and from jumps in the buffers' own clock. The file on disk is a playable WAV at every moment, finished properly on quitting, and named next time after a crash. The page no longer rewrites unchanged text: redrawing a button several times a second can lose a press in the Mac's web view. smoke.py records from a file standing in for the input, on every system. Monitoring and the real devices are Mac only and were tried by hand. Co-Authored-By: Claude Opus 5.5 --- README.md | 38 ++- app.py | 611 +++++++++++++++++++++++++++++++++++++- app.py.lock | 36 +++ packaging/Info.plist.tmpl | 1 + smoke.py | 47 ++- static/index.html | 222 +++++++++++++- 6 files changed, 944 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index fc0230a..61f28a5 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ Transcribe a folder of audio recordings, read and search them, and pull clips ou Built for making selects from an archive of digitised cassette tapes: hours of speech, uneven quality, not much time. +- **Records tapes** (on a Mac): the master WAV straight from a sound input, started before the tape and ended by itself when the deck stops, then transcribed without being asked. - **Transcribes on your own computer.** Whisper large-v3, with a time for every word. Stretches in another language are marked and roughly translated into English; stretches with no speech are marked too. - **Music is marked** where there are no words: in the transcript ("♪ Music · 3 min 20 s") and as a green band on the waveform. It goes by the sound alone, so take it as a guide: a busy room with a hum in it can be taken for music, and music under speech is not marked. - **Transcript and waveform, linked.** Click a word to play from it. Drag across words to make a clip, drag the clip's edges on the waveform to trim it. @@ -62,6 +63,37 @@ uv fetches Python and everything else the first time, ffmpeg included. On a Mac Closing the window quits Transclip; while a transcription is running it asks first, because quitting stops it. Where it runs in the browser instead, starting it again just shows it, and **Recordings… → Quit Transclip** stops it. +## Recording a tape + +On a Mac, **Record…** (beside Recordings…) transfers a tape through any sound input and makes the master: a 24-bit, 48 kHz stereo WAV in the session's recordings folder, as `/.wav`. + +1. Choose the **input**, and for an interface with more than two inputs the **channels** the deck is on. The meter is live from then on. +2. Play the loudest part of the tape and set the gain on your interface or deck until "loudest so far" sits near the **target max** (the orange mark, −6 dBFS unless you move it). Transclip only measures; the master is exactly what arrives. +3. Type the **tape**'s name. The **side** starts as "Side A". +4. With the deck stopped, press **Record** and wait for **ARMED**. Then press Play on the deck: the panel turns to **● RECORDING**. + +What it keeps, and when it ends: + +- The master begins one second before the tape's first sound, so the wait before you press Play is not in it. A click is not taken for the tape: the sound has to last. +- The side **ends by itself** once the deck has been stopped for 30 seconds, and the master ends three seconds after the last sound. A blank stretch of tape, however long, does not end the side; a pause of the deck shorter than 30 seconds stays in the master. While it counts down the panel says **DECK STOPPED** and the button reads **End side now**. +- **Stop** ends a side at any time. While sound is still coming it asks to be pressed twice, so a stray press does not end a transfer. **Cancel**, while armed, records nothing. +- If the sound clipped, the panel says where. If the sound system ever lost sound, it says that too: such a master has gaps and should be done again. + +**The stop level** (the blue mark) is the level under which the deck counts as stopped. A deck standing still is far quieter than blank tape running, and the level has to lie between the two. + +- With the slider all the way left it is **learned**: from the moments between Record and the tape starting. That needs Record before Play; if the tape was already running, nothing could be learned, the side does not end by itself, and the panel says so. +- Anywhere else, it is what you set: read the meter with the deck stopped ("quietest" shows it), read it on blank tape, and put the mark between. It can be moved while a side is recording. + +**Monitor** plays the input through to an output you choose, so the tape can be heard: as recorded, or with one track in both ears for a tape recorded on one. It is a separate program from the recorder and has no part in the master, so it can be switched on and off while a side is recording. It is never on unless you tick it. + +**Recording a side again.** A name that is taken is refused; the panel then offers to record it again, and the old master goes to the Mac's bin. + +When a side ends it is transcribed straight away, or as soon as a transcription already running has finished, and the panel offers the next side of the same tape. The panel keeps the window until the side is over, and the session and its recordings folder cannot be changed meanwhile. + +The sound comes first. The recorder is a program of its own that nothing else in the app can hold up; every buffer the sound system delivers is queued, never skipped; the file on disk is a playable WAV at every moment; quitting asks first and finishes the file; and after a crash or a power cut, what had been recorded is given its name the next time the Record panel is opened. It will not start without room for two hours on the disk. + +Not yet: the transcript appearing while the tape is still playing, and recording on Windows or Linux. + ## Sessions A session is one project: its own recordings, its own recordings folder, its own clips and exports. Search looks through every recording of the open session and none of any other. @@ -110,7 +142,9 @@ echo '[]' > /tmp/none.json && uv run transcribe.py /tmp/none.json && echo "The s It fetches the same model to the same place, and the app finds it there. If that stalls too, put `HF_HUB_DISABLE_XET=1 ` in front of `uv` to fetch it by the plain route. -**macOS asks whether "python3.12" may read a folder.** That is Transclip (see [Install](#macos-app)). It can ask again for Downloads, Documents or Desktop when a file is imported or located there. +**macOS asks whether "python3.12" may read a folder, or use the microphone.** That is Transclip (see [Install](#macos-app)). It can ask again for Downloads, Documents or Desktop when a file is imported or located there. "The microphone" is how macOS speaks of every sound input: it is asked the first time the Record panel is opened, and recording cannot work without it. + +**A side did not end by itself.** Either the tape was already running when Record was pressed (the panel said so), or the deck does not go quiet enough when it stops. Press Stop; nothing is lost. For the next side, set the stop level by hand. **Anything else:** the app's own messages are in `Library/Logs/Transclip.log` in your home folder. @@ -149,4 +183,4 @@ After changing a script's dependencies: `uv lock --script app.py` (or `transcrib ## Built with -[Whisper](https://github.com/openai/whisper) via [MLX](https://github.com/ml-explore/mlx-examples/tree/main/whisper) and [faster-whisper](https://github.com/SYSTRAN/faster-whisper), [Silero VAD](https://github.com/snakers4/silero-vad), [fastembed](https://github.com/qdrant/fastembed), [wavesurfer.js](https://wavesurfer.xyz), [FFmpeg](https://ffmpeg.org) through [imageio-ffmpeg](https://github.com/imageio/imageio-ffmpeg), [Flask](https://flask.palletsprojects.com), [pywebview](https://pywebview.flowrl.com) for the Mac window, [Pillow](https://python-pillow.org) to draw the icon, and [uv](https://docs.astral.sh/uv/), a copy of which is inside the Mac app. +[Whisper](https://github.com/openai/whisper) via [MLX](https://github.com/ml-explore/mlx-examples/tree/main/whisper) and [faster-whisper](https://github.com/SYSTRAN/faster-whisper), [Silero VAD](https://github.com/snakers4/silero-vad), [fastembed](https://github.com/qdrant/fastembed), [wavesurfer.js](https://wavesurfer.xyz), [FFmpeg](https://ffmpeg.org) through [imageio-ffmpeg](https://github.com/imageio/imageio-ffmpeg), [Flask](https://flask.palletsprojects.com), [pywebview](https://pywebview.flowrl.com) for the Mac window, [sounddevice](https://python-sounddevice.readthedocs.io) and [PortAudio](https://www.portaudio.com) for recording, [Pillow](https://python-pillow.org) to draw the icon, and [uv](https://docs.astral.sh/uv/), a copy of which is inside the Mac app. diff --git a/app.py b/app.py index c26ba85..b6b6267 100644 --- a/app.py +++ b/app.py @@ -3,6 +3,7 @@ # dependencies = [ # "flask>=3", "fastembed>=0.9", "imageio-ffmpeg>=0.6", "numpy", # "pywebview>=6; sys_platform == 'darwin'", +# "sounddevice>=0.5; sys_platform == 'darwin'", # ] # /// """Transclip: uv run app.py @@ -15,7 +16,9 @@ moves it): tapes/ holds each recording's transcript, listening copy and waveform outline, selects.json the clips, exports/ what you export. A session is another such folder inside it, in sessions/: one project's recordings, clips and search, apart -from every other's. Recordings can be collected into one file for someone else and +from every other's. On a Mac a tape can be recorded straight into a session's recordings +folder: `app.py --record` is the program that listens to the sound input, started and +stopped by the app. Recordings can be collected into one file for someone else and imported from one; originals that arrive that way are kept in originals/. Exports are cut from the original recordings, which are only ever read. Corrections to a transcript are kept beside it in .fixes and laid over the machine's words when it is read; the @@ -24,11 +27,14 @@ """ import csv import json +import math import os import posixpath +import queue import re import shutil import socket +import struct import subprocess import sys import threading @@ -74,6 +80,20 @@ BLOCKS = RATE / HOP / PER_BLOCK # measurements a second FLAT, CHANGE = 0.1, 0.15 SMOOTH, BRIDGE, SHORTEST = 5, 3, 10 # seconds: judged over, a lapse a piece may contain, and the least that counts +# Recording a tape. The master is what came in, as 24-bit stereo at 48 kHz, judged a tenth of a second at a time. +REC_RATE, REC_BYTES = 48000, 6 # frames a second, and bytes to a frame: two channels of three +REC_BLOCK = REC_RATE // 10 * REC_BYTES # bytes in a tenth of a second +# A deck that has stopped is far quieter than blank tape still running: about 45 dB on the chain this was built +# against (-117 dBFS stopped, -72 running). The level under which the deck counts as stopped is either set by +# the person, or learned between Record and the tape starting: +STOPPED_ABOVE, STARTED_ABOVE = 10, 15 # dB over the learned level: still stopped, and certainly playing +# ponytail: one fixed level stands guard over the learning. A lead-in louder than this is taken for a tape already +# running, and the side is then never ended automatically. With the gain set very low, running tape could slip +# under it; setting the stop level by hand is the way round that. +QUIET_ENOUGH = -80 # dBFS +SIDE_ENDS, LEAD_IN, TAIL = 30, 1, 3 # seconds: stopped this long is the end; kept before the tape's first sound, and after its last +STEADY = 5 # tenths of a second that sound must last to be the tape starting, and not a click +TEST_INPUT = os.environ.get("TRANSCLIP_TEST_INPUT") # a sound file to stand in for the sound inputs: for tests app = Flask(__name__, static_folder="static", static_url_path="") @@ -225,6 +245,259 @@ def shown(tape_id): return {**d, "music": music(np.load(kept), [w for c in d["chunks"] for w in c["words"]])} +def measure(block): + """A stretch of 24-bit stereo sound: its level over both channels, each channel's peak (all in dBFS), + and whether it clipped.""" + import numpy as np + b = np.frombuffer(block, np.uint8).reshape(-1, 2, 3).astype(np.int32) + v = b[..., 0] | b[..., 1] << 8 | (b[..., 2] ^ 0x80) - 0x80 << 16 # three bytes to a number, the top one carrying the sign + peak = np.abs(v).max(0) + db = lambda x: round(20 * math.log10(max(float(x), 0.5) / 2 ** 23), 1) + return db(math.sqrt(float((v.astype(np.float64) ** 2).mean()))), db(peak[0]), db(peak[1]), bool(peak.max() >= 2 ** 23 - 1) + + +class Side: + """One side of a tape as it comes in, a tenth of a second at a time: what of it to keep, and when it is over. + The master starts LEAD_IN before the tape's first sound and ends TAIL after its last. A deck stopped for + less than SIDE_ENDS is kept whole; stopped for that long, the side has ended.""" + + def __init__(self, below=None): + self.state = "waiting" # for the tape to start; then "playing", then "over" + self.below = below # the level under which the deck counts as stopped, if the person has set one + self.floor = None # otherwise the level of the stopped deck, once learned; False if the lead-in was no stopped deck + self.before = [] # the lead-in as (level, sound, clipped): all of it until the floor is known, then the last LEAD_IN + self.held = [] # sound at the stopped level, kept back until it is known whether the side has ended + self.kept = 0 # tenths of a second in the master so far + self.clipped = [] # where in the master the sound clipped, in seconds, at most once a second + + def hear(self, block, measured=None): + """Take in the next tenth of a second. Returns what belongs in the master now, which may be nothing.""" + level, _, _, clipped = measured or measure(block) + if self.state == "over": + return b"" + if self.state == "waiting": + self.before.append((level, block, clipped)) + if self.below is None and self.floor is None: + if len(self.before) < LEAD_IN * 10: + return b"" + low = sorted(l for l, *_ in self.before)[len(self.before) // 5] # near the quietest, a stray click aside + self.floor = low if low <= QUIET_ENOUGH else False + if self.stops_below is None: # the tape was already running: keep it all, and leave the stopping to the person + return self.start(0) + playing = self.below if self.below is not None else self.floor + STARTED_ABOVE + quiet = [l <= playing for l, *_ in reversed(self.before)] + lasted = quiet.index(True) if True in quiet else len(quiet) # how long there has now been sound + if lasted < STEADY: + del self.before[:-(LEAD_IN * 10 + STEADY)] + return b"" + return self.start(max(len(self.before) - lasted - LEAD_IN * 10, 0)) + if self.stops_below is not None and level <= self.stops_below: + self.held.append(block) + return self.stop() if len(self.held) >= SIDE_ENDS * 10 else b"" + back, self.held = self.held, [] # sound again: the deck had only paused + return self.keep([(b, False) for b in back] + [(block, clipped)]) + + @property + def stops_below(self): + """The level under which the deck counts as stopped: set, or learned. None while that is not known, or never will be.""" + return self.below if self.below is not None else self.floor + STOPPED_ABOVE if self.floor else None + + def start(self, at): + self.state, lead, self.before = "playing", self.before[at:], [] + return self.keep([(b, c) for _, b, c in lead]) + + def keep(self, blocks): + for _, clipped in blocks: + if clipped and (not self.clipped or self.kept / 10 - self.clipped[-1] >= 1): + self.clipped.append(self.kept / 10) + self.kept += 1 + return b"".join(b for b, _ in blocks) + + def stop(self): + """End the side. Returns the last of what belongs in the master: at most TAIL of the stopped deck.""" + self.state, tail, self.held = "over", self.held[:TAIL * 10], [] + return self.keep([(b, False) for b in tail]) + + +class Master: + """A WAV file being written. Its header is brought up to date as it grows, so that whatever happens + the file on disk is one that plays as far as it had got.""" + + def __init__(self, path): + self.f, self.size = open(path, "xb"), 0 # never over a file that is already there + self.f.write(self.head()) + + def head(self): + return struct.pack("<4sI4s4sIHHIIHH4sI", b"RIFF", 36 + self.size, b"WAVE", b"fmt ", 16, 1, 2, REC_RATE, + REC_RATE * REC_BYTES, REC_BYTES, 24, b"data", self.size) + + def write(self, sound): + self.f.write(sound) + self.size += len(sound) + + def settle(self): + self.f.seek(0) + self.f.write(self.head()) + self.f.seek(0, 2) + self.f.flush() + os.fsync(self.f.fileno()) + + +def recorder(spec): + """`app.py --record `: the program that listens to a sound input. The app starts it, gives it orders one + to a line on its standard input ({"record": path}, {"stop": true}), and ends it by closing that. It answers one + JSON object to a line: the level ten times a second, and {"done": ...} when a side is finished. + It is a program of its own so that nothing the app is busy with can hold up the sound.""" + def say(**message): + try: + print(json.dumps(message), flush=True) + except OSError: + pass # the app has gone: the side is still finished properly + + orders = queue.Queue() + + def listen_for_orders(): + for line in sys.stdin: + orders.put(json.loads(line)) + orders.put(None) # the app closed the panel, or is no longer there + threading.Thread(target=listen_for_orders, daemon=True).start() + if spec.get("file"): + # Tests: a sound file stands in for an input. It would be over before Record was pressed, so it waits for that. + orders.put(orders.get()) + played = subprocess.Popen([FFMPEG, "-v", "error", "-i", spec["file"], "-af", f"pan=stereo|c0=c{int(spec['left'])}|c1=c{int(spec['right'])}", + "-ar", str(REC_RATE), "-f", "s24le", "-"], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE) + incoming = lambda: (played.stdout.read(REC_BLOCK), False) + else: + # The sound system hands over every buffer by calling arrived(), and they wait in a queue until taken: + # nothing is skipped because this program was busy. (ffmpeg's own Mac input keeps only the newest buffer, + # and on the interface this was built with it lost one in nine.) If the sound system itself ever has to + # throw sound away it says so, and so does a jump in the buffers' own clock: either way the side is told. + import sounddevice as sd + waiting, clock = queue.Queue(), {"next": None} + + def arrived(data, frames, when, status): + late = clock["next"] is not None and when.inputBufferAdcTime - clock["next"] > 0.02 + clock["next"] = when.inputBufferAdcTime + frames / REC_RATE + waiting.put((bytes(data), bool(status.input_overflow) or late)) + device = next(i for i, d in enumerate(sd.query_devices()) if d["name"] == spec["device"] and d["max_input_channels"]) + stream = sd.RawInputStream(device=device, samplerate=REC_RATE, channels=2, dtype="int24", blocksize=REC_RATE // 10, dither_off=True, + extra_settings=sd.CoreAudioSettings(channel_map=[int(spec["left"]), int(spec["right"])]), callback=arrived) + stream.start() + + def incoming(): + try: + return waiting.get(timeout=5) + except queue.Empty: # unplugged, or switched off + return b"", False + side = master = path = None + + def finish(why): + """Close the side being kept, give it its name, and say what became of it.""" + nonlocal side, master + done = {"why": why, "file": None, "seconds": side.kept / 10, "auto": side.stops_below is not None, "lost": lost} + try: + last = side.stop() if side.state != "over" else b"" + if master: + master.write(last) + done.update(seconds=side.kept / 10, clipped=side.clipped) + master.settle() + master.f.close() + final, n = Path(path), 1 + while final.exists(): # the app looked before starting; this is for a file that turned up since + n += 1 + final = Path(path).with_name(f"{Path(path).stem} ({n}).wav") + os.replace(path + ".part", final) + done["file"] = str(final) + except OSError as e: + done["why"] = f"{why}; and the file could not be finished: {e}. What was recorded is in {path}.part" + side = master = None + say(done=done) + + kept_at_last_settle = 0 + top, quietest = [-200.0, -200.0], 0.0 # the loudest each channel has been and the quietest the input has been, since asked to forget + lost = [] # where in the side being kept the sound system lost sound, in seconds + while True: + block, gap = incoming() # waits until a tenth of a second has come in + closing = False + while not orders.empty(): + order = orders.get() + if order is None: + closing = True + elif order.get("record") and not side: + path, side, kept_at_last_settle, lost = order["record"], Side(order.get("below")), 0, [] + elif order.get("stop") and side: + finish("stopped") + elif order.get("forget"): + top, quietest = [-200.0, -200.0], 0.0 + elif "below" in order and side and order["below"] is not None: # the stop level, moved while the side runs + side.below = order["below"] + if len(block) < REC_BLOCK: # the input has gone: unplugged, refused, or a test's file at its end + if side: + finish("the input stopped") + say(error="The sound input stopped. Is it still plugged in and switched on?") + break + if gap and side and side.state == "playing": + lost.append(side.kept / 10) + level, left, right, clipped = measure(block) + top, quietest = [max(top[0], left), max(top[1], right)], min(quietest, level) + if side: + try: + sound = side.hear(block, (level, left, right, clipped)) + if sound: + master = master or Master(path + ".part") + master.write(sound) + if side.kept - kept_at_last_settle >= 20: + master.settle() + kept_at_last_settle = side.kept + except OSError as e: # the disk is full, or has gone + finish(f"it could not be written: {e}") + if side and side.state == "over": + finish("the side ended") + learning = bool(side) and side.below is None and side.floor is None + say(l=left, r=right, clip=clipped, level=level, top=top, quietest=quietest, state=side.state if side else "listening", + seconds=side.kept / 10 if side else 0, stopped=len(side.held) / 10 if side else 0, + below=side.stops_below if side else None, auto=None if not side or learning else side.stops_below is not None, lost=len(lost)) + if closing: + if side: + finish("Transclip was closed") + break + + +def ears(hear): + """Which of the two channels coming in goes to the left ear and which to the right: both as they are, + or one of them in both ears, for a tape recorded on one track.""" + return {"left": [0, 0], "right": [1, 1]}.get(hear, [0, 1]) + + +def to_outputs(count, left, right): + """For a device with `count` outputs: what each one is sent. 0 is the left of what is heard, 1 the right, -1 nothing.""" + sent = [-1] * count + sent[left], sent[right] = 0, 1 + return sent + + +def monitor(spec): + """`app.py --monitor `: plays a sound input straight through to an output, so that a tape can be heard. + It runs until its standard input is closed. It is a program of its own and takes no part in recording: + whatever becomes of it, the master is not touched.""" + import sounddevice as sd + try: + all_of_them = sd.query_devices() + find = lambda name, kind: next(i for i, d in enumerate(all_of_them) if d["name"] == name and d[kind]) + coming, going = find(spec["input"], "max_input_channels"), find(spec["output"], "max_output_channels") + route = ears(spec.get("hear")) + + def through(indata, outdata, frames, when, status): + outdata[:] = indata[:, route] + wiring = (sd.CoreAudioSettings(channel_map=[int(spec["left"]), int(spec["right"])]), + sd.CoreAudioSettings(channel_map=to_outputs(all_of_them[going]["max_output_channels"], int(spec["out_left"]), int(spec["out_right"])))) + with sd.Stream(device=(coming, going), samplerate=REC_RATE, channels=2, dtype="float32", latency="low", extra_settings=wiring, callback=through): + print(json.dumps({"on": True}), flush=True) + sys.stdin.read() + except Exception as e: # no such device any more, or one that will not open: said, not thrown + print(json.dumps({"error": str(e) or type(e).__name__}), flush=True) + + def norm(word): return "".join(ch for ch in word.lower() if ch.isalnum()) @@ -567,8 +840,13 @@ def watch(): state.update({k: said[k] for k in ("i", "n", "file", "fraction", "note") if k in said}) if proc.wait() == 0 and state["running"]: state["note"] = "Finished." if not state["failed"] else f"Finished, but {len(state['failed'])} could not be read." + waiting = [r for f, r in _queue if f == folder] # sides recorded while this was going on + del _queue[:] + if waiting: + return start_job(folder, waiting) elif state["running"]: state["note"] = "The transcriber stopped: " + state["note"] + del _queue[:] # stopped or failed: they are not lost, only left "to do" like any other recording state["running"] = False threading.Thread(target=watch, daemon=True).start() @@ -582,6 +860,123 @@ def stop_job(): proc.terminate() # in case it had not got as far as listening +_rec = {"proc": None, "state": {"on": False}} # the program listening to a sound input, and the last it said +_queue = [] # sides recorded while the transcriber was busy, as (folder, recording) + + +def recording(): + return _rec["state"].get("state") in ("waiting", "playing") + + +def inputs(way="input"): + """The sound inputs this computer has (or with "output", its outputs): each one's name, how many channels it + offers, the rate it is running at, and whether it is the one the system uses unless told otherwise.""" + if TEST_INPUT: + return [{"name": "Test input", "channels": 2, "rate": REC_RATE, "usual": True}] if way == "input" else [] + if sys.platform != "darwin": + return [] # ponytail: recording is built on the Mac's sound system. PortAudio speaks to Windows' and Linux's too, when wanted. + told = json.loads(subprocess.run(["system_profiler", "SPAudioDataType", "-json"], capture_output=True, text=True).stdout or "{}") + return [{"name": d["_name"], "channels": int(d[f"coreaudio_device_{way}"]), "rate": int(d.get("coreaudio_device_srate") or 0), + "usual": f"coreaudio_default_audio_{way}_device" in d} + for d in told.get("SPAudioDataType", [{}])[0].get("_items", []) if d.get(f"coreaudio_device_{way}")] + + +_mon = {"proc": None, "state": {"on": False}} # the program playing the input through to an output, and what it last said + + +def unmonitor(): + proc, _mon["proc"] = _mon["proc"], None + if proc and proc.poll() is None: + proc.stdin.close() + try: + proc.wait(5) + except subprocess.TimeoutExpired: + proc.terminate() + + +def hush(): + """Stop listening, and stop playing the input through. A side being recorded is finished properly first.""" + unmonitor() + proc, _rec["proc"] = _rec["proc"], None + if proc and proc.poll() is None: + proc.stdin.close() + try: + proc.wait(15) + except subprocess.TimeoutExpired: + proc.terminate() + + +def listen(device, left, right): + """Start listening to an input, for the meter and ready to record from.""" + hush() + spec = {"file": TEST_INPUT} if TEST_INPUT else {"device": device} + proc = subprocess.Popen([sys.executable, str(ROOT / "app.py"), "--record", json.dumps({**spec, "left": left, "right": right})], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace") + state = {"on": True, "device": device, "left": left, "right": right, "state": "listening", "last": None} + _rec.update(proc=proc, state=state) + + def watch(): + for line in proc.stdout: + try: + said = json.loads(line) + except ValueError: + said = None + if not isinstance(said, dict): # not its own voice: the sound system's, or a crash + state["complaint"] = line.strip()[-300:] or state.get("complaint") + continue + if "done" not in said: + state.update(said) + continue + state.update(last={**said["done"], "tape": state.get("tape"), "side": state.get("side")}, state="listening", seconds=0, stopped=0) + if said["done"]["file"]: # transcribed at once, or as soon as the transcriber is free + folder, rel = Path(state["folder"]), Path(said["done"]["file"]).relative_to(state["folder"]).as_posix() + try: + _queue.append((folder, rel)) if _job["state"]["running"] else start_job(folder, [rel]) + except Exception: + pass # the sound is safe, and the side is "to do" like any other recording + if proc is _rec["proc"]: # it stopped without being told to: say what it said last + state.setdefault("error", state.get("complaint") or "The program that listens to the input stopped.") + state["on"] = False + threading.Thread(target=watch, daemon=True).start() + + +def tell(order): + """Give the listening program an order.""" + _rec["proc"].stdin.write(json.dumps(order) + "\n") + _rec["proc"].stdin.flush() + + +def level(given): + """A stop level as the page sends it: a number of dBFS, kept within reason, or None for "learn it".""" + return None if given is None else max(-120.0, min(float(given), -20.0)) + + +def bin_it(path): + """Put a file in the system's bin, where it can be had back; or where there is no bin to be had, set it aside + under a name the app does not take for a recording.""" + try: + from Foundation import NSURL, NSFileManager + if not TEST_INPUT and NSFileManager.defaultManager().trashItemAtURL_resultingItemURL_error_(NSURL.fileURLWithPath_(str(path)), None, None)[0]: + return # (a test's leavings are kept out of the person's bin) + except ImportError: + pass + os.replace(path, path.with_name(path.name + time.strftime(".replaced %Y-%m-%d %H.%M.%S"))) + + +def rescue(): + """Give a recording that was cut short (a crash, the power) its name. It is whole as far as it got.""" + folder, saved = pending()[0], [] + for part in sorted(folder.glob("*/*.wav.part")) if folder else []: + final, size = part.with_suffix(""), (part.stat().st_size - 44) // REC_BYTES * REC_BYTES + if size <= 0 or final.exists(): + continue + with open(part, "r+b") as f: # its header may be a couple of seconds behind + f.seek(4), f.write(struct.pack("//.wav.""" + body = request.get_json() + tape, side = (safe(name) if (name := str(body.get(k) or "").strip()) else "" for k in ("tape", "side")) + folder = pending()[0] + path = folder / tape / (side + ".wav") if folder and tape and side else None + there = [f for f in path.parent.iterdir() if f.name == path.name + ".part" or (f.stem == side and f.suffix.lower() in AUDIO) + ] if path and path.parent.is_dir() else [] + kept = [f for ext in (".json", ".fixes", ".m4a", ".peaks", ".emb.npy", ".sound.npy") if path and (f := TAPES / tape / (side + ext)).exists()] + taken = bool(there or kept) and not body.get("replace") + problem = ("Open the Record panel, so the input is being listened to." if not _rec["state"]["on"] or not _rec["proc"] + else "A side is already being recorded." if recording() + else "Give the tape and the side each a name." if not (tape and side) + else "Choose this session's recordings folder first, in Recordings…: the master is written there." if not folder + else "The recordings folder cannot be written to." if not os.access(folder, os.W_OK) + else f"There is already a recording called {tape} / {side}." if taken + else "There is not room on that disk for two hours of recording (2 GB)." if shutil.disk_usage(folder).free < 2e9 + else None) + if problem: + return jsonify({"error": problem, "exists": problem.startswith("There is already")}), 409 + for f in there: # recorded again: the old master goes to the bin, not out of existence + bin_it(f) + for f in kept: # what the app made from it is of no more use + f.unlink() + path.parent.mkdir(parents=True, exist_ok=True) + _rec["state"].update(folder=str(folder), tape=tape, side=side, last=None, state="waiting", seconds=0, stopped=0, auto=None) + tell({"record": str(path), "below": level(body.get("below"))}) + return jsonify(_rec["state"]) + + +@app.patch("/api/record") +def record_adjust(): + """While listening: move the stop level of the side being recorded ({"below": dBFS}), or forget the loudest and + quietest heard so far ({"forget": true}).""" + body = request.get_json() + if _rec["state"]["on"] and _rec["proc"]: + tell({"forget": True} if body.get("forget") else {"below": level(body.get("below"))}) + return jsonify(_rec["state"]) + + +@app.delete("/api/record") +def record_stop(): + """Stop the side being recorded, and go on listening; with ?all, stop listening too (the panel was closed).""" + if request.args.get("all") is not None: + hush() + elif recording(): + tell({"stop": True}) + return jsonify(_rec["state"]) + + @app.post("/api/share") def share(): """Collect the named recordings into one file in the exports folder.""" @@ -890,6 +1415,74 @@ def export(): def check(): + # Recording. Sound made to order: a tenth of a second of noise at a level, different every time. + import tempfile + import wave + import numpy as np + rng = np.random.default_rng(1) + as_bytes = lambda v: np.asarray(v, "CFBundleShortVersionString__VERSION__ CFBundleVersion__VERSION__ LSMinimumSystemVersion14.0 + NSMicrophoneUsageDescriptionTransclip records tapes from the sound input you choose. CFBundleIconFileAppIcon NSHighResolutionCapable diff --git a/smoke.py b/smoke.py index 00fdf4d..fb9be6d 100644 --- a/smoke.py +++ b/smoke.py @@ -56,7 +56,12 @@ def main(): s.bind(("127.0.0.1", 0)) port = s.getsockname()[1] base = f"http://127.0.0.1:{port}" - env = {**os.environ, "TRANSCLIP_HOME": str(tmp / "home"), "TRANSCLIP_PORT": str(port)} + # A tape to record from, standing in for a sound input: the deck stopped, six seconds of sound, the deck stopped for good. + tone(tmp / "sound.wav") + with wave.open(str(tmp / "deck.wav"), "wb") as w: + w.setnchannels(2), w.setsampwidth(2), w.setframerate(RATE) + w.writeframes(bytes(2 * RATE * 4) + frames(tmp / "sound.wav") + bytes(35 * RATE * 4)) + env = {**os.environ, "TRANSCLIP_HOME": str(tmp / "home"), "TRANSCLIP_PORT": str(port), "TRANSCLIP_TEST_INPUT": str(tmp / "deck.wav")} start = [os.environ.get("UV") or shutil.which("uv"), "run", "--script", str(ROOT / "app.py"), "--no-open"] log = open(tmp / "app.log", "w+", encoding="utf-8") app = subprocess.Popen(start, env=env, stdout=log, stderr=subprocess.STDOUT) @@ -218,6 +223,46 @@ def refused(path, body): assert call("PUT", "/api/session", {"name": "Second - project"})["transcribed"] == 1 print("sessions", flush=True) + # Recording a side: nowhere to put it at first, then named, started, and left to end by itself. + assert call("GET", "/api/inputs") == [{"name": "Test input", "channels": 2, "rate": RATE, "usual": True}] + # No sound is played in a test: with no output to play through, monitoring is refused. + assert call("GET", "/api/outputs") == [] and call("GET", "/api/monitor") == {"on": False} + try: + call("PUT", "/api/monitor", {"input": "Test input", "output": "Speakers"}) + raise AssertionError("monitoring started with nowhere to play") + except urllib.error.HTTPError as e: + assert e.code == 409, e.code + assert call("PUT", "/api/record", {"device": "Test input", "left": 0, "right": 1})["on"] + assert "recordings folder" in refused("/api/record", {"tape": "Reel", "side": "Side A"})["error"] + (tmp / "Transfers").mkdir() + call("PUT", "/api/library", {"folder": str(tmp / "Transfers"), "depth": 3}) + assert "name" in refused("/api/record", {"tape": " ", "side": "Side A"})["error"] + assert call("POST", "/api/record", {"tape": "Reel: one", "side": "Side A"})["state"] == "waiting" + done = wait("the side to end by itself", lambda: call("GET", "/api/record")["last"], 1) + master = tmp / "Transfers" / "Reel_ one" / "Side A.wav" + # A second of the stopped deck before the sound, all six seconds of it, and three after. + assert (done["why"], done["seconds"], done["auto"], done["clipped"], done["lost"], Path(done["file"])) == ("the side ended", 10.0, True, [], [], master), done + with wave.open(str(master)) as w: + assert (w.getframerate(), w.getnchannels(), w.getsampwidth(), w.getnframes()) == (RATE, 2, 3, 10 * RATE) + kept = w.readframes(10 * RATE) + played = frames(tmp / "sound.wav") # 16 bits a sample: in the master each has a silent byte beneath it + assert kept[RATE * 6:RATE * 6 + 9000] == b"".join(b"\0" + played[i:i + 2] for i in range(0, 6000, 2)), "the master is not what was played" + assert not any(kept[:RATE * 6]) and not any(kept[-3 * RATE * 6:]) and [p.name for p in master.parent.iterdir()] == ["Side A.wav"] + # It is transcribed without being asked, and its name cannot be used twice. + wait("the side to be transcribed", lambda: "Reel_ one/Side A" in {t["id"] for t in call("GET", "/api/tapes")}, 10) + assert call("PUT", "/api/record", {"device": "Test input", "left": 0, "right": 1})["on"] + again = refused("/api/record", {"tape": "Reel: one", "side": "Side A"}) + assert "already" in again["error"] and again["exists"] is True, again + # Unless it is said that the side is to be recorded again: the old master is then set aside, not destroyed, + # and this time the stop level is given, not learned. + assert call("POST", "/api/record", {"tape": "Reel: one", "side": "Side A", "replace": True, "below": -90})["state"] == "waiting" + done = wait("the side to be recorded again", lambda: call("GET", "/api/record")["last"], 1) + assert (done["why"], done["seconds"], Path(done["file"])) == ("the side ended", 10.0, master), done + assert sorted(p.name.split(".replaced")[0] for p in master.parent.iterdir()) == ["Side A.wav", "Side A.wav"], list(master.parent.iterdir()) + wait("the new side to be transcribed", lambda: "Reel_ one/Side A" in {t["id"] for t in call("GET", "/api/tapes")}, 10) + call("DELETE", "/api/record?all") + print("recording", flush=True) + assert (tmp / "home" / "session.txt").read_text(encoding="utf-8") == "Second - project" assert subprocess.run(start, env=env, timeout=300).returncode == 0 # a second launch finds the first and bows out call("POST", "/api/quit") diff --git a/static/index.html b/static/index.html index 3a2a69f..5625671 100644 --- a/static/index.html +++ b/static/index.html @@ -96,7 +96,38 @@ #depth { width: 4.5em; } #bar { width: 100%; } #jobnote, dialog small, dialog .small { color: var(--dim); font-size: 13px; overflow-wrap: anywhere; } -#closelib { margin-left: auto; } +#closelib, #recclose { margin-left: auto; } +#rec { white-space: nowrap; flex-shrink: 0; } +#recorder label.grow { flex: 1; } +#recorder label input { width: 100%; padding: 4px 8px; box-sizing: border-box; } +#input { flex: 1; min-width: 0; } +#meter { display: grid; grid-template-columns: 1.2em 1fr; gap: 4px 6px; margin: 12px 0 4px; } +#meter .names { display: grid; gap: 4px; line-height: 12px; } +#meter .bars { display: grid; gap: 4px; position: relative; } +#meter .bar { height: 12px; border-radius: 3px; overflow: hidden; background: linear-gradient(90deg, #3a6 0 82%, #db3 94%, #e44 100%); } +#meter .bar i { display: block; height: 100%; margin-left: auto; width: 100%; background: var(--line); } /* covers what is not lit */ +#meter .bars b { position: absolute; top: -3px; bottom: -3px; width: 2px; margin-left: -1px; } /* a level marked across both bars */ +#markstop { background: #6af; } +#marktarget { background: #fa3; } +#mdb { grid-column: 1 / -1; display: flex; gap: 1.2em; align-items: baseline; flex-wrap: wrap; } +#mtop.over { color: #fa3; } +#mreset { border: 0; background: none; color: var(--dim); padding: 0; text-decoration: underline; font-size: inherit; } +#clip.on { color: var(--bad); font-weight: 600; } +#recorder .levels label { flex: 1; display: flex; gap: 6px; align-items: center; white-space: nowrap; } +#recorder .levels input { flex: 1; min-width: 0; width: auto; padding: 0; } +#recorder .levels output { min-width: 7.5em; color: var(--dim); font-size: 13px; } +#monrow { flex-wrap: wrap; margin: 10px 0 4px; } +#monrow label { margin: 0; white-space: nowrap; display: flex; gap: 6px; align-items: center; } +#recorder #mon { width: auto; padding: 0; } +#monout { flex: 1; min-width: 0; } +#recstate { font-size: 20px; font-weight: 700; letter-spacing: .03em; min-height: 1.5em; margin: 12px 0 2px; } +#recstate.armed { color: #fa3; animation: armed .7s ease-in-out infinite alternate; } +#recstate.ending { color: #fa3; } +#recstate.on { color: var(--bad); } +@keyframes armed { to { opacity: .4; } } +#recnote { min-height: 2.8em; margin-top: 2px; overflow-wrap: anywhere; } +#recnote.bad { color: var(--bad); } +#recgo { min-width: 9em; padding: 6px 12px; font-weight: 600; } #lib { white-space: nowrap; max-width: 24em; overflow: hidden; text-overflow: ellipsis; flex-shrink: 0; } /* a session's name can be long */ #sessions { margin-bottom: 12px; padding-bottom: 12px; border-bottom: 1px solid var(--line); } #session { flex: 1; min-width: 0; } @@ -118,6 +149,7 @@
+ 00:00 / 00:00 @@ -169,6 +201,35 @@

Recordings

Recordings are only read, never changed, and nothing leaves this computer. Transcripts, listening copies, your clips and exports are kept in .

+ +

Record a tape

+ +
+
LR
+
+ clipped +
+
+ + +
+ +
+ + +
+

+

+
+

Press Record with the deck stopped, wait for ARMED, then press Play on the deck. The master begins a second before the tape's first sound, and the side ends by itself once the deck has been stopped for 30 seconds. It is written to this session's recordings folder as a 24-bit, 48 kHz WAV, and transcribed as soon as it ends.

+
@@ -735,11 +796,168 @@

Recordings

$('#library').close(); document.body.append(h('div', { id: 'gone', textContent: 'Transclip has quit. Your clips are saved. Open Transclip again to carry on.' })); }; +// ── Recording a tape ─────────────────────────────────────────────────────── + +let rec = null, recInputs = [], recTimer = null, clipLit = 0, sure = 0, recTold = null; // recTold: the finished side already reported +const going = () => rec?.state === 'waiting' || rec?.state === 'playing'; +// Text is only touched when it changes. Redrawing a button while it is being pressed loses the press in the Mac's window. +const put = (el, text) => { if (el.textContent !== text) el.textContent = text; }; +const recSay = (text, bad) => { put($('#recnote'), text); $('#recnote').className = bad ? 'bad' : ''; }; +const recCall = async (method, body, query = '') => { + const r = await fetch('/api/record' + query, { method, headers: { 'Content-Type': 'application/json' }, body: body && JSON.stringify(body) }).catch(() => null); + return { ok: !!r?.ok, d: await r?.json().catch(() => null) }; +}; +const theInput = () => recInputs.find(i => i.name === $('#input').value); +// "Side A" is followed by "Side B", "Side 3" by "Side 4". +const nextSide = side => side.replace(/[A-Ya-y0-8]$/, c => String.fromCharCode(c.charCodeAt(0) + 1)); +const onBar = db => Math.max(0, Math.min(1, ((db ?? -144) + 100) / 100)) * 100 + '%'; // the bars run from -100 dBFS to full scale +const stopSet = () => +$('#stoplevel').value <= -101 ? null : +$('#stoplevel').value; // null: learned from the lead-in + +// The channel menus for the chosen input: the pair used last time on it, or its first two. +function recChannels() { + const n = theInput()?.channels || 1, same = localStorage.recInput === $('#input').value; + for (const [sel, kept, first] of [['#chl', localStorage.recLeft, 0], ['#chr', localStorage.recRight, 1]]) { + $(sel).replaceChildren(...Array.from({ length: n }, (_, i) => h('option', { value: i, textContent: i + 1 }))); + $(sel).value = Math.min(same && kept != null ? +kept : first, n - 1); + } + $('#pair').hidden = n < 2; +} +// Listen to the chosen input and channels: the meter runs from here on. +async function recListen() { + if (!theInput()) return recSay('No sound input was found on this computer.', true); + Object.assign(localStorage, { recInput: $('#input').value, recLeft: $('#chl').value, recRight: $('#chr').value }); + const { ok, d } = await recCall('PUT', { device: $('#input').value, left: +$('#chl').value, right: +$('#chr').value }); + recSay(!ok ? d?.error || 'The input could not be opened. Is Transclip still running?' + : (d.rescued?.length ? `A recording that was cut short has been kept: ${d.rescued.join(', ')}. ` : '') + + (d.rate && d.rate !== 48000 ? `This input is running at ${d.rate / 1000} kHz and is converted to 48 kHz. Set it to 48 kHz for a master that is not converted.` : ''), !ok); +} +// Monitoring: the input played through to an output by a program apart from the recorder. +let recOutputs = []; +function monChannels() { + const n = recOutputs.find(o => o.name === $('#monout').value)?.channels || 2, same = localStorage.monOut === $('#monout').value; + for (const [sel, kept, first] of [['#monl', localStorage.monL, 0], ['#monr', localStorage.monR, 1]]) { + $(sel).replaceChildren(...Array.from({ length: n }, (_, i) => h('option', { value: i, textContent: i + 1 }))); + $(sel).value = Math.min(same && kept != null ? +kept : first, n - 1); + } + $('#monpair').hidden = n <= 2; +} +// Start it, start it afresh with what is now chosen, or stop it: whichever the tick box says. +async function monitorSet() { + Object.assign(localStorage, { monOut: $('#monout').value, monL: $('#monl').value, monR: $('#monr').value, monHear: $('#monhear').value }); + const wanted = $('#mon').checked; + const r = await fetch('/api/monitor', !wanted ? { method: 'DELETE' } : { method: 'PUT', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ input: $('#input').value, left: +$('#chl').value, right: +$('#chr').value, output: $('#monout').value, + out_left: +$('#monl').value, out_right: +$('#monr').value, hear: $('#monhear').value }) }).catch(() => null); + const failed = why => { $('#mon').checked = false; recSay(`The input could not be played through${why ? ': ' + why : '.'}`, true); }; + if (!wanted) return; + if (!r?.ok) return failed((await r?.json().catch(() => null))?.error); + setTimeout(async () => { // an output that will not open says so a moment later + const m = await fetch('/api/monitor').then(r => r.json()).catch(() => null); + if ($('#mon').checked && m && !m.on) failed(m.error); + }, 1500); +} +$('#mon').onchange = monitorSet; +$('#monout').onchange = () => { monChannels(); if ($('#mon').checked) monitorSet(); }; +$('#monl').onchange = $('#monr').onchange = $('#monhear').onchange = () => { if ($('#mon').checked) monitorSet(); }; + +// The two levels the person sets, drawn as marks across the meter. +function recLevels() { + const stop = stopSet() ?? rec?.below ?? null, target = +$('#target').value; + put($('#stopval'), stopSet() != null ? `${stopSet()} dBFS` : rec?.below != null ? `learned: ${Math.round(rec.below)} dBFS` : 'learned from the lead-in'); + put($('#targetval'), `${target} dBFS`); + $('#markstop').hidden = stop == null; + $('#markstop').style.left = onBar(stop); + $('#marktarget').style.left = onBar(target); +} +async function recTick() { + const r = await fetch('/api/record').catch(() => null); + if (!r?.ok) return; + rec = await r.json(); + $('#ml').style.width = `calc(100% - ${onBar(rec.l)})`; + $('#mr').style.width = `calc(100% - ${onBar(rec.r)})`; + const heard = rec.on && rec.l != null, top = heard ? Math.max(...rec.top) : null, target = +$('#target').value; + put($('#mnum'), heard ? `L ${rec.l.toFixed(1)} R ${rec.r.toFixed(1)} dBFS` : ''); + put($('#mtop'), heard ? `loudest so far L ${rec.top[0].toFixed(1)} R ${rec.top[1].toFixed(1)} (${Math.abs(top - target).toFixed(1)} dB ${top > target ? 'over' : 'under'} target) · quietest ${rec.quietest.toFixed(1)}` : ''); + $('#mtop').className = heard && top > target ? 'over' : ''; + if (rec.clip) clipLit = Date.now() + 3000; + $('#clip').className = Date.now() < clipLit ? 'on' : ''; + $('#clip').style.visibility = Date.now() < clipLit ? 'visible' : 'hidden'; + recLevels(); + const armed = rec.state === 'waiting', playing = rec.state === 'playing', ending = playing && rec.stopped >= 3; + put($('#recstate'), armed ? 'ARMED · press Play on the deck' : ending ? `DECK STOPPED · the side ends in ${Math.ceil(30 - rec.stopped)} s` + : playing ? `● RECORDING · ${rec.side} · ${fmt(rec.seconds)}` : ''); + $('#recstate').className = armed ? 'armed' : ending ? 'ending' : playing ? 'on' : ''; + put($('#recgo'), armed ? 'Cancel' : ending ? 'End side now' : playing ? (Date.now() < sure ? 'Press again to stop' : 'Stop') : 'Record'); + $('#recgo').disabled = !rec.on; + for (const id of ['#input', '#chl', '#chr', '#tapename', '#sidename', '#recclose']) $(id).disabled = going(); + if (going()) { + recSay(rec.lost ? `The sound system has lost sound ${rec.lost} time${rec.lost === 1 ? '' : 's'} on this side: the master will have gaps.` + : armed ? 'Waiting for the tape. The master will begin a second before its first sound.' + : rec.auto === false ? 'The input was not quiet when Record was pressed, so this side will not end by itself: press Stop when it is over, or set a stop level.' + : ending ? 'Sound returning carries the side on.' : '', rec.lost > 0); + } else if (rec.last && recTold !== rec.last.file + rec.last.seconds) { // a side has just finished + recTold = rec.last.file + rec.last.seconds; + const d = rec.last, why = { 'the side ended': 'it ended by itself when the deck stopped', stopped: 'stopped by you' }[d.why] || d.why; + recSay(d.file ? `${d.side} is recorded: ${span(d.seconds)}, ${why}. Saved as ${d.file}. It is being transcribed and will appear in the list.` + + (d.clipped?.length ? ` It clipped at ${d.clipped.map(fmt).join(', ')}: the level was too high there.` : '') + + (d.lost?.length ? ` The sound system lost sound at ${d.lost.map(fmt).join(', ')}: the master has gaps there.` : '') : `Nothing was recorded: ${why}.`, + !d.file || d.clipped?.length > 0 || d.lost?.length > 0); + if (d.file) { $('#sidename').value = nextSide(d.side); library(); } + } else if (!rec.on && rec.error && !rec.last) recSay(`The input cannot be heard: ${rec.error}`, true); +} +$('#rec').onclick = async () => { + recInputs = await fetch('/api/inputs').then(r => r.json()).catch(() => []); + $('#input').replaceChildren(...recInputs.map(i => h('option', { value: i.name, textContent: `${i.name} (${i.channels} in)` }))); + if (recInputs.some(i => i.name === localStorage.recInput)) $('#input').value = localStorage.recInput; + recChannels(); + recOutputs = await fetch('/api/outputs').then(r => r.json()).catch(() => []); + $('#monrow').hidden = !recOutputs.length; + $('#monout').replaceChildren(...recOutputs.map(o => h('option', { value: o.name, textContent: `${o.name} (${o.channels} out)` }))); + $('#monout').value = (recOutputs.find(o => o.name === localStorage.monOut) || recOutputs.find(o => o.usual) || recOutputs[0])?.name ?? ''; + $('#monhear').value = localStorage.monHear || 'both'; + $('#mon').checked = false; // never on by itself: sound should not start because a panel was opened + monChannels(); + $('#stoplevel').value = localStorage.recStop ?? -101; + $('#target').value = localStorage.recTarget ?? -6; + recTold = null; sure = 0; + recLevels(); + $('#recorder').showModal(); + await recListen(); + recTimer = setInterval(recTick, 120); +}; +$('#input').onchange = async () => { recChannels(); await recListen(); if ($('#mon').checked) monitorSet(); }; +$('#chl').onchange = $('#chr').onchange = async () => { await recListen(); if ($('#mon').checked) monitorSet(); }; +$('#stoplevel').oninput = () => { + localStorage.recStop = $('#stoplevel').value; + recLevels(); + if (going() && stopSet() != null) recCall('PATCH', { below: stopSet() }); // moved while a side runs: it counts from now +}; +$('#target').oninput = () => { localStorage.recTarget = $('#target').value; recLevels(); }; +$('#mreset').onclick = () => recCall('PATCH', { forget: true }); +async function recStart(replace) { + const { ok, d } = await recCall('POST', { tape: $('#tapename').value, side: $('#sidename').value, below: stopSet(), replace }); + if (ok) return; + recSay(d?.error || 'That did not work. Is Transclip still running?', true); + // Recording a side again is allowed, once it has been said: the old master goes to the bin. + if (d?.exists) $('#recnote').append(' ', h('button', { type: 'button', textContent: 'Record it again, and put the old one in the bin', onclick: () => recStart(true) })); +} +$('#recgo').onclick = () => { + if (!going()) return recStart(false); + // A side in full flow is not stopped by one stray press. Armed, or with the deck already stopped, once is enough. + if (rec.state === 'playing' && rec.stopped < 3 && Date.now() > sure) return void (sure = Date.now() + 4000); + sure = 0; + recCall('DELETE'); +}; +$('#recclose').onclick = () => $('#recorder').close(); +$('#recorder').addEventListener('cancel', e => { if (going()) e.preventDefault(); }); // Esc does not walk away from a side +$('#recorder').addEventListener('close', () => { clearInterval(recTimer); recCall('DELETE', null, '?all'); }); +fetch('/api/inputs').then(r => r.json()).then(list => { $('#rec').hidden = !list.length; }).catch(() => {}); + // While a job runs or the panel is open, keep the picture current. setInterval(() => { if (lib?.job.running || $('#library').open) library(); }, 2000); document.addEventListener('keydown', e => { - if (!tape || $('#library').open || e.metaKey || e.ctrlKey || e.altKey || e.target.matches('input:not([type=range]), select, textarea')) return; + if (!tape || $('#library').open || $('#recorder').open || e.metaKey || e.ctrlKey || e.altKey || e.target.matches('input:not([type=range]), select, textarea')) return; const t = audio.currentTime; if (e.key === ' ') { e.preventDefault(); toggle(); } else if (e.key === 'Enter') clipFromSelection(); From c75799e024284a1c73f4dafbcd4e1acdea5a2fe2 Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Wed, 14 Oct 2026 21:55:03 +1100 Subject: [PATCH 2/6] Say what the recorder last said when a test side does not end Co-Authored-By: Claude Opus 5.5 --- smoke.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/smoke.py b/smoke.py index fb9be6d..1a3a3a7 100644 --- a/smoke.py +++ b/smoke.py @@ -238,7 +238,10 @@ def refused(path, body): call("PUT", "/api/library", {"folder": str(tmp / "Transfers"), "depth": 3}) assert "name" in refused("/api/record", {"tape": " ", "side": "Side A"})["error"] assert call("POST", "/api/record", {"tape": "Reel: one", "side": "Side A"})["state"] == "waiting" - done = wait("the side to end by itself", lambda: call("GET", "/api/record")["last"], 1) + try: + done = wait("the side to end by itself", lambda: call("GET", "/api/record")["last"], 1) + except AssertionError: # what the recorder last said is the clue, and it is not in the app's log + raise AssertionError(f"the side did not end; the recorder's state: {call('GET', '/api/record')}") master = tmp / "Transfers" / "Reel_ one" / "Side A.wav" # A second of the stopped deck before the sound, all six seconds of it, and three after. assert (done["why"], done["seconds"], done["auto"], done["clipped"], done["lost"], Path(done["file"])) == ("the side ended", 10.0, True, [], [], master), done From d46cbb473129bd2a44978308f68c40e0d5775256 Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Wed, 14 Oct 2026 21:57:54 +1100 Subject: [PATCH 3/6] Signposts in the recorder's test path, to see where Windows stops Co-Authored-By: Claude Opus 5.5 --- app.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app.py b/app.py index b6b6267..ce4c5e4 100644 --- a/app.py +++ b/app.py @@ -363,7 +363,9 @@ def listen_for_orders(): threading.Thread(target=listen_for_orders, daemon=True).start() if spec.get("file"): # Tests: a sound file stands in for an input. It would be over before Record was pressed, so it waits for that. + print(json.dumps({"test": "waiting for Record"}), flush=True) orders.put(orders.get()) + print(json.dumps({"test": "playing the file"}), flush=True) played = subprocess.Popen([FFMPEG, "-v", "error", "-i", spec["file"], "-af", f"pan=stereo|c0=c{int(spec['left'])}|c1=c{int(spec['right'])}", "-ar", str(REC_RATE), "-f", "s24le", "-"], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE) incoming = lambda: (played.stdout.read(REC_BLOCK), False) From 48cda8ae94b33b4dd1c0232f5196db7fe1c904cf Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Wed, 14 Oct 2026 22:01:26 +1100 Subject: [PATCH 4/6] Read a test's sound file directly, without ffmpeg On Windows the ffmpeg started by the recorder to play the stand-in file never delivered anything. Tests only ever give it a WAV, which needs no ffmpeg: 16- and 24-bit come out as the same 24-bit samples. Co-Authored-By: Claude Opus 5.5 --- app.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/app.py b/app.py index ce4c5e4..03292d1 100644 --- a/app.py +++ b/app.py @@ -362,13 +362,20 @@ def listen_for_orders(): orders.put(None) # the app closed the panel, or is no longer there threading.Thread(target=listen_for_orders, daemon=True).start() if spec.get("file"): - # Tests: a sound file stands in for an input. It would be over before Record was pressed, so it waits for that. - print(json.dumps({"test": "waiting for Record"}), flush=True) + # Tests: a WAV at 48 kHz stands in for an input. It would be over before Record was pressed, so it waits for that. + import wave + import numpy as np orders.put(orders.get()) - print(json.dumps({"test": "playing the file"}), flush=True) - played = subprocess.Popen([FFMPEG, "-v", "error", "-i", spec["file"], "-af", f"pan=stereo|c0=c{int(spec['left'])}|c1=c{int(spec['right'])}", - "-ar", str(REC_RATE), "-f", "s24le", "-"], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE) - incoming = lambda: (played.stdout.read(REC_BLOCK), False) + played = wave.open(spec["file"]) + width, count = played.getsampwidth(), played.getnchannels() + + def incoming(): + raw = np.frombuffer(played.readframes(REC_RATE // 10), np.uint8).reshape(-1, count, width).astype(np.int32) + v = (raw[..., -1] ^ 0x80) - 0x80 # the top byte carries the sign; whatever the depth, made 24-bit + for i in range(2, width + 1): + v = v << 8 | raw[..., -i] + v = v << 8 * (3 - width) if width < 3 else v >> 8 * (width - 3) + return np.ascontiguousarray(v[:, [int(spec["left"]), int(spec["right"])]], " Date: Wed, 14 Oct 2026 22:04:43 +1100 Subject: [PATCH 5/6] Temporary signposts in the recorder's first pass, for Windows Co-Authored-By: Claude Opus 5.5 --- app.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/app.py b/app.py index 03292d1..3b46de7 100644 --- a/app.py +++ b/app.py @@ -365,8 +365,11 @@ def listen_for_orders(): # Tests: a WAV at 48 kHz stands in for an input. It would be over before Record was pressed, so it waits for that. import wave import numpy as np + print(json.dumps({"test": "1 waiting for Record"}), flush=True) orders.put(orders.get()) + print(json.dumps({"test": "2 opening the file"}), flush=True) played = wave.open(spec["file"]) + print(json.dumps({"test": "3 opened"}), flush=True) width, count = played.getsampwidth(), played.getnchannels() def incoming(): @@ -425,8 +428,11 @@ def finish(why): kept_at_last_settle = 0 top, quietest = [-200.0, -200.0], 0.0 # the loudest each channel has been and the quietest the input has been, since asked to forget lost = [] # where in the side being kept the sound system lost sound, in seconds + first = bool(spec.get("file")) while True: + first and print(json.dumps({"test": "4 reading"}), flush=True) block, gap = incoming() # waits until a tenth of a second has come in + first and print(json.dumps({"test": f"5 read {len(block)}"}), flush=True) closing = False while not orders.empty(): order = orders.get() @@ -447,7 +453,9 @@ def finish(why): break if gap and side and side.state == "playing": lost.append(side.kept / 10) + first and print(json.dumps({"test": "6 measuring"}), flush=True) level, left, right, clipped = measure(block) + first and print(json.dumps({"test": "7 measured"}), flush=True) top, quietest = [max(top[0], left), max(top[1], right)], min(quietest, level) if side: try: @@ -462,6 +470,8 @@ def finish(why): finish(f"it could not be written: {e}") if side and side.state == "over": finish("the side ended") + first and print(json.dumps({"test": "8 heard"}), flush=True) + first = False learning = bool(side) and side.below is None and side.floor is None say(l=left, r=right, clip=clipped, level=level, top=top, quietest=quietest, state=side.state if side else "listening", seconds=side.kept / 10 if side else 0, stopped=len(side.held) / 10 if side else 0, From 140e71a3923ff8047ac9e2a5c4a459ed0fafd8cc Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Wed, 14 Oct 2026 22:35:58 +1100 Subject: [PATCH 6/6] Load the recorder's libraries before waiting on its input On Windows the recorder never got past loading numpy: it did so after starting the thread that waits on standard input, and loading it while that thread waits on the pipe does not finish. The signposts used to find this are gone. Co-Authored-By: Claude Opus 5.5 --- app.py | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/app.py b/app.py index 3b46de7..e0d9439 100644 --- a/app.py +++ b/app.py @@ -354,6 +354,12 @@ def say(**message): except OSError: pass # the app has gone: the side is still finished properly + # Everything is loaded before a thread starts waiting on standard input: on Windows, loading numpy + # while another thread waits on that pipe never finishes. + import wave + import numpy as np + if not spec.get("file"): + import sounddevice as sd orders = queue.Queue() def listen_for_orders(): @@ -363,13 +369,8 @@ def listen_for_orders(): threading.Thread(target=listen_for_orders, daemon=True).start() if spec.get("file"): # Tests: a WAV at 48 kHz stands in for an input. It would be over before Record was pressed, so it waits for that. - import wave - import numpy as np - print(json.dumps({"test": "1 waiting for Record"}), flush=True) orders.put(orders.get()) - print(json.dumps({"test": "2 opening the file"}), flush=True) played = wave.open(spec["file"]) - print(json.dumps({"test": "3 opened"}), flush=True) width, count = played.getsampwidth(), played.getnchannels() def incoming(): @@ -384,7 +385,6 @@ def incoming(): # nothing is skipped because this program was busy. (ffmpeg's own Mac input keeps only the newest buffer, # and on the interface this was built with it lost one in nine.) If the sound system itself ever has to # throw sound away it says so, and so does a jump in the buffers' own clock: either way the side is told. - import sounddevice as sd waiting, clock = queue.Queue(), {"next": None} def arrived(data, frames, when, status): @@ -428,11 +428,8 @@ def finish(why): kept_at_last_settle = 0 top, quietest = [-200.0, -200.0], 0.0 # the loudest each channel has been and the quietest the input has been, since asked to forget lost = [] # where in the side being kept the sound system lost sound, in seconds - first = bool(spec.get("file")) while True: - first and print(json.dumps({"test": "4 reading"}), flush=True) block, gap = incoming() # waits until a tenth of a second has come in - first and print(json.dumps({"test": f"5 read {len(block)}"}), flush=True) closing = False while not orders.empty(): order = orders.get() @@ -453,9 +450,7 @@ def finish(why): break if gap and side and side.state == "playing": lost.append(side.kept / 10) - first and print(json.dumps({"test": "6 measuring"}), flush=True) level, left, right, clipped = measure(block) - first and print(json.dumps({"test": "7 measured"}), flush=True) top, quietest = [max(top[0], left), max(top[1], right)], min(quietest, level) if side: try: @@ -470,8 +465,6 @@ def finish(why): finish(f"it could not be written: {e}") if side and side.state == "over": finish("the side ended") - first and print(json.dumps({"test": "8 heard"}), flush=True) - first = False learning = bool(side) and side.below is None and side.floor is None say(l=left, r=right, clip=clipped, level=level, top=top, quietest=quietest, state=side.state if side else "listening", seconds=side.kept / 10 if side else 0, stopped=len(side.held) / 10 if side else 0,