diff options
| author | Charlie Root <root@dangofactory.local> | 2026-10-25 10:15:31 +0900 |
|---|---|---|
| committer | Charlie Root <root@dangofactory.local> | 2026-10-25 10:15:31 +0900 |
| commit | 7318435b737394904bb1c5ce9fe013b0eee1882f (patch) | |
| tree | 41adf14909f5f8d15c8e1c5db361e6ea0ac97598 /src/spoon.c | |
| download | mpegcap-baseline-1016.tar.gz mpegcap-baseline-1016.zip | |
kare / spoon - CX23416 + FX2 USB MPEG capture toolHEADbaseline-1016
Capture tool for the I-O DATA GV-MVP/RZ2 (04bb:0514): Conexant CX23416 MPEG
encoder behind an EZ-USB FX2 bridge, with a CX25837 video decoder (I2C 0x44)
and a WM8739 audio ADC (I2C 0x1a). libusb-1.0, C99, built with GNU make on
FreeBSD/Linux.
kare capture: MPEG-2 PS or raw HM12 (y4m), MPEG audio, --pcm WAV,
live parameter control through CTLFILE
spoon live viewer: pipe -> ffmpeg -> SDL2, clickable control bar,
resizable window, raw PCM playback on -r
State at this commit:
- MPEG-2 PS 720x480 ~6.5 Mbit/s, colour, mp2 48 kHz stereo 224 kbit/s
- raw HM12 (NV12_16L16, 518,416-byte frames) with selective median denoise
- S-Video works: luma In1 + chroma In5 (0x103=0xd0); RCA is In2+In6 (0xe1)
- VBI cropped: 0x0474=24 with 0x0477=28 (they must move together, +4)
- audio: never issue an I2C READ to the WM8739 (write-only part)
History note: this repository was squashed to a single commit on 2026-10-25
because the earlier history carried the CX23416 firmware images and the vendor
trees. Those still exist on the working copy (firmware/, ref/) and are in
.gitignore; only src/, include/, Makefile, README.md and .gitignore are
versioned. The pre-squash history is preserved locally as a bundle.
Diffstat (limited to 'src/spoon.c')
| -rw-r--r-- | src/spoon.c | 1969 |
1 files changed, 1969 insertions, 0 deletions
diff --git a/src/spoon.c b/src/spoon.c new file mode 100644 index 0000000..764d769 --- /dev/null +++ b/src/spoon.c @@ -0,0 +1,1969 @@ +/* + * spoon — single-binary live viewer for the GV-MVP/RZ2 (kare's sibling). + * + * The user's ask (2026-10-15): + * - NOT a shell+python pipeline: one C program. + * - ffplay embedded = libavformat/libavcodec/libswresample + + * SDL2 for video+audio out (this host: SDL2 OSS -> /dev/dsp, hw.snd + * default_unit 9 = HDMI). + * - MODE: mpeg (video+audio) | raw (y4m from kare's HM12 writer). + * Audio ON/OFF freely selectable (raw is video-only by chip design). + * - Minimal lag: we read the growing live FILE directly (no HTTP, no + * sockets), poll at 2 ms, decode the moment a packet exists, and never + * buffer ahead. Audio is the master clock (if enabled) so A/V stays + * synced while both run as close to the write edge as possible. + * + * Usage: + * spoon [-a] [-m | -r] [-f FILE] [-W] -- by default it LAUNCHES + * kare itself (like live-play.sh did) and follows its --live file; + * -f follows an existing file only; -a disables audio; -W keeps video + * window off (audio-only monitor); -m/-r pick MPEG vs raw(y4m) capture. + * + * Build (FreeBSD, ffmpeg + SDL2 from ports): + * cc -O2 -o spoon spoon.c \ + * $(pkg-config --cflags --libs libavformat libavcodec \ + * libswresample libavutil sdl2) + */ + +#include <ctype.h> +#include <errno.h> +#include <fcntl.h> +#include <math.h> +#include <signal.h> +#include <stdarg.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <poll.h> +#include <sys/ioctl.h> +#include <sys/stat.h> +#include <sys/wait.h> +#include <sys/socket.h> + +/* + * Windows support (2026-10-16). spoon was POSIX-only: fork/execv to + * start kare, pipe(), pread(), kill/waitpid, setenv, usleep. The layer + * below keeps the SAME code body with Windows primitives: + * pipe() -> _pipe (_O_BINARY) + * fork+execv -> _spawnvp(_P_NOWAIT) with the pipe write end dup'ed onto + * stdout for the child (the classic _dup2/_spawn/restore) + * kill() -> TerminateProcess (last resort; the graceful stop goes + * through the control channel's "Q" command) + * pread() -> win_pread() (_lseeki64 + _read) + * usleep() -> Sleep(), setenv() -> _putenv_s() + * NOT compile-verified here: there is no MinGW/MSVC toolchain on this FreeBSD + * host, so build this path on Windows (see the spoon note in Makefile.win). + */ +#if defined(_WIN32) +#include <windows.h> +#include <io.h> +#include <fcntl.h> +#include <process.h> +#define usleep(us) Sleep((DWORD)((us) / 1000)) +static int win_setenv(const char *k, const char *v) { return _putenv_s(k, v); } +#define setenv win_setenv +static ssize_t win_pread(int fd, void *buf, size_t n, off_t off) +{ + _lseeki64(fd, (long long)off, SEEK_SET); + return (ssize_t)_read(fd, buf, (unsigned)n); +} +#define pread win_pread +static int win_pipe(int fds[2]) { return _pipe(fds, 1 << 20, _O_BINARY); } +#define pipe win_pipe +static void win_kill(int pid) +{ + if (pid > 0) + TerminateProcess((HANDLE)(intptr_t)pid, 0); +} +#define kill(pid, sig) win_kill(pid) +/* waitpid(pid, st, WNOHANG) / waitpid(pid, st, 0) -> WaitForSingleObject */ +#ifndef WNOHANG +#define WNOHANG 1 +#endif +static int win_waitpid(int pid, int *st, int opt) +{ + (void)st; + if (pid <= 0) + return -1; + return WaitForSingleObject((HANDLE)(intptr_t)pid, + opt ? 0 : INFINITE) == WAIT_OBJECT_0 + ? pid : 0; +} +#define waitpid win_waitpid +#endif + +#include <SDL.h> +#ifdef SDL_AUDIO +#include <SDL_audio.h> +#endif + +#include <libavformat/avformat.h> +#include <libavcodec/avcodec.h> +#include <libswresample/swresample.h> +#include <libavutil/imgutils.h> +#include <libavutil/opt.h> +#include <libavutil/time.h> + +/* ---------------- tunables ---------------- */ +static int opt_audio = 1; /* -a toggles */ +static int opt_raw = 0; /* -r raw y4m, -m mpeg (default) */ +static int opt_novideo = 0; /* -W */ +static const char *opt_file = NULL; /* -f */ +/* ★ No live file any more (2026-10-16): when spoon launches the capture + * it uses a pipe. The old /tmp/spoon-<uid>.bin existed for VLC and was + * never truncated, so a raw (15.5 MB/s) session filled the root FS. */ +static const char *kare_path = "./kare"; +static const char *fw_mpeg = "firmware/cx23416/cx_1_raw.bin"; + +/* live file poll: the whole point is NOT to wait */ +#define POLL_US 2000 /* 2 ms */ +#define PROBE_SIZE (1 << 20) + +static float dc_x1 = 0.0f, dc_y1 = 0.0f; /* DC-blocker state */ +static volatile sig_atomic_t g_stop = 0; +static void on_sig(int s) { (void)s; g_stop = 1; } + +/* ---------------- SDL audio out ---------------- */ +static SDL_AudioSpec g_aspec; +static Uint8 *g_abuf = NULL; /* ring */ +static size_t g_abuf_sz, g_awrite, g_aread; +/* + * ★ A/V latency: the ring used to be allowed to fill to its full 2 s and the + * whole capture loop is gated by "ring nearly full", so the PICTURE ran up to + * ~2 s ahead of the audio you hear (reported: "MPEG audio lags the picture by + * several seconds"). Keep only ~250 ms of unplayed audio queued; + * MPEGVIEW_ABUF=<ms> retunes it. + */ +static size_t g_abuf_target = 0; +static SDL_mutex *g_amtx = NULL; + +static void audio_cb(void *u, Uint8 *stream, int len) +{ + (void)u; + size_t avail = (g_awrite >= g_aread) ? g_awrite - g_aread + : g_abuf_sz - g_aread + g_awrite; + size_t n = (size_t)len < avail ? (size_t)len : avail; + size_t first = g_abuf_sz - g_aread; + if (first > n) first = n; + memcpy(stream, g_abuf + g_aread, first); + if (n > first) + memcpy(stream + first, g_abuf, n - first); + memset(stream + n, 0, (size_t)len - n); + g_aread = (g_aread + n) % g_abuf_sz; +} + +/* total buffered bytes pending in the ring */ +static size_t audio_pending(void) +{ + size_t a = (g_awrite >= g_aread) ? g_awrite - g_aread + : g_abuf_sz - g_aread + g_awrite; + return a; +} + +/* ---------------- video out (SDL2 texture) ---------------- + * Zero-copy note (measured 2026-10-15): this host is Intel IvyBridge HD4000 + * with i915kms + GLAMOR Textured Video (Xv PutImage only, no VA-API path for + * live MPEG-2 here). SDL_UpdateYUVTexture uploads the decoded frame to the + * GPU texture once per frame and RenderPresent flips it via DRI3/Present — + * that IS the zero-copy display path on this stack: no /tmp file, no extra + * userland copy of the pixels (the only copy is the required GPU upload, + * which DMA-BUF import would also need for a software-decoded frame). + * True DMA-BUF import (drm_prime / VA-API decode-to-surface) only pays off + * with hardware decode; our frames come from libavcodec software decode, so + * texture upload is already the floor. If a future VA-API path lands, swap + * SDL_UpdateYUVTexture for AV_HWFramesContext + SDL texture-from-DMA-BUF. */ +static SDL_Window *g_win = NULL; +static SDL_Renderer *g_ren = NULL; +static SDL_Texture *g_tex = NULL; + + +/* + * ★ A/V sync for the live MPEG view. The audio you hear is inevitably behind + * the picture by (SDL ring + the OSS kernel buffer, ~340 ms here and not + * tunable because the sysctl is read-only). The picture is decoded and drawn + * the moment it arrives, so the ONLY way to line the two up is to hold the + * video back by that same amount. Frames are queued with their arrival time + * and drawn once they are old enough. + * MPEGVIEW_VDELAY=<ms> extra delay (default 340 = the kernel play buffer) + * MPEGVIEW_VDELAY=0 disable the whole thing + */ + +/* + * ★ Low-frequency noise removal (hum + rumble). Measured on a silent source: + * the MPEG audio carries a 60 Hz hum with a strong harmonic series + * (120/180/240/300 Hz) plus broadband hiss, so a plain DC blocker is not + * enough. Chain: 2nd-order high-pass (kills the 60 Hz fundamental and the + * rumble below it) followed by narrow notches at f0..5*f0 (kills the + * harmonics). Verified offline on a captured stream: -27.5 dB at 60 Hz, + * -21.6..-22.3 dB at the harmonics, and -0.0 dB from 500 Hz up, i.e. the + * program band is untouched. + * MPEGVIEW_HPF=<Hz> high-pass corner (default 80; 0 = off) + * MPEGVIEW_HUM=<f0> mains frequency (default 60; 0 = no notches) + * MPEGVIEW_NODC=1 disables the whole chain (as before) + */ +struct bq { float b0, b1, b2, a1, a2, x1, x2, y1, y2; }; + +static void bq_hp(struct bq *q, double fs, double f0, double qq) +{ + double w0 = 2.0 * M_PI * f0 / fs, a = sin(w0) / (2.0 * qq), + c = cos(w0), a0 = 1.0 + a; + memset(q, 0, sizeof(*q)); + q->b0 = (float)((1.0 + c) / 2.0 / a0); + q->b1 = (float)(-(1.0 + c) / a0); + q->b2 = (float)((1.0 + c) / 2.0 / a0); + q->a1 = (float)(-2.0 * c / a0); + q->a2 = (float)((1.0 - a) / a0); +} + +static void bq_notch(struct bq *q, double fs, double f0, double qq) +{ + double w0 = 2.0 * M_PI * f0 / fs, a = sin(w0) / (2.0 * qq), + c = cos(w0), a0 = 1.0 + a; + memset(q, 0, sizeof(*q)); + q->b0 = (float)(1.0 / a0); + q->b1 = (float)(-2.0 * c / a0); + q->b2 = (float)(1.0 / a0); + q->a1 = (float)(-2.0 * c / a0); + q->a2 = (float)((1.0 - a) / a0); +} + +static inline float bq_run(struct bq *q, float x) +{ + float y = q->b0 * x + q->b1 * q->x1 + q->b2 * q->x2 - + q->a1 * q->y1 - q->a2 * q->y2; + q->x2 = q->x1; q->x1 = x; + q->y2 = q->y1; q->y1 = y; + return y; +} + +#define NHUM 5 +static struct bq g_hpf; +static int g_hpf_on; +static struct bq g_hum[NHUM]; +static int g_nhum; + +static void audio_filters_init(double fs) +{ + const char *e; + double f0; + if (getenv("MPEGVIEW_NODC")) + return; + e = getenv("MPEGVIEW_HPF"); + f0 = e ? atof(e) : 80.0; + if (f0 > 0.0 && f0 < fs / 2.0) { + bq_hp(&g_hpf, fs, f0, 0.707); + g_hpf_on = 1; + } + e = getenv("MPEGVIEW_HUM"); + f0 = e ? atof(e) : 60.0; + if (f0 > 0.0) { + int k; + for (k = 0; k < NHUM; k++) { + double h = f0 * (k + 1); + if (h < fs / 2.0 - 100.0) { + bq_notch(&g_hum[g_nhum], fs, h, 15.0); + g_nhum++; + } + } + } + fprintf(stderr, "audio filters: high-pass %s, %d hum notches at " + "%.0f Hz series\n", g_hpf_on ? "on" : "off", g_nhum, f0); +} + +static void audio_filters_apply(int16_t *p, size_t n) +{ + size_t i; + int k; + if (!g_hpf_on && !g_nhum) + return; + for (i = 0; i < n; i++) { + float x = (float)p[i]; + for (k = 0; k < g_nhum; k++) + x = bq_run(&g_hum[k], x); + if (g_hpf_on) + x = bq_run(&g_hpf, x); + if (x > 32767.0f) x = 32767.0f; + if (x < -32768.0f) x = -32768.0f; + p[i] = (int16_t)x; + } +} + +static void video_show(AVFrame *fr); /* defined below */ +static void ctl_send(const char *fmt, ...); /* defined below */ +static int g_again; /* volume, defined below */ + + +#define VDQ_N 48 +static AVFrame *g_vq[VDQ_N]; +static double g_vt[VDQ_N]; +static int g_vq_n; + +static double vdq_delay_ms(void) +{ + double d; + const char *e = getenv("MPEGVIEW_VDELAY"); + /* + * Measured with tools/dsp_lat.c: the kernel hands out 1024-byte blocks + * (5.3 ms) and its whole queue is only 8192 B (43 ms), so the device + * side is NOT the problem -- the app's own ring is (it used to be + * allowed to hold 2 s). Default to a small device allowance. + */ + d = e ? (double)atol(e) : 50.0; + if (g_abuf_target) { + size_t p = audio_pending(); + double denom = (double)g_aspec.freq * + (double)(g_aspec.channels ? g_aspec.channels : 2) * 2.0; + if (denom > 0.0) + d += (double)p / denom * 1000.0; + } + return d < 0.0 ? 0.0 : d; +} + +static void vdq_push(AVFrame *fr) +{ + if (g_vq_n >= VDQ_N) { + /* keep the queue bounded: drop the oldest */ + av_frame_unref(g_vq[0]); + memmove(g_vq, g_vq + 1, sizeof(g_vq[0]) * (size_t)(g_vq_n - 1)); + memmove(g_vt, g_vt + 1, sizeof(g_vt[0]) * (size_t)(g_vq_n - 1)); + g_vq_n--; + } + g_vq[g_vq_n] = av_frame_alloc(); + av_frame_ref(g_vq[g_vq_n], fr); + g_vt[g_vq_n] = SDL_GetTicks() / 1000.0; + g_vq_n++; +} + +static void vdq_flush(void) +{ + double now = SDL_GetTicks() / 1000.0; + double d = vdq_delay_ms() / 1000.0; + while (g_vq_n > 0 && now - g_vt[0] >= d) { + video_show(g_vq[0]); + av_frame_unref(g_vq[0]); + memmove(g_vq, g_vq + 1, sizeof(g_vq[0]) * (size_t)(g_vq_n - 1)); + memmove(g_vt, g_vt + 1, sizeof(g_vt[0]) * (size_t)(g_vq_n - 1)); + g_vq_n--; + } +} + +/* values the bar cycles (the keys change the same ones) */ +static int g_yc_bypass = 0; /* vendor coring (2/9/3/6) or bypass */ +static int g_gr_mode = 0; /* 0 on, 1 off, 2 through */ +static int g_svideo = 0; +static int g_lc = 2, g_lg = 9, g_cc = 3, g_cg = 6; +static int g_ycmode = 0; /* 0 = 3D Y/C, 1 = 2D Y/C + NR */ +static int g_pre = 1; /* 1 = PREGHSTS -2.6us, 0 = -1.0us */ + +/* ================================================================== + * ★ Control bar (2026-10-24) + * + * A real, clickable strip across the top of the window. Every option that can + * change while the capture runs has a chip; clicking a chip cycles its value. + * Nothing here restarts the capture: + * DEINT / VOL act in this process + * LP / NT / PAD / IN / YC / GR / YCM / PRE go to kare over CTLFILE + * ARST / WM send the two recovery commands (see the notes) + * + * The chips are laid out by measuring them, so adding an entry to g_chips is + * all it takes to add an option; the bar wraps to as many rows as it needs and + * the window grows to match, which is why the height is computed before the + * window is created. + * + * No SDL_ttf on this host, so labels are drawn from a 5x7 bitmap font + * generated by tools/gen_font.py. + * ================================================================== */ +#define BAR_ROW_H 30 + +/* generated by tools/gen_font.py - do not edit by hand */ +static const char g_font_chars[] = " %+-./0123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ"; +static const unsigned char g_font[][7] = { + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, /* */ + { 0x18, 0x19, 0x02, 0x04, 0x08, 0x13, 0x03 }, /* % */ + { 0x00, 0x04, 0x04, 0x1f, 0x04, 0x04, 0x00 }, /* + */ + { 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00 }, /* - */ + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x0c }, /* . */ + { 0x01, 0x01, 0x02, 0x04, 0x08, 0x10, 0x10 }, /* / */ + { 0x0e, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0e }, /* 0 */ + { 0x04, 0x0c, 0x04, 0x04, 0x04, 0x04, 0x0e }, /* 1 */ + { 0x0e, 0x11, 0x01, 0x02, 0x04, 0x08, 0x1f }, /* 2 */ + { 0x1e, 0x01, 0x01, 0x0e, 0x01, 0x01, 0x1e }, /* 3 */ + { 0x02, 0x06, 0x0a, 0x12, 0x1f, 0x02, 0x02 }, /* 4 */ + { 0x1f, 0x10, 0x1e, 0x01, 0x01, 0x11, 0x0e }, /* 5 */ + { 0x0e, 0x10, 0x10, 0x1e, 0x11, 0x11, 0x0e }, /* 6 */ + { 0x1f, 0x01, 0x02, 0x04, 0x08, 0x08, 0x08 }, /* 7 */ + { 0x0e, 0x11, 0x11, 0x0e, 0x11, 0x11, 0x0e }, /* 8 */ + { 0x0e, 0x11, 0x11, 0x0f, 0x01, 0x01, 0x0e }, /* 9 */ + { 0x00, 0x0c, 0x0c, 0x00, 0x0c, 0x0c, 0x00 }, /* : */ + { 0x0e, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11 }, /* A */ + { 0x1e, 0x11, 0x11, 0x1e, 0x11, 0x11, 0x1e }, /* B */ + { 0x0e, 0x11, 0x10, 0x10, 0x10, 0x11, 0x0e }, /* C */ + { 0x1e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x1e }, /* D */ + { 0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x1f }, /* E */ + { 0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x10 }, /* F */ + { 0x0e, 0x11, 0x10, 0x17, 0x11, 0x11, 0x0f }, /* G */ + { 0x11, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11 }, /* H */ + { 0x1f, 0x04, 0x04, 0x04, 0x04, 0x04, 0x1f }, /* I */ + { 0x07, 0x02, 0x02, 0x02, 0x02, 0x12, 0x0c }, /* J */ + { 0x11, 0x12, 0x14, 0x18, 0x14, 0x12, 0x11 }, /* K */ + { 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1f }, /* L */ + { 0x11, 0x1b, 0x15, 0x15, 0x11, 0x11, 0x11 }, /* M */ + { 0x11, 0x19, 0x15, 0x13, 0x11, 0x11, 0x11 }, /* N */ + { 0x0e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e }, /* O */ + { 0x1e, 0x11, 0x11, 0x1e, 0x10, 0x10, 0x10 }, /* P */ + { 0x0e, 0x11, 0x11, 0x11, 0x15, 0x12, 0x0d }, /* Q */ + { 0x1e, 0x11, 0x11, 0x1e, 0x14, 0x12, 0x11 }, /* R */ + { 0x0f, 0x10, 0x10, 0x0e, 0x01, 0x01, 0x1e }, /* S */ + { 0x1f, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04 }, /* T */ + { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e }, /* U */ + { 0x11, 0x11, 0x11, 0x11, 0x11, 0x0a, 0x04 }, /* V */ + { 0x11, 0x11, 0x11, 0x15, 0x15, 0x1b, 0x11 }, /* W */ + { 0x11, 0x11, 0x0a, 0x04, 0x0a, 0x11, 0x11 }, /* X */ + { 0x11, 0x11, 0x0a, 0x04, 0x04, 0x04, 0x04 }, /* Y */ + { 0x1f, 0x01, 0x02, 0x04, 0x08, 0x10, 0x1f }, /* Z */ +}; +/* 43 glyphs */ + + +static void bar_glyph(SDL_Renderer *r, int x, int y, int s, char c) +{ + const char *p = strchr(g_font_chars, c); + int idx, row, col; + + if (!p) + p = strchr(g_font_chars, ' '); + if (!p) + return; + idx = (int)(p - g_font_chars); + for (row = 0; row < 7; row++) { + unsigned v = g_font[idx][row]; + for (col = 0; col < 5; col++) { + if (v & (1u << (4 - col))) { + SDL_Rect rc = { x + col * s, y + row * s, s, s }; + SDL_RenderFillRect(r, &rc); + } + } + } +} + +static void bar_text(SDL_Renderer *r, int x, int y, int s, const char *txt) +{ + int i; + for (i = 0; txt[i]; i++) + bar_glyph(r, x + i * 6 * s, y, s, txt[i]); +} + +static int bar_text_w(const char *txt, int s) +{ + int n = (int)strlen(txt); + return n ? (n * 6 - 1) * s : 0; +} + +/* ---- the options ------------------------------------------------- */ + +struct bar_chip { + void (*text)(char *buf, size_t n); /* label + current value */ + void (*click)(void); /* advance one step */ + /* + * ★ The WIDEST label this chip can ever show. + * + * The chip is sized from this, not from the current label: measuring the + * live label and keeping the width made the text spill out of its box the + * moment a longer value was selected ("YCM 3D" -> "YCM 2D+NR", + * "LP OFF" -> "LP 15K"), and because the layout was only computed once, + * the spilled text could also run into the next chip. + */ + const char *widest; +}; + +/* VOL (this process) */ +static const int g_vol_pct[4] = { 100, 75, 50, 25 }; +static int g_vol_i = 0; +static void chip_vol_text(char *b, size_t n) +{ + snprintf(b, n, "VOL %d", g_vol_pct[g_vol_i]); +} +static void chip_vol_click(void) +{ + g_vol_i = (g_vol_i + 1) % 4; + g_again = g_vol_pct[g_vol_i]; + fprintf(stderr, "bar: volume %d%%\n", g_again); +} + +/* LP low-pass (kare) */ +static const int g_lp_hz[4] = { 0, 15000, 10000, 6000 }; +static const char *g_lp_names[4] = { "OFF", "15K", "10K", "6K" }; +static int g_lp_i; +static void chip_lp_text(char *b, size_t n) +{ + snprintf(b, n, "LP %s", g_lp_names[g_lp_i]); +} +static void chip_lp_click(void) +{ + g_lp_i = (g_lp_i + 1) % 4; + ctl_send("LP %d", g_lp_hz[g_lp_i]); + fprintf(stderr, "bar: LP %s\n", g_lp_names[g_lp_i]); +} + +/* NT notch (kare) */ +static const int g_nt_hz[4] = { 0, 15734, 15625, 60 }; +static const char *g_nt_names[4] = { "OFF", "15734", "15625", "HUM" }; +static int g_nt_i; +static void chip_nt_text(char *b, size_t n) +{ + snprintf(b, n, "NT %s", g_nt_names[g_nt_i]); +} +static void chip_nt_click(void) +{ + g_nt_i = (g_nt_i + 1) % 4; + ctl_send("NTCH %d", g_nt_hz[g_nt_i]); + fprintf(stderr, "bar: notch %s\n", g_nt_names[g_nt_i]); +} + +/* PAD attenuation (kare) */ +static const int g_pad_db[4] = { 0, -6, -12, -18 }; +static int g_pad_i; +static void chip_pad_text(char *b, size_t n) +{ + snprintf(b, n, "PAD %d", g_pad_db[g_pad_i]); +} +static void chip_pad_click(void) +{ + g_pad_i = (g_pad_i + 1) % 4; + ctl_send("PAD %d", g_pad_db[g_pad_i]); + fprintf(stderr, "bar: pad %d dB\n", g_pad_db[g_pad_i]); +} + +/* INPUT: composite vs S-Video. Composite reaches the decoder as Y/C through + * the NEC pair (luma In2, chroma In6, 0x103=0xe1). ★ The S jack is + * MEASURED (2026-10-25, a recorder plugged in): luma In1 + chroma In5, + * 0x103=0xd0 - it shows a real picture, while the old 0xc3 (luma In4) is a + * dead flat black frame. */ +static void chip_in_text(char *b, size_t n) +{ + snprintf(b, n, "IN %s", g_svideo ? "SVID" : "COMP"); +} +static void chip_in_click(void) +{ + g_svideo = !g_svideo; + ctl_send("IN 0x%x", g_svideo ? 0xd0 : 0xe1); + ctl_send("MODE 0xf2"); + fprintf(stderr, "bar: input %s\n", g_svideo ? "svideo" : "composite"); +} + +/* YC: the NEC coring/ghost pairs, or bypass */ +static void chip_yc_text(char *b, size_t n) +{ + snprintf(b, n, "YC %s", g_yc_bypass ? "BYPASS" : "VENDOR"); +} +static void chip_yc_click(void) +{ + g_yc_bypass = !g_yc_bypass; + if (g_yc_bypass) + ctl_send("YC0"); + else + ctl_send("YC %d %d %d %d", g_lc, g_lg, g_cc, g_cg); + fprintf(stderr, "bar: YC %s\n", g_yc_bypass ? "bypass" : "vendor"); +} + +/* GR: ghost reduction mode (0 on, 1 off, 2 through) */ +static const char *g_gr_names[3] = { "ON", "OFF", "THRU" }; +static void chip_gr_text(char *b, size_t n) +{ + snprintf(b, n, "GR %s", g_gr_names[g_gr_mode % 3]); +} +static void chip_gr_click(void) +{ + g_gr_mode = (g_gr_mode + 1) % 3; + ctl_send("GR %d", g_gr_mode); + fprintf(stderr, "bar: ghost %s\n", g_gr_names[g_gr_mode]); +} + +/* YCM: 3-D Y/C or 2-D + noise reduction (the 3-D filter keeps a frame of + * memory, which is what drags colour behind a cut) */ +static void chip_ycm_text(char *b, size_t n) +{ + snprintf(b, n, "YCM %s", g_ycmode ? "2D+NR" : "3D"); +} +static void chip_ycm_click(void) +{ + g_ycmode = !g_ycmode; + ctl_send("YCMODE %d", g_ycmode); + fprintf(stderr, "bar: Y/C mode %s\n", g_ycmode ? "2D+NR" : "3D"); +} + +/* PRE: ghost pre-filter position */ +static void chip_pre_text(char *b, size_t n) +{ + snprintf(b, n, "PRE %s", g_pre ? "-2.6" : "-1.0"); +} +static void chip_pre_click(void) +{ + g_pre = !g_pre; + ctl_send("PRE %d", g_pre); + fprintf(stderr, "bar: pre-ghost %s\n", g_pre ? "-2.6us" : "-1.0us"); +} + +/* ARST: CX2341X_ENC_MISC 12, the audio-interface reset. Measured to flip a + * live capture out of the wrong audio state, so it is worth one click. */ +static void chip_arst_text(char *b, size_t n) +{ + snprintf(b, n, "ARESET"); +} +static void chip_arst_click(void) +{ + ctl_send("ARESET"); + fprintf(stderr, "bar: sent ARESET\n"); +} + +/* WM: re-send the WM8739 bring-up (measured NOT to fix the state, kept because + * it is the cheap test if a future firmware behaves differently) */ +static void chip_wm_text(char *b, size_t n) +{ + snprintf(b, n, "CODEC"); +} +static void chip_wm_click(void) +{ + ctl_send("WM"); + fprintf(stderr, "bar: re-sent WM8739 bring-up\n"); +} + +static const struct bar_chip g_chips[] = { + { chip_vol_text, chip_vol_click , "VOL 100" }, + { chip_lp_text, chip_lp_click , "LP 15K" }, + { chip_nt_text, chip_nt_click , "NT 15734" }, + { chip_pad_text, chip_pad_click , "PAD -18" }, + { chip_in_text, chip_in_click , "IN SVIDEO" }, + { chip_yc_text, chip_yc_click , "YC VENDOR" }, + { chip_gr_text, chip_gr_click , "GR THRU" }, + { chip_ycm_text, chip_ycm_click , "YCM 2D+NR" }, + { chip_pre_text, chip_pre_click , "PRE -2.6" }, + { chip_arst_text, chip_arst_click , "ARESET" }, + { chip_wm_text, chip_wm_click , "CODEC" }, +}; +#define NCHIP ((int)(sizeof(g_chips) / sizeof(g_chips[0]))) + +#define CHIP_MAX 32 +static int g_chip_x[NCHIP], g_chip_y[NCHIP], g_chip_w[NCHIP]; +static int g_bar_rows = 1, g_bar_h = BAR_ROW_H, g_bar_lay_w; + +/* + * Lay the chips out for a window of width w: left to right, wrapping when the + * next chip would not fit. Called before the window is created (so the window + * can be tall enough) and again on resize. + */ +static void bar_layout(int w) +{ + char buf[CHIP_MAX]; + int i, x = 6, y = 4, row = 0; + + g_bar_lay_w = w; + for (i = 0; i < NCHIP; i++) { + int cw; + snprintf(buf, sizeof(buf), "%s", + g_chips[i].widest ? g_chips[i].widest : ""); + cw = bar_text_w(buf, 2) + 14; /* 7 px each side */ + if (x + cw > w - 6 && x > 6) { + x = 6; + y += BAR_ROW_H - 6; + row++; + } + g_chip_x[i] = x; + g_chip_y[i] = y; + g_chip_w[i] = cw; + x += cw + 4; + } + g_bar_rows = row + 1; + /* + * Height = the last chip's bottom edge plus a margin, so there is padding + * under the bar instead of the video starting flush against it. (The + * first version used a fixed 10 px, which left the second row of chips + * with no room at all once there were 12 of them.) + */ + g_bar_h = (g_bar_rows - 1) * (BAR_ROW_H - 6) + 4 + + (BAR_ROW_H - 14) + 8; +} + +static void bar_draw(SDL_Renderer *r, int w) +{ + SDL_Rect bg = { 0, 0, w, g_bar_h }; + char buf[CHIP_MAX]; + int i; + + if (g_bar_lay_w != w) + bar_layout(w); + + SDL_SetRenderDrawColor(r, 24, 24, 28, 255); + SDL_RenderFillRect(r, &bg); + + for (i = 0; i < NCHIP; i++) { + SDL_Rect rc = { g_chip_x[i], g_chip_y[i], + g_chip_w[i], BAR_ROW_H - 14 }; + SDL_SetRenderDrawColor(r, 58, 58, 66, 255); + SDL_RenderFillRect(r, &rc); + SDL_SetRenderDrawColor(r, 210, 210, 215, 255); + g_chips[i].text(buf, sizeof(buf)); + bar_text(r, g_chip_x[i] + 6, g_chip_y[i] + 2, 2, buf); + } +} + +static void bar_click(int x, int y) +{ + int i; + if (y >= g_bar_h) + return; + for (i = 0; i < NCHIP; i++) { + if (x >= g_chip_x[i] && x < g_chip_x[i] + g_chip_w[i] && + y >= g_chip_y[i] && y < g_chip_y[i] + BAR_ROW_H - 14) { + g_chips[i].click(); + return; + } + } +} + +static void video_show(AVFrame *fr) +{ + if (!g_win) { + /* + * The bar's height depends on how many chips fit in one row, so it + * has to be laid out BEFORE the window exists - otherwise the window + * is created one row too short and the bottom of the picture (and the + * last row of chips) is cut off. Measured: 12 chips wrapped to two + * rows wanted 58 px but the window had been made with 30, and the + * bottom-right of the video was missing. + */ + bar_layout(fr->width); + /* + * Linear filtering on the upscale: at 2x the nearest-neighbour + * look is all stair-steps, and the encoder's picture is already + * soft. Set before the renderer is created - the hint is read + * once, when the texture is made. + */ + SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"); + if (SDL_CreateWindowAndRenderer(fr->width, fr->height + g_bar_h, + SDL_WINDOW_RESIZABLE, &g_win, &g_ren) < 0) { + fprintf(stderr, "SDL video: %s\n", SDL_GetError()); + opt_novideo = 1; + return; + } + SDL_SetWindowTitle(g_win, "spoon"); + /* + * Below ~400 px wide the chips wrap to so many rows that the + * bar alone fills the window (measured: at 240x150 the bar + * took all of it and the picture was not drawn at all), so + * keep the window from going that small. + */ + SDL_SetWindowMinimumSize(g_win, 400, 300); + g_tex = SDL_CreateTexture(g_ren, + SDL_PIXELFORMAT_YV12, + SDL_TEXTUREACCESS_STREAMING, + fr->width, fr->height); + if (!g_tex) { + fprintf(stderr, "SDL texture: %s\n", SDL_GetError()); + opt_novideo = 1; + return; + } + } + SDL_UpdateYUVTexture(g_tex, NULL, + fr->data[0], fr->linesize[0], + fr->data[1], fr->linesize[1], + fr->data[2], fr->linesize[2]); + { + /* + * ★ The window is resizable, so draw into the CURRENT window + * size, not the frame size. The first version used + * {0, bar, fr->width, fr->height} no matter what the window + * was, so dragging the window bigger only added black - the + * picture stayed 720x480 in the corner. Now the picture is + * scaled to fit the area below the bar, aspect kept, and + * centred (letterbox), so resizing up enlarges it and + * resizing down shrinks it instead of cropping. + * + * The bar itself stays at native pixel size on purpose: the + * chips are a fixed-size UI and bar_click() works in window + * pixels, so scaling it would need a coordinate transform + * for every click. + */ + int ww = 0, wh = 0; + double s; + SDL_Rect dst; + + SDL_GetRendererOutputSize(g_ren, &ww, &wh); + if (ww <= 0 || wh <= 0) { + ww = fr->width; + wh = fr->height + g_bar_h; + } + /* the bar may need another row at the new width */ + if (g_bar_lay_w != ww) + bar_layout(ww); + + if (wh - g_bar_h < 1) { + /* window squeezed below the bar: draw the bar only */ + SDL_SetRenderDrawColor(g_ren, 0, 0, 0, 255); + SDL_RenderClear(g_ren); + bar_draw(g_ren, ww); + SDL_RenderPresent(g_ren); + return; + } + + s = (double)(wh - g_bar_h) / (double)fr->height; + if ((double)ww / (double)fr->width < s) + s = (double)ww / (double)fr->width; + if (s <= 0.0) + s = 1.0; + dst.w = (int)((double)fr->width * s + 0.5); + dst.h = (int)((double)fr->height * s + 0.5); + if (dst.w < 1) dst.w = 1; + if (dst.h < 1) dst.h = 1; + dst.x = (ww - dst.w) / 2; + dst.y = g_bar_h + (wh - g_bar_h - dst.h) / 2; + + /* SPOON_SCALEDBG=1: print what the resize maths decided */ + { + const char *dbg = getenv("SPOON_SCALEDBG"); + static int last_w = -1, last_h = -1; + if (dbg && (ww != last_w || wh != last_h)) { + last_w = ww; + last_h = wh; + fprintf(stderr, "scale: window %dx%d bar %d -> " + "picture %dx%d at %d,%d (x%.3f)\n", + ww, wh, g_bar_h, dst.w, dst.h, + dst.x, dst.y, s); + } + } + + /* + * ★ SDL_RenderClear fills with the DRAW colour, not with black + * - and the previous frame's bar_draw leaves it at the glyph + * grey (210,210,215). Without this line the letterbox around + * an enlarged picture came out light grey instead of black + * (measured: 66 px strips down both sides at 1440x900). + */ + SDL_SetRenderDrawColor(g_ren, 0, 0, 0, 255); + SDL_RenderClear(g_ren); + SDL_RenderCopy(g_ren, g_tex, NULL, &dst); + bar_draw(g_ren, ww); + } + SDL_RenderPresent(g_ren); +} + +/* ---------------- growing-file AVIO for libavformat ---------------- + * libavformat normally wants seekable input; a growing file is fine if we + * implement seek only within written data and report HUGE file size so the + * MPEG-PS demuxer never pre-scans to the end. */ +/* + * MPEGVIEW_AUDIO=1 (raw mode): show the raw YUV picture in SDL *and* play the + * encoder PCM at the same time. Reference: ivtv exposes raw YUV on + * /dev/video32 and PCM on /dev/video24 from the same subtype-0x03 session -- + * one stream demultiplexed into two outputs. We do the same: kare takes the + * PCM out of the raw stream and hands it over on fd 3 (--pcmfd 3) while the + * now-clean video arrives on the y4m pipe. + */ +static int g_audio_on = 0; +/* + * ★ MPEGVIEW_AUDIOVOL=<percent> (default 25): the raw PCM comes straight off + * the encoder front end at ~-5 dBFS (measured), i.e. about 40 dB hotter than + * the MPEG audio path, so it is painfully loud as-is. Scale before queueing. + */ +/* + * ★ Default 100%, not 25% (2026-10-23). + * + * 25% is -12 dB applied in software to int16 samples: the top two bits of + * every sample are thrown away before the device sees them, and the raw path + * then plays 12 dB quieter than the mixer expects. It was introduced when the + * raw PCM was believed to be overdriven - but those +-32768 peaks were the + * byte-swapped sample halves (fixed in 5efed36), not clipping. Measured with + * the swap in place and a real source playing: peak -11 dBFS, rms -27 dBFS, + * crest 15 dB, i.e. 11 dB of headroom, so no scaling is needed at all. + * + * MPEGVIEW_AUDIOVOL=<0..200> still overrides it, and the level meter printed + * every second ("audio level: peak ... rms ... crest ...") shows whether a + * given source actually needs attenuation. + */ +static int g_again = 100; +static int g_audio_ok = 1; /* SDL audio subsystem came up */ +static int g_pcmin = -1; +static int g_pfd2[2] = { -1, -1 }; +static SDL_AudioDeviceID g_adev = 0; +static unsigned char g_pcmbuf[65536]; + +static int g_fd = -1; +/* ★ 2026-10-16: when spoon launches kare itself there is NO live + * file any more -- kare writes into a pipe (-o -) and we read it. The + * growing --live file existed for VLC, which needs a seekable file; spoon + * IS the player (SDL), so nothing needs to seek, and a pipe cannot fill the + * disk. (The live file took the root FS to ENOSPC on 2026-10-16: 15.5 MB/s + * of raw y4m, and neither kare nor spoon ever truncates it.) A pipe + * also puts the reader exactly at the live edge. */ +static int g_usepipe = 0; +static off_t g_maxpos = 0; /* highest byte ever read = live edge */ +static off_t g_pos = 0; /* OUR logical position (what libav thinks). + * libav buffers ahead, so the fd position is + * NOT the logical position; SEEK_CUR must be + * relative to this, not to lseek(SEEK_CUR). */ + +static int fio_read(void *opaque, uint8_t *buf, int buf_size) +{ + (void)opaque; + for (;;) { + ssize_t n; + if (g_usepipe) { + /* sequential: a pipe has no offsets, and the reader + * is always at the live edge */ + n = read(g_fd, buf, (size_t)buf_size); + if (n > 0) { + g_pos += n; + g_maxpos = g_pos; + return (int)n; + } + if (n == 0) { /* writer gone */ + if (g_stop) return AVERROR_EOF; + usleep(POLL_US); + continue; + } + if (errno == EINTR) continue; + return AVERROR(errno); + } + n = pread(g_fd, buf, (size_t)buf_size, g_pos); + if (n > 0) { + g_pos += n; + if (g_pos > g_maxpos) + g_maxpos = g_pos; + return (int)n; + } + if (n == 0) { + /* -f <complete file>: real EOF, report it. Growing + * live file: not written yet = the live edge; libav + * treats AVERROR(EAGAIN) as "retry". */ + if (opt_file) + return AVERROR_EOF; + if (g_stop) return AVERROR_EOF; + usleep(POLL_US); + continue; + } + if (errno == EINTR) continue; + return AVERROR(errno); + } +} +static int64_t fio_seek(void *opaque, int64_t offset, int whence) +{ + (void)opaque; + int64_t pos; + /* A pipe cannot seek: say so, and let libavformat run in streaming + * mode (it does that for stdin/ffplay too). */ + if (g_usepipe) + return AVERROR(ENOSYS); + switch (whence) { + case SEEK_CUR: pos = g_pos + offset; break; + case SEEK_END: + /* -f <complete file>: report the real size (the mpeg demuxer + * needs it for duration/stream detection). Growing file: + * keep the huge lie so it never pre-scans to "the end". */ + if (opt_file) { + struct stat fst; + if (fstat(g_fd, &fst) == 0) + return (int64_t)fst.st_size + offset; + return AVERROR(EIO); + } + pos = (1LL << 40) + offset; + break; + case AVSEEK_SIZE: + if (opt_file) { + struct stat fst; + if (fstat(g_fd, &fst) == 0) + return (int64_t)fst.st_size; + return AVERROR(EIO); + } + return 1LL << 40; /* lie: huge */ + default: pos = offset; break; + } + if (!opt_file && pos > g_maxpos) return AVERROR(EINVAL); /* beyond edge */ + g_pos = pos; + return pos; +} + +/* ---------------- live parameter control (CTLFILE) ---------------- + * ★ 2026-10-16: spoon is the keyboard front-end for kare's CTLFILE + * command channel, so the NEC/decoder parameters can be changed while the + * picture runs -- no recompile, no replug. spoon only appends text + * lines; kare owns the device and executes them (and echoes the result + * to its own stderr). + * + * b uPD64084GC coring bypass <-> vendor coring (the "noise reduction") + * g uPD64031A ghost reduction: ON -> OFF -> THROUGH + * c input mux: composite (NEC pair, In2+In6) <-> S-Video (In4+chroma) + * s read back the uPD64031A status register RD00 + * h/l luma core -/+ H/L luma gain -/+ + * j/k chroma core -/+ J/K chroma gain -/+ + * p print what the keys do + * Disabled entirely when -f <file> is used (no capture child of ours). + */ +static FILE *g_ctl = NULL; +static char g_ctlpath[96]; + +static void ctl_send(const char *fmt, ...) +{ + char line[128]; + va_list ap; + if (!g_ctl) + return; + va_start(ap, fmt); + vsnprintf(line, sizeof(line), fmt, ap); + va_end(ap); + fprintf(g_ctl, "%s\n", line); + fflush(g_ctl); + fprintf(stderr, "spoon: %s\n", line); +} + +static void key_help(void) +{ + fprintf(stderr, + "keys: b=coring bypass g=GR on/off/through c=input " + "s=status o=show all\n" + " m=Y/C mode (3D <-> 2D+NR) a=pre-ghost range " + "(-1.0 <-> -2.6us)\n" + " h/l luma core j/k chroma core Shift+those = gains " + "p=help q=quit\n"); +} + +static void key_action(SDL_Keycode k, int shift) +{ + switch (k) { + case SDLK_b: + g_yc_bypass = !g_yc_bypass; + if (g_yc_bypass) + ctl_send("YC0"); + else + ctl_send("YC %d %d %d %d", g_lc, g_lg, g_cc, g_cg); + break; + case SDLK_g: + g_gr_mode = (g_gr_mode + 1) % 3; + ctl_send("GR %d", g_gr_mode); + break; + case SDLK_c: + g_svideo = !g_svideo; + /* composite reaches the decoder as Y/C via the NEC pair + * (luma In2 / chroma In6); the S jack map (In4) is an + * unverified assumption - see chip_in_text() */ + if (g_svideo) + ctl_send("IN 0xc3"); + else + ctl_send("IN 0xe1"); + ctl_send("MODE 0xf2"); + break; + case SDLK_s: + ctl_send("R 0x12 0"); + break; + case SDLK_h: if (shift) { if (g_lg > 0) g_lg--; } else if (g_lc > 0) g_lc--; goto yc; + case SDLK_l: if (shift) { if (g_lg < 15) g_lg++; } else if (g_lc < 15) g_lc++; goto yc; + case SDLK_j: if (shift) { if (g_cg > 0) g_cg--; } else if (g_cc > 0) g_cc--; goto yc; + case SDLK_k: if (shift) { if (g_cg < 15) g_cg++; } else if (g_cc < 15) g_cc++; goto yc; +yc: + g_yc_bypass = 0; + ctl_send("YC %d %d %d %d", g_lc, g_lg, g_cc, g_cg); + break; + case SDLK_m: + g_ycmode = !g_ycmode; + ctl_send("YCMODE %d", g_ycmode); + break; + case SDLK_a: + g_pre = !g_pre; + ctl_send("PRE %d", g_pre); + break; + case SDLK_o: + ctl_send("SHOW"); + break; + case SDLK_p: + key_help(); + break; + case SDLK_q: + case SDLK_ESCAPE: + g_stop = 1; + break; + } +} + +/* ---------------- second input: the split PCM file ---------------- + * ★ MPEGVIEW_PCM=<path> with -r: kare runs the one-pass split + * (SPLITAV=1, subtype 0x03) and writes the y4m video to our pipe plus the + * raw PCM to a growing RIFF/WAVE file. We open that file with a second + * AVIO (same growing-file policy as the main input) and play its audio, so + * the live view has BOTH raw video and raw audio. + */ +static int p_fd = -1; +static off_t p_pos = 0, p_maxpos = 0; + +static int pio_read(void *opaque, uint8_t *buf, int buf_size) +{ + (void)opaque; + for (;;) { + ssize_t n = pread(p_fd, buf, (size_t)buf_size, p_pos); + if (n > 0) { + p_pos += n; + if (p_pos > p_maxpos) p_maxpos = p_pos; + return (int)n; + } + if (n == 0) { + if (g_stop) return AVERROR_EOF; + usleep(POLL_US); /* still being written */ + continue; + } + if (errno == EINTR) continue; + return AVERROR(errno); + } +} +static int64_t pio_seek(void *opaque, int64_t offset, int whence) +{ + (void)opaque; + int64_t pos; + switch (whence) { + case SEEK_CUR: pos = p_pos + offset; break; + case SEEK_END: pos = (1LL << 40) + offset; break; + case AVSEEK_SIZE: return 1LL << 40; /* lie: never pre-scan */ + default: pos = offset; break; + } + p_pos = pos; + return pos; +} + +/* ---------------- main ---------------- */ +int main(int argc, char **argv) +{ + int i; + for (i = 1; i < argc && argv[i]; i++) { + const char *a = argv[i]; + if (!strcmp(a, "-a")) opt_audio = 0; + else if (!strcmp(a, "-r")) opt_raw = 1; + else if (!strcmp(a, "-m")) opt_raw = 0; + else if (!strcmp(a, "-W")) opt_novideo = 1; + else if (!strcmp(a, "-f") && i + 1 < argc) opt_file = argv[++i]; + else { fprintf(stderr, "usage: spoon [-a] [-m|-r] [-W] [-f FILE]\n run as the desktop user (needs DISPLAY + XAUTHORITY); root use -W or -f\n"); return 1; } + } + + /* + * ★ Say which build this is (2026-10-24). A running window keeps the + * code it was started with, so "the fix changed nothing" has twice been + * an old process on this project; the stamp makes that visible instead + * of arguable. + */ + fprintf(stderr, "spoon build %s %s\n", __DATE__, __TIME__); + + signal(SIGINT, on_sig); + signal(SIGTERM, on_sig); + /* A closed pipe (the capture child exiting) must not kill the player + * mid-cleanup: EPIPE comes back as a write error instead. */ + signal(SIGPIPE, SIG_IGN); + pid_t cap = -1; + const char *live = opt_file ? opt_file : "pipe:"; + if (!opt_file) { + /* If no X display is reachable, fail fast with a clear message + * instead of capturing invisibly (root without XAUTHORITY hits + * this; run as the desktop user, e.g. beatrice). */ + if (!opt_novideo && !getenv("DISPLAY")) { + fprintf(stderr, "spoon: no DISPLAY; run as the " + "desktop user (e.g. beatrice) or with -W " + "(audio only)\n"); + return 1; + } + /* + * ★ No live file: kare writes into a pipe (-o -) and we + * read it. execv() directly (not via /bin/sh) so the pid we + * kill at the end IS kare -- the old sh -c wrapper left + * kare running when only the shell got the SIGTERM. + */ + int pfd[2]; + if (pipe(pfd) < 0) { perror("pipe"); return 1; } + /* live parameter channel: kare opens CTLFILE, we append */ + snprintf(g_ctlpath, sizeof(g_ctlpath), "/tmp/spoon-%d.ctl", + (int)geteuid()); + unlink(g_ctlpath); + { + FILE *f = fopen(g_ctlpath, "w"); + if (f) + fclose(f); + } + setenv("CTLFILE", g_ctlpath, 1); + { + char *av[32]; + int n = 0; + g_audio_on = getenv("MPEGVIEW_AUDIO") != NULL; + av[n++] = (char *)kare_path; + if (g_audio_on && opt_raw) { + /* + * ★ A socketpair, not a pipe (2026-10-23). + * + * FreeBSD's pipe buffer is fixed at 64 KB + * (BIG_PIPE_SIZE) and there is no + * F_SETPIPE_SZ, so the audio path only has + * 64 KB = 341 ms of slack. The viewer + * drains it from the same loop that decodes + * video, and one slow frame is enough for + * the writer to hit EAGAIN - kare then + * DROPS the record (it must not block, that + * stalls USB). Measured with a pipe: 563 + * records in 13.8 s where the rate demands + * 575, i.e. 12 gaps of 24 ms - a click + * about once a second, while the standalone + * --pcm file path loses none. + * + * SO_SNDBUF/SO_RCVBUF on a unix socket are + * tunable, so the same fix costs one call + * and gives seconds of slack instead of + * 341 ms. MPEGVIEW_PCMBUF sets the size + * (bytes, default 1 MB = 5.4 s). + */ + if (socketpair(AF_UNIX, SOCK_STREAM, 0, + g_pfd2) == 0) { + const char *bs = getenv("MPEGVIEW_PCMBUF"); + int want = bs && *bs ? atoi(bs) : 1048576; + if (want < 65536) + want = 65536; + setsockopt(g_pfd2[0], SOL_SOCKET, + SO_RCVBUF, &want, sizeof(want)); + setsockopt(g_pfd2[1], SOL_SOCKET, + SO_SNDBUF, &want, sizeof(want)); + { + int got = 0; + socklen_t gl = sizeof(got); + getsockopt(g_pfd2[0], SOL_SOCKET, + SO_RCVBUF, &got, &gl); + fprintf(stderr, "pcm socket: asked " + "%d, got %d bytes " + "(%.1f s of audio)\n", + want, got, + (double)got / 192000.0); + } + /* argv[0] must stay the program name! */ + av[n++] = (char *)"--pcmfd"; + av[n++] = (char *)"3"; + setenv("SPLITAV", "1", 1); + setenv("RAWCAPTYPE", "1", 1); + setenv("RAWAUDIO", "0x03", 1); + } else { + perror("socketpair(pcm)"); + g_pfd2[0] = -1; + } + } + av[n++] = (char *)"-c"; av[n++] = (char *)fw_mpeg; + av[n++] = (char *)"-o"; av[n++] = (char *)"-"; + /* + * ★ INPUT=svideo selects the S jack instead of the RCA. + * + * ★ MEASURED 2026-10-25 with a recorder in the S + * jack: the jack is luma In1 + chroma In5 + * (0x103=0xd0) and shows a real picture. The RCA + * reaches the decoder as Y/C through the NEC pair + * (luma In2 / chroma In6, 0x103=0xe1). Both use + * 0x401 bits1-2 = 2 (Y/C mode). + * + * INPUT=svideo -> -S <pin> (default pin 0 = chroma In5) + * INPUT=composite -> -C (default) + * INPUTPIN=<n> chroma pin for S-Video (0..3 = In5..In8; + * only In5 is measured) + */ + { + const char *in = getenv("INPUT"); + const char *pin = getenv("INPUTPIN"); + if (in && *in && (!strncmp(in, "sv", 2) || + !strcmp(in, "S"))) + g_svideo = 1; /* so the bar shows the truth */ + if (in && *in && (!strncmp(in, "sv", 2) || + !strcmp(in, "S"))) { + av[n++] = (char *)"-S"; + av[n++] = (char *)(pin && *pin ? pin : "0"); + fprintf(stderr, "input: S-Video " + "(luma In1, chroma In%s)\n", + pin && *pin ? pin : "5"); + } else { + av[n++] = (char *)"-C"; + } + } + if (opt_raw) av[n++] = (char *)"-r"; + /* + * MPEGCAP_EXTRA="--pcm /tmp/live.wav ..." - pass extra + * flags through to kare (space separated). Used to + * combine the one-pass split with the live view: + * SPLITAV=1 RAWCAPTYPE=1 RAWAUDIO=0x03 \ + * MPEGCAP_EXTRA="--pcm /tmp/live.wav" spoon -r + * the video arrives here clean (the PCM records are taken + * out by the splitter) and the audio grows in the WAV. + */ + { + const char *ex = getenv("MPEGCAP_EXTRA"); + if (ex && *ex && n < 24) { + static char extrabuf[512]; + char *tok; + snprintf(extrabuf, sizeof(extrabuf), "%s", ex); + for (tok = strtok(extrabuf, " "); + tok && n < 24; + tok = strtok(NULL, " ")) + av[n++] = tok; + } + } + av[n] = NULL; +#if defined(_WIN32) + /* no fork(): spawn with our stdout already on the pipe */ + cap = win_spawn(kare_path, av, pfd[1]); + if (cap <= 0) { + fprintf(stderr, "cannot start %s\n", kare_path); + return 1; + } +#else + cap = fork(); + if (cap == 0) { + dup2(pfd[1], 1); + close(pfd[0]); + close(pfd[1]); + if (g_pfd2[0] >= 0) { + dup2(g_pfd2[1], 3); + close(g_pfd2[0]); + close(g_pfd2[1]); + } + execv(kare_path, av); + execvp("kare", av); + perror("exec kare"); + _exit(127); + } +#endif + } + if (cap < 0) { perror("fork"); return 1; } + close(pfd[1]); + if (g_pfd2[0] >= 0) { + close(g_pfd2[1]); + fcntl(g_pfd2[0], F_SETFL, + fcntl(g_pfd2[0], F_GETFL) | O_NONBLOCK); + g_pcmin = g_pfd2[0]; + fprintf(stderr, "raw audio: PCM on fd %d\n", g_pcmin); + } + g_fd = pfd[0]; + g_usepipe = 1; + g_ctl = fopen(g_ctlpath, "a"); + if (!g_ctl) + fprintf(stderr, "live control: cannot open %s\n", + g_ctlpath); + else + fprintf(stderr, "live control: %s (press p for keys)\n", + g_ctlpath); + fprintf(stderr, "kare -> pipe (no live file)\n"); + } else { + g_fd = open(live, O_RDONLY); + if (g_fd < 0) { perror(live); return 1; } + } + + /* -f <complete file>: start at byte 0 so stream detection sees the + * pack header + sequence header from the beginning. The live-edge + * jump below only applies to a growing capture file (the pipe needs + * neither: it has no history). */ + if (opt_file) { + struct stat fst; + g_pos = 0; + /* complete file: the whole thing is readable, so the seek + * guard must allow it (it only grows if something appends) */ + if (fstat(g_fd, &fst) == 0) + g_maxpos = fst.st_size; + else + g_maxpos = 0; + } else if (!g_usepipe) { + + /* + * ★ Live edge: NEVER start at byte 0 — that replays the whole + * history as lag. Jump to the newest decodable point: + * MPEG-PS: the last sequence header (00 00 01 b3) preceded by + * its pack header, searched backward in the tail. + * y4m: the last whole FRAME (header line + W*H*3/2). + * This mirrors what kare-live.py does, but in-process. + */ + { + off_t end = lseek(g_fd, 0, SEEK_END); + /* unsigned char: the MPEG start-code bytes (0xb3/0xba) are >127, + * and a signed char comparison against them is always false + * (that is why the old live-edge scan could never match). */ + unsigned char tail[4 << 20]; + off_t start = end - (off_t)sizeof(tail); + if (start < 0) start = 0; + ssize_t got = pread(g_fd, tail, (size_t)(end - start), start); + if (opt_raw) { + /* y4m: locate header line length, then last frame */ + unsigned char *hl = memmem(tail, (size_t)got, "YUV4MPEG2", 9); + if (hl) { + unsigned char *nl = memchr(hl, '\n', + (size_t)got - (hl - tail)); + if (nl) { + size_t hlen = (size_t)(nl - tail) + 1; + int w = 720, h2 = 480; + unsigned char *p = hl; + while (p < nl) { + if (*p == 'W') w = atoi((const char *)p + 1); + else if (*p == 'H') h2 = atoi((const char *)p + 1); + p = memchr(p, ' ', + (size_t)(nl - p)); + if (!p) break; + p++; + } + size_t fb = 6 + + (size_t)w * h2 * 3 / 2; + off_t body_end = start + got - (off_t)hlen; + off_t k = (body_end) / (off_t)fb; + off_t pos = (off_t)hlen + k * (off_t)fb; + if (pos > start + got) pos = start; + g_pos = pos; + if (g_pos > g_maxpos) + g_maxpos = g_pos; + fprintf(stderr, "y4m edge: frame %lld " + "at %lld\n", (long long)k, + (long long)pos); + } + } + } else { + /* MPEG: last 00 00 01 b3 with a pack header before it */ + unsigned char *seq = NULL; + for (ssize_t i = got - 4; i >= 0; i--) { + if (tail[i] == 0 && tail[i+1] == 0 && + tail[i+2] == 1 && tail[i+3] == 0xb3) { + seq = tail + i; + break; + } + } + if (seq) { + /* back up to the preceding pack start */ + unsigned char *pk = NULL; + for (ssize_t j = seq - tail - 1; + j >= 3; j--) { + if (tail[j] == 0 && tail[j+1] == 0 && + tail[j+2] == 1 && tail[j+3] == 0xba) { + pk = tail + j; + break; + } + } + off_t pos = start + (pk ? pk - tail + : seq - tail); + g_pos = pos; + if (g_pos > g_maxpos) + g_maxpos = g_pos; + fprintf(stderr, "mpeg edge: seq at %lld, " + "starting %lld\n", + (long long)(start + (seq - tail)), + (long long)pos); + } else { + g_pos = 0; + g_maxpos = 0; + } + } /* MPEG else */ + } /* live-edge block */ + } /* opt_file else */ + + /* + * Audio device selection is MANUAL on purpose (2026-10-24). + * + * An auto-picker was tried and removed: it can only see what + * /dev/sndstat claims is playable, not which output the speakers are + * actually wired to, so it silently chose the wrong unit. The user + * picks: MPEGVIEW_DSP=/dev/dspN. + * + * One trap is still worth reporting rather than obeying: SDL's OSS + * backend treats a NUMERIC AUDIODEV as a card index and then fails + * with "dsp: No such audio device", which is what a leftover + * `export AUDIODEV=11` looks like. Measured: + * AUDIODEV=11 -> SDL_Init(AUDIO) = -1 + * AUDIODEV=/dev/dsp4 -> 0 + */ + { + const char *dsp = getenv("MPEGVIEW_DSP"); + if (dsp && *dsp) { + if (isdigit((unsigned char)*dsp)) { + char dev[32]; + snprintf(dev, sizeof(dev), "/dev/dsp%d", + atoi(dsp)); + setenv("AUDIODEV", dev, 1); + fprintf(stderr, "audio device: %s (from " + "MPEGVIEW_DSP=%s)\n", dev, dsp); + } else { + setenv("AUDIODEV", dsp, 1); + fprintf(stderr, "audio device: %s " + "(MPEGVIEW_DSP)\n", dsp); + } + } else { + const char *cur = getenv("AUDIODEV"); + if (cur && *cur && isdigit((unsigned char)*cur)) { + fprintf(stderr, "audio device: AUDIODEV=%s is a " + "bare number and SDL cannot open it\n", + cur); + unsetenv("AUDIODEV"); + } + fprintf(stderr, "audio device: %s\n", + getenv("AUDIODEV") ? getenv("AUDIODEV") + : "/dev/dsp (= hw.snd.default_unit)"); + } + } + + + /* + * ★ Bring AUDIO and VIDEO up SEPARATELY (2026-10-23). + * + * SDL_Init(VIDEO|AUDIO) is one transaction: if VIDEO fails, SDL rolls + * the whole call back, so AUDIO is left uninitialised and the next + * SDL_OpenAudioDevice reports only "Audio subsystem is not + * initialized" - with the real reason ("<driver> not available", + * "No such file or directory") thrown away. Measured here: + * SDL_VIDEODRIVER=doesnotexist -> SDL_Init(VIDEO|AUDIO) = -1, + * SDL_WasInit = 0x4000 (EVENTS only, audio gone). + * + * The two subsystems are independent, so init them independently: + * a video problem must not cost the sound, and each failure names + * itself. + */ + { + if (g_audio_on) { + if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) { + g_audio_ok = 0; + fprintf(stderr, "audio init failed: %s " + "(device %s) - no sound this run; " + "set MPEGVIEW_DSP=/dev/dsp4\n", + SDL_GetError(), + getenv("AUDIODEV") ? getenv("AUDIODEV") + : "/dev/dsp"); + } else + g_audio_ok = 1; + if (g_audio_ok) + fprintf(stderr, "audio driver: %s\n", + SDL_GetCurrentAudioDriver() + ? SDL_GetCurrentAudioDriver() : "?"); + } + if (!opt_novideo) { + if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) + fprintf(stderr, "video init failed: %s\n", + SDL_GetError()); + } + if (!g_audio_on && opt_novideo) { + /* -W with no audio requested: still need EVENTS */ + if (SDL_Init(SDL_INIT_EVENTS) < 0) + fprintf(stderr, "SDL_Init: %s\n", SDL_GetError()); + } + } + + if (g_audio_on && g_audio_ok) { + const char *av_ = getenv("MPEGVIEW_AUDIOVOL"); + if (av_) { + int v = atoi(av_); + if (v < 0) v = 0; + if (v > 200) v = 200; + g_again = v; + } + SDL_AudioSpec want; + memset(&want, 0, sizeof(want)); + want.freq = 48000; + want.format = AUDIO_S16SYS; + want.channels = 2; + want.samples = 2048; + g_adev = SDL_OpenAudioDevice(NULL, 0, &want, NULL, 0); + if (!g_adev) + fprintf(stderr, "raw audio: SDL_OpenAudioDevice: %s\n", + SDL_GetError()); + else { + SDL_PauseAudioDevice(g_adev, 0); + fprintf(stderr, "raw audio: 48000 Hz 2 ch via SDL " + "(volume %d%%)\n", g_again); + } + } + + if (g_pcmin >= 0) { + /* + * The splitter emits the y4m header only once it has seen the + * first PCM record (a few tens of ms). ffmpeg's probe would + * otherwise look at an empty pipe and report "video=-1", so + * wait (without consuming) until the pipe actually has data. + */ + struct pollfd pf; + pf.fd = g_fd; + pf.events = POLLIN; + { + /* + * The splitter writes the y4m header immediately but the + * first 518,400-byte frame only once the first PCM record + * arrives (~35 ms). Probing with just those ~50 header + * bytes makes ffmpeg report "video=-1" (measured: + * readable=50), so wait until real frame data is queued. + */ + int waited = 0; + for (;;) { + int avail = 0; + if (poll(&pf, 1, 1000) > 0) + ioctl(g_fd, FIONREAD, &avail); + if (avail >= 65536 || waited >= 5000) + break; + waited += 100; + } + } + } + + unsigned char *aviobuf = av_malloc(PROBE_SIZE); + AVIOContext *avio = avio_alloc_context(aviobuf, PROBE_SIZE, 0, NULL, + fio_read, NULL, fio_seek); + AVFormatContext *fc = avformat_alloc_context(); + fc->pb = avio; + + avformat_network_init(); + int rc = avformat_open_input(&fc, live, NULL, NULL); + if (rc < 0) { + char e[128]; av_strerror(rc, e, sizeof(e)); + fprintf(stderr, "open_input: %s\n", e); + return 1; + } + /* do NOT let it scan the (huge fake) file */ + fc->probesize = 4 * 1024 * 1024; + fc->max_analyze_duration = 2 * AV_TIME_BASE; + if (avformat_find_stream_info(fc, NULL) < 0) + fprintf(stderr, "stream_info failed (continuing)\n"); + + int vi = -1, ai = -1; + for (i = 0; i < (int)fc->nb_streams; i++) { + if (vi < 0 && fc->streams[i]->codecpar->codec_type == + AVMEDIA_TYPE_VIDEO) vi = i; + if (ai < 0 && fc->streams[i]->codecpar->codec_type == + AVMEDIA_TYPE_AUDIO) ai = i; + } + if (opt_novideo) vi = -1; + if (!opt_audio) ai = -1; + fprintf(stderr, "streams: video=%d audio=%d\n", vi, ai); + + AVCodecContext *vc = NULL, *ac = NULL; + const AVCodec *vcod = NULL, *acod = NULL; + if (vi >= 0) { + vcod = avcodec_find_decoder(fc->streams[vi]->codecpar->codec_id); + vc = avcodec_alloc_context3(vcod); + avcodec_parameters_to_context(vc, fc->streams[vi]->codecpar); + avcodec_open2(vc, vcod, NULL); + } + if (ai >= 0) { + acod = avcodec_find_decoder(fc->streams[ai]->codecpar->codec_id); + ac = avcodec_alloc_context3(acod); + avcodec_parameters_to_context(ac, fc->streams[ai]->codecpar); + avcodec_open2(ac, acod, NULL); + + /* audio out: resample to S16 stereo at the stream rate. + * ★ The device may NOT grant what we asked (different rate, + * channels, or sample format). Feeding our S16 stereo @ stream + * rate into a device running anything else = wrong pitch at best, + * full-scale noise at worst. So the resampler targets what SDL + * actually opened (got), not what we wanted. */ + SDL_AudioSpec want; + memset(&want, 0, sizeof(want)); + want.freq = ac->sample_rate; + want.format = AUDIO_S16SYS; + want.channels = ac->ch_layout.nb_channels > 2 ? 2 + : ac->ch_layout.nb_channels; + want.samples = 256; /* ~5 ms */ + want.callback = audio_cb; + SDL_AudioSpec got; + if (SDL_OpenAudio(&want, &got) < 0) { + fprintf(stderr, "SDL audio: %s (audio off)\n", + SDL_GetError()); + ai = -1; + } else if (got.format != AUDIO_S16SYS) { + fprintf(stderr, "SDL audio: device gave format 0x%x, " + "need S16 (audio off)\n", got.format); + SDL_CloseAudio(); + ai = -1; + } else { + int out_ch = (got.channels >= 2) ? 2 : 1; + g_aspec = got; + g_abuf_sz = (size_t)got.freq * (size_t)out_ch * 2 * 2; + g_abuf = calloc(1, g_abuf_sz); + g_abuf_target = (size_t)got.freq * + (size_t)out_ch * 2u / 4u; /* 250 ms */ + { + const char *ab = getenv("MPEGVIEW_ABUF"); + if (ab) { + long ms = atol(ab); + if (ms < 20) ms = 20; + if (ms > 3000) ms = 3000; + g_abuf_target = (size_t)got.freq * + (size_t)out_ch * 2u * + (size_t)ms / 1000u; + } + } + fprintf(stderr, "audio buffer target: %zu ms " + "(ring %zu ms, dev samples %u)\n", + g_abuf_target * 1000u / + ((size_t)got.freq * (size_t)out_ch * 2u), + g_abuf_sz * 1000u / + ((size_t)got.freq * (size_t)out_ch * 2u), + got.samples); + g_amtx = SDL_CreateMutex(); + SDL_PauseAudio(0); + fprintf(stderr, "audio out: %d Hz %d ch (OSS)\n", + got.freq, got.channels); + audio_filters_init((double)got.freq); + /* stash the granted layout for the resampler below */ + ac->sample_rate = ac->sample_rate; /* unchanged: input side */ + g_aspec.channels = (Uint8)out_ch; + } + } + struct SwrContext *swr = NULL; + static int g_out_ch = 2, g_out_rate = 48000; + if (ai >= 0) { + AVChannelLayout out_ch = + (g_aspec.channels == 1) ? (AVChannelLayout)AV_CHANNEL_LAYOUT_MONO + : (AVChannelLayout)AV_CHANNEL_LAYOUT_STEREO; + g_out_ch = (g_aspec.channels == 1) ? 1 : 2; + g_out_rate = g_aspec.freq; + AVChannelLayout in_ch = (ac->ch_layout.nb_channels == 1) + ? (AVChannelLayout)AV_CHANNEL_LAYOUT_MONO + : (AVChannelLayout)AV_CHANNEL_LAYOUT_STEREO; + swr_alloc_set_opts2(&swr, + &out_ch, AV_SAMPLE_FMT_S16, g_out_rate, + &in_ch, ac->sample_fmt, ac->sample_rate, + 0, NULL); + swr_init(swr); + } + + AVPacket *pkt = av_packet_alloc(); + AVFrame *fr = av_frame_alloc(); + int64_t a_pts0 = AV_NOPTS_VALUE, v_pts0 = AV_NOPTS_VALUE; + int64_t last_vpts = AV_NOPTS_VALUE; + + while (!g_stop) { + /* raw PCM from kare (fd 3) -> SDL queue, in parallel with the + * video below (ivtv's two-device split) */ + if (g_pcmin >= 0) { + for (;;) { + ssize_t r = read(g_pcmin, g_pcmbuf, + sizeof(g_pcmbuf)); + if (r > 0) { + /* + * ★ Level meter (2026-10-23). "The sound + * has no range" has two completely different + * causes and only a meter separates them: + * - the raw PCM already sits at 0 dBFS + * (analogue input too hot -> the whole + * programme is compressed against the + * rail, and no digital gain helps), or + * - the level is fine and the volume + * scaling is eating the resolution + * (MPEGVIEW_AUDIOVOL=25 is -12 dB in + * software on int16 = two bits gone). + * Printed every ~2 s, measured BEFORE the + * scaling, so it describes the stream. + */ + { + static unsigned long nacc; + static unsigned long bytes_acc; + static double peak, sq; + int16_t *m = (int16_t *)g_pcmbuf; + size_t k, ns = (size_t)r / 2; + for (k = 0; k < ns; k++) { + double v = m[k] < 0 ? + -(double)m[k] : (double)m[k]; + if (v > peak) peak = v; + sq += v * v; + } + nacc += ns; + bytes_acc += (unsigned long)r; + /* 48 kHz stereo s16: one second */ + if (nacc >= 96000) { + double rms = sqrt(sq / nacc); + /* + * kB/s is the tell for DROPPED + * records: the capture writes + * 48 kHz x 2 ch x 2 B = 187.5 + * KiB/s, and kare drops a + * record rather than block when + * the pipe is full. A dip here + * is an audible click/gap. + */ + fprintf(stderr, "audio level: " + "peak %.1f dBFS rms %.1f " + "dBFS crest %.1f dB " + "%.1f kB/s (gain %d%%)\n", + 20 * log10((peak + 1) / 32768.0), + 20 * log10((rms + 1) / 32768.0), + 20 * log10((peak + 1) / (rms + 1)), + (double)bytes_acc / 1024.0, g_again); + nacc = 0; + bytes_acc = 0; + peak = 0; + sq = 0; + } + } + if (g_adev) { + if (g_again != 100) { + int16_t *sp = + (int16_t *)g_pcmbuf; + size_t n = + (size_t)r / 2, q; + for (q = 0; q < n; q++) { + int32_t v = + (int32_t)sp[q] * + g_again / 100; + if (v > 32767) v = 32767; + if (v < -32768) v = -32768; + sp[q] = (int16_t)v; + } + } + SDL_QueueAudio(g_adev, + g_pcmbuf, (Uint32)r); + } + } else { + break; + } + } + } + /* housekeep window events + live parameter keys */ + if (!opt_novideo) { + SDL_Event ev; + while (SDL_PollEvent(&ev)) { + if (ev.type == SDL_QUIT) + g_stop = 1; + else if (ev.type == SDL_MOUSEBUTTONDOWN && + ev.button.button == SDL_BUTTON_LEFT) + bar_click(ev.button.x, ev.button.y); + else if (ev.type == SDL_KEYDOWN) + key_action(ev.key.keysym.sym, + (ev.key.keysym.mod & KMOD_SHIFT) + ? 1 : 0); + } + } + rc = av_read_frame(fc, pkt); + if (rc == AVERROR(EAGAIN)) { usleep(POLL_US); continue; } + if (rc < 0) { + /* treat as transient (growing file) */ + usleep(POLL_US); + continue; + } + { + static double t_log; + double tn = SDL_GetTicks() / 1000.0; + if (tn - t_log > 2.0 && g_abuf_target) { + size_t p = audio_pending(); + double denom = (double)g_out_rate * + (double)g_out_ch * 2.0; + t_log = tn; + fprintf(stderr, "audio-ahead: %.0f ms " + "(pending %zu B) video-delay %.0f ms " + "(queued %d)\n", + denom > 0 ? p / denom * 1000.0 : 0.0, p, + vdq_delay_ms(), g_vq_n); + } + } + vdq_flush(); + if (pkt->stream_index == vi && vc) { + if (avcodec_send_packet(vc, pkt) >= 0) { + while (avcodec_receive_frame(vc, fr) >= 0) { + vdq_push(fr); + last_vpts = fr->pts; + av_frame_unref(fr); + } + } + } else if (pkt->stream_index == ai && ac) { + if (avcodec_send_packet(ac, pkt) >= 0) { + while (avcodec_receive_frame(ac, fr) >= 0) { + if (a_pts0 == AV_NOPTS_VALUE) + a_pts0 = fr->pts; + /* pace: if the audio ring is way ahead + * (join), drop; if full, wait */ + int guard = 0; + while (audio_pending() > + g_abuf_target && + !g_stop && guard++ < 2000) + usleep(1000); + /* convert with buffer */ + int dstcap = fr->nb_samples * 4; + uint8_t *dst = malloc((size_t)dstcap); + uint8_t *d2[1] = { dst }; + int n2 = swr_convert(swr, d2, + dstcap / 4, + (const uint8_t **)fr->data, + fr->nb_samples); + if (n2 > 0) { + audio_filters_apply( + (int16_t *)dst, + (size_t)n2 * + (size_t)g_out_ch); + } + if (0) { + /* + * ★ One-pole DC blocker on the + * PCM sent to OSS (2026-10-16): + * the capture carries a + * low-frequency rumble that the + * encoder path leaves in. + * ~30 Hz corner; the audible + * band is untouched. + * MPEGVIEW_NODC=1 disables. + */ + int16_t *pp = (int16_t *)dst; + int q; + for (q = 0; q < n2 * g_out_ch; q++) { + float x = (float)pp[q]; + float y = x - dc_x1 + + 0.9950f * dc_y1; + dc_x1 = x; + dc_y1 = y; + if (y > 32767.0f) y = 32767.0f; + if (y < -32768.0f) y = -32768.0f; + pp[q] = (int16_t)y; + } + } + if (n2 > 0) { + size_t nb = (size_t)n2 * + (size_t)g_out_ch * 2; + size_t first = + g_abuf_sz - g_awrite; + if (first > nb) first = nb; + memcpy(g_abuf + g_awrite, dst, + first); + if (nb > first) + memcpy(g_abuf, + dst + first, + nb - first); + g_awrite = (g_awrite + nb) % + g_abuf_sz; + } + free(dst); + av_frame_unref(fr); + } + } + } + av_packet_unref(pkt); + (void)v_pts0; (void)last_vpts; (void)a_pts0; + } + + fprintf(stderr, "stopping\n"); + /* + * Close our end of the pipe FIRST: kare may be blocked writing a + * raw (15 MB/s) frame into a full pipe, and while we hold the read + * end open it can never see the close -- it would sit there instead + * of running its own shutdown (which is where STOP_CAPTURE is sent). + * Then give it a bounded grace period before SIGKILL, so a stuck + * child can never hang the player. + */ + if (g_usepipe && g_fd >= 0) { + close(g_fd); + g_fd = -1; + } + /* + * Graceful shutdown through the control channel: kare's "Q" command + * stops the capture properly, which is what sends CX2341X_ENC_STOP_CAPTURE + * (0x82) and leaves the encoder idle for the next run. Works on every + * platform -- Windows has no SIGTERM, so this is the only clean stop there. + */ + if (g_ctl && cap > 0) + ctl_send("Q"); + if (cap > 0) { + int i; + kill(cap, SIGTERM); + for (i = 0; i < 40; i++) { /* up to ~2 s */ + if (waitpid(cap, NULL, WNOHANG) == cap) + break; + usleep(50000); + } + if (i == 40) { + fprintf(stderr, "kare did not exit; killing it\n"); + kill(cap, SIGKILL); + waitpid(cap, NULL, 0); + } + } + return 0; +} |
